prjct-cli 1.23.0 → 1.24.1

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.
@@ -1,1745 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import { fileURLToPath as __fileURLToPath } from 'url';
3
- import { dirname as __pathDirname } from 'path';
4
- const __filename = __fileURLToPath(import.meta.url);
5
- const __dirname = __pathDirname(__filename);
6
- var zy=Object.create;var hr=Object.defineProperty;var Jy=Object.getOwnPropertyDescriptor;var Wy=Object.getOwnPropertyNames;var By=Object.getPrototypeOf,Vy=Object.prototype.hasOwnProperty;var l=(r,e)=>hr(r,"name",{value:e,configurable:!0}),Tp=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),Ep=r=>e=>{var t=r[e];if(t)return t();throw new Error("Module not found in bundle: "+e)};var y=(r,e)=>()=>(r&&(e=r(r=0)),e);var qy=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ne=(r,e)=>{for(var t in e)hr(r,t,{get:e[t],enumerable:!0})},jp=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Wy(e))!Vy.call(r,s)&&s!==t&&hr(r,s,{get:()=>e[s],enumerable:!(n=Jy(e,s))||n.enumerable});return r};var Ky=(r,e,t)=>(t=r!=null?zy(By(r)):{},jp(e||!r||!r.__esModule?hr(t,"default",{value:r,enumerable:!0}):t,r)),bt=r=>jp(hr({},"__esModule",{value:!0}),r);import{z as Wt}from"zod";function Ap(r,e){let t=r.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<3;s++){let o=t[s]??0,i=n[s]??0;if(o<i)return-1;if(o>i)return 1}return 0}var hj,yj,wj,yr,kj,wr=y(()=>{"use strict";hj=Wt.enum(["opus","sonnet","haiku"]),yj=Wt.enum(["2.5-pro","2.5-flash","2.0-flash"]),wj=Wt.string().min(1),yr=Wt.object({provider:Wt.string(),model:Wt.string(),cliVersion:Wt.string().optional(),recordedAt:Wt.string()}),kj=Wt.object({preferredModel:Wt.string().optional(),lastAnalysisModel:yr.optional()});l(Ap,"compareSemver")});function Ip(r){return r instanceof Error&&"code"in r}function k(r){return Ip(r)&&r.code==="ENOENT"}function w(r){return r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}function So(r){if(r instanceof Error)return r.stack}var M=y(()=>{"use strict";l(Ip,"isNodeError");l(k,"isNotFoundError");l(w,"getErrorMessage");l(So,"getErrorStack")});import $p from"node:fs/promises";async function Mp(r,e){let t;try{t=await $p.readFile(r,"utf-8")}catch(o){if(k(o))return null;throw o}let n;try{n=JSON.parse(t)}catch{return await Dp(r,t),Rp(r,"Malformed JSON"),null}let s=e.safeParse(n);return s.success?n:(await Dp(r,t),Rp(r,Xy(s.error)),null)}async function Dp(r,e){let t=`${r}.backup`;try{await $p.writeFile(t,e,"utf-8")}catch{}}function Rp(r,e){console.error(`[prjct] Warning: Corrupted storage file: ${r}`),console.error(`[prjct] Reason: ${e}`),console.error("[prjct] A .backup file has been created. Returning defaults.")}function Xy(r){return r.issues.slice(0,3).map(e=>`${e.path.join(".")}: ${e.message}`).join("; ")}var Fp=y(()=>{"use strict";M();l(Mp,"safeRead");l(Dp,"createBackup");l(Rp,"logCorruption");l(Xy,"formatZodError")});var ae={};Ne(ae,{appendLine:()=>Da,appendToFile:()=>Qy,atomicWrite:()=>Yy,copyFile:()=>rw,deleteDir:()=>tw,deleteFile:()=>ew,dirExists:()=>bo,ensureDir:()=>dt,fileExists:()=>C,getFileExtension:()=>cw,getFileModifiedTime:()=>sw,getFileNameWithoutExtension:()=>lw,getFileSize:()=>nw,listFiles:()=>ks,moveFile:()=>ow,prependToFile:()=>Zy,readFile:()=>ws,readJson:()=>Un,readLines:()=>iw,writeFile:()=>Op,writeJson:()=>kr,writeLines:()=>aw});import de from"node:fs/promises";import ys from"node:path";async function Un(r,e=null,t){if(t)return await Mp(r,t)??e;try{let n=await de.readFile(r,"utf-8");return JSON.parse(n)}catch(n){if(k(n))return e;throw n}}async function kr(r,e,t=2){let n=JSON.stringify(e,null,t);await de.writeFile(r,n,"utf-8")}async function ws(r,e=""){try{return await de.readFile(r,"utf-8")}catch(t){if(k(t))return e;throw t}}async function Op(r,e){let t=ys.dirname(r);await de.mkdir(t,{recursive:!0}),await de.writeFile(r,e,"utf-8")}async function Yy(r,e){let t=ys.dirname(r);await de.mkdir(t,{recursive:!0});let n=`${r}.${Date.now()}.tmp`;await de.writeFile(n,e,"utf-8"),await de.rename(n,r)}async function Qy(r,e){await de.appendFile(r,e,"utf-8")}async function Da(r,e){let t=ys.dirname(r);await de.mkdir(t,{recursive:!0}),await de.appendFile(r,`${e}
7
- `,"utf-8")}async function Zy(r,e){try{let t=await de.readFile(r,"utf-8");await de.writeFile(r,e+t,"utf-8")}catch(t){if(k(t))await de.writeFile(r,e,"utf-8");else throw t}}async function C(r){try{return await de.access(r),!0}catch(e){if(k(e))return!1;throw e}}async function bo(r){try{return(await de.stat(r)).isDirectory()}catch(e){if(k(e))return!1;throw e}}async function dt(r){await de.mkdir(r,{recursive:!0})}async function ew(r){try{return await de.unlink(r),!0}catch(e){if(k(e))return!1;throw e}}async function tw(r){try{return await de.rm(r,{recursive:!0,force:!0}),!0}catch(e){if(k(e))return!1;throw e}}async function ks(r,e={}){try{let n=await de.readdir(r,{withFileTypes:!0});return e.filesOnly&&(n=n.filter(s=>s.isFile())),e.dirsOnly&&(n=n.filter(s=>s.isDirectory())),e.extension&&(n=n.filter(s=>s.name.endsWith(e.extension))),n.map(s=>s.name)}catch(t){if(k(t))return[];throw t}}async function nw(r){return(await de.stat(r)).size}async function sw(r){return(await de.stat(r)).mtime}async function rw(r,e){await de.copyFile(r,e)}async function ow(r,e){await de.rename(r,e)}async function iw(r){return(await ws(r,"")).split(`
8
- `)}async function aw(r,e){let t=e.join(`
9
- `);await Op(r,t)}function cw(r){return ys.extname(r)}function lw(r){return ys.basename(r,ys.extname(r))}var me=y(()=>{"use strict";Fp();M();l(Un,"readJson");l(kr,"writeJson");l(ws,"readFile");l(Op,"writeFile");l(Yy,"atomicWrite");l(Qy,"appendToFile");l(Da,"appendLine");l(Zy,"prependToFile");l(C,"fileExists");l(bo,"dirExists");l(dt,"ensureDir");l(ew,"deleteFile");l(tw,"deleteDir");l(ks,"listFiles");l(nw,"getFileSize");l(sw,"getFileModifiedTime");l(rw,"copyFile");l(ow,"moveFile");l(iw,"readLines");l(aw,"writeLines");l(cw,"getFileExtension");l(lw,"getFileNameWithoutExtension")});import Po from"node:fs/promises";import uw from"node:os";import _p from"node:path";async function Lp(){try{let r=await Po.readFile(Ra,"utf-8"),e=JSON.parse(r);return!e.timestamp||!e.detection||Date.now()-new Date(e.timestamp).getTime()>pw?null:e.detection}catch{return null}}async function Up(r){let e={timestamp:new Date().toISOString(),detection:r};await Po.mkdir(Np,{recursive:!0}),await Po.writeFile(Ra,JSON.stringify(e,null,2))}async function Hp(){try{await Po.unlink(Ra)}catch{}}var Np,Ra,pw,$a=y(()=>{"use strict";Np=_p.join(uw.homedir(),".prjct-cli","cache"),Ra=_p.join(Np,"providers.json"),pw=600*1e3;l(Lp,"readProviderCache");l(Up,"writeProviderCache");l(Hp,"invalidateProviderCache")});var mt={};Ne(mt,{AntigravityProvider:()=>Fa,ClaudeProvider:()=>Co,CursorProvider:()=>Jp,GeminiProvider:()=>Ma,Providers:()=>$e,WindsurfProvider:()=>Wp,detectAllProviders:()=>Pt,detectAntigravity:()=>bs,detectCursorProject:()=>Vp,detectProvider:()=>vo,detectWindsurfProject:()=>qp,getActiveProvider:()=>hw,getCommandsDir:()=>Cw,getGlobalContextPath:()=>Sw,getGlobalSettingsPath:()=>bw,getProjectCommandsPath:()=>vw,getProviderBranding:()=>xo,getSkillsPath:()=>Pw,hasProviderConfig:()=>yw,needsCursorRouterRegeneration:()=>ww,needsWindsurfRouterRegeneration:()=>kw,selectProvider:()=>Oa,validateCliVersion:()=>Bp});import{exec as dw}from"node:child_process";import Ss from"node:os";import Xe from"node:path";import{promisify as mw}from"node:util";async function gw(r){try{let{stdout:e}=await Gp(`which ${r}`,{timeout:zp});return e.trim()}catch{return null}}async function fw(r){try{let{stdout:e}=await Gp(`${r} --version`,{timeout:zp}),t=e.match(/\d+\.\d+\.\d+/);return t?t[0]:e.trim()}catch{return null}}async function vo(r){let e=$e[r];if(!e.cliCommand)return{installed:!1};let t=await gw(e.cliCommand);if(!t)return{installed:!1};let n=await fw(e.cliCommand),s=Bp(r,n||void 0);return{installed:!0,version:n||void 0,path:t,versionWarning:s||void 0}}function Bp(r,e){let t=$e[r];return!t.minCliVersion||!e?null:Ap(e,t.minCliVersion)<0?`\u26A0\uFE0F ${t.displayName} v${e} is below minimum v${t.minCliVersion}. Some features may not work correctly.`:null}async function Pt(r=!1){if(!r){let s=await Lp();if(s)return s}let[e,t]=await Promise.all([vo("claude"),vo("gemini")]),n={claude:e,gemini:t};return await Up(n).catch(()=>{}),n}async function hw(r){if(r&&$e[r])return $e[r];let e=await Pt();return e.claude.installed&&!e.gemini.installed?Co:e.gemini.installed&&!e.claude.installed?Ma:Co}async function yw(r){let e=$e[r];return e.configDir?C(e.configDir):!1}function xo(r){return{commitFooter:"Generated with [p/](https://www.prjct.app/)",signature:{claude:"\u26A1 prjct + Claude",gemini:"\u26A1 prjct + Gemini",cursor:"\u26A1 prjct + Cursor",antigravity:"\u26A1 prjct + Antigravity",windsurf:"\u26A1 prjct + Windsurf"}[r]||"\u26A1 prjct"}}async function Vp(r){let e=Xe.join(r,".cursor"),t=Xe.join(e,"rules"),n=Xe.join(t,"prjct.mdc"),[s,o]=await Promise.all([C(e),C(n)]);return{detected:s,routerInstalled:o,projectRoot:s?r:void 0}}async function ww(r){let e=await Vp(r);return e.detected&&!e.routerInstalled}async function qp(r){let e=Xe.join(r,".windsurf"),t=Xe.join(e,"rules"),n=Xe.join(t,"prjct.md"),[s,o]=await Promise.all([C(e),C(n)]);return{detected:s,routerInstalled:o,projectRoot:s?r:void 0}}async function kw(r){let e=await qp(r);return e.detected&&!e.routerInstalled}async function bs(){let r=Fa.configDir;if(!r)return{installed:!1,skillInstalled:!1};let e=Xe.join(r,"skills","prjct","SKILL.md"),[t,n]=await Promise.all([C(r),C(e)]);return{installed:t,skillInstalled:n,configPath:t?r:void 0}}function Sw(r){let e=$e[r];return e.configDir?Xe.join(e.configDir,e.contextFile):null}function bw(r){let e=$e[r];return!e.configDir||!e.settingsFile?null:Xe.join(e.configDir,e.settingsFile)}function Pw(r){return $e[r].skillsDir}function Cw(r){return $e[r].commandsDir}function vw(r,e){let t=$e[r];return Xe.join(e,t.commandsDir)}async function Oa(){let r=await Pt(),e=r.claude.installed,t=r.gemini.installed;return!e&&!t?{provider:"claude",userSelected:!1,detection:r}:e&&!t?{provider:"claude",userSelected:!1,detection:r}:t&&!e?{provider:"gemini",userSelected:!1,detection:r}:{provider:"claude",userSelected:!0,detection:r}}var Gp,zp,Co,Ma,Fa,Jp,Wp,$e,He=y(()=>{"use strict";wr();me();$a();Gp=mw(dw),zp=2e3,Co={name:"claude",displayName:"Claude Code",cliCommand:"claude",configDir:Xe.join(Ss.homedir(),".claude"),contextFile:"CLAUDE.md",skillsDir:Xe.join(Ss.homedir(),".claude","skills"),commandsDir:".claude/commands",commandFormat:"md",settingsFile:"settings.json",projectSettingsFile:"settings.local.json",ignoreFile:".claudeignore",websiteUrl:"https://www.anthropic.com/claude",docsUrl:"https://docs.anthropic.com/claude-code",defaultModel:"sonnet",supportedModels:["opus","sonnet","haiku"],minCliVersion:"1.0.0"},Ma={name:"gemini",displayName:"Gemini CLI",cliCommand:"gemini",configDir:Xe.join(Ss.homedir(),".gemini"),contextFile:"GEMINI.md",skillsDir:Xe.join(Ss.homedir(),".gemini","skills"),commandsDir:".gemini/commands",commandFormat:"toml",settingsFile:"settings.json",projectSettingsFile:"settings.json",ignoreFile:".geminiignore",websiteUrl:"https://geminicli.com",docsUrl:"https://geminicli.com/docs",defaultModel:"2.5-flash",supportedModels:["2.5-pro","2.5-flash","2.0-flash"],minCliVersion:"1.0.0"},Fa={name:"antigravity",displayName:"Google Antigravity",cliCommand:null,configDir:Xe.join(Ss.homedir(),".gemini","antigravity"),contextFile:"ANTIGRAVITY.md",skillsDir:Xe.join(Ss.homedir(),".gemini","antigravity","global_skills"),commandsDir:".agent/skills",commandFormat:"md",settingsFile:"mcp_config.json",projectSettingsFile:null,ignoreFile:".agentignore",websiteUrl:"https://gemini.google.com/app/antigravity",docsUrl:"https://gemini.google.com/app/antigravity",defaultModel:null,supportedModels:[],minCliVersion:null},Jp={name:"cursor",displayName:"Cursor IDE",cliCommand:null,configDir:null,contextFile:"prjct.mdc",skillsDir:null,commandsDir:".cursor/commands",rulesDir:".cursor/rules",commandFormat:"md",settingsFile:null,projectSettingsFile:null,ignoreFile:".cursorignore",isProjectLevel:!0,websiteUrl:"https://cursor.com",docsUrl:"https://cursor.com/docs",defaultModel:null,supportedModels:[],minCliVersion:null},Wp={name:"windsurf",displayName:"Windsurf IDE",cliCommand:null,configDir:null,contextFile:"prjct.md",skillsDir:null,commandsDir:".windsurf/workflows",rulesDir:".windsurf/rules",commandFormat:"md",settingsFile:null,projectSettingsFile:null,ignoreFile:".windsurfignore",isProjectLevel:!0,websiteUrl:"https://windsurf.com",docsUrl:"https://docs.windsurf.com",defaultModel:null,supportedModels:[],minCliVersion:null},$e={claude:Co,gemini:Ma,cursor:Jp,antigravity:Fa,windsurf:Wp};l(gw,"whichCommand");l(fw,"getCliVersion");l(vo,"detectProvider");l(Bp,"validateCliVersion");l(Pt,"detectAllProviders");l(hw,"getActiveProvider");l(yw,"hasProviderConfig");l(xo,"getProviderBranding");l(Vp,"detectCursorProject");l(ww,"needsCursorRouterRegeneration");l(qp,"detectWindsurfProject");l(kw,"needsWindsurfRouterRegeneration");l(bs,"detectAntigravity");l(Sw,"getGlobalContextPath");l(bw,"getGlobalSettingsPath");l(Pw,"getSkillsPath");l(Cw,"getCommandsDir");l(vw,"getProjectCommandsPath");l(Oa,"selectProvider")});import{z as ge}from"zod";function xw(r){return r instanceof Ps}function Y(r){return xw(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var Cs,Vj,qj,Kj,Xj,Yj,Qj,Ps,To,Eo,Sr,an=y(()=>{"use strict";Cs={create(r,e){class t extends Error{static{l(this,"TypedError")}errorName;data;isOperational=!0;constructor(s){let o=e.parse(s);super(`${r}: ${JSON.stringify(o)}`),this.name=r,this.errorName=r,this.data=o,Error.captureStackTrace?.(this,this.constructor)}static throw(s){throw new t(s)}static is(s){return s instanceof t&&s.errorName===r}static create(s){return new t(s)}}return t}},Vj=Cs.create("FileError",ge.object({path:ge.string(),operation:ge.enum(["read","write","delete","create","copy"]),reason:ge.string().optional()})),qj=Cs.create("ValidationError",ge.object({field:ge.string(),expected:ge.string(),received:ge.string().optional(),message:ge.string().optional()})),Kj=Cs.create("PermissionError",ge.object({action:ge.string(),resource:ge.string(),reason:ge.string().optional()})),Xj=Cs.create("TaskError",ge.object({taskId:ge.string().optional(),operation:ge.enum(["create","update","complete","pause","resume","delete"]),reason:ge.string()})),Yj=Cs.create("SessionError",ge.object({sessionId:ge.string().optional(),reason:ge.string()})),Qj=Cs.create("SyncError",ge.object({projectId:ge.string().optional(),operation:ge.enum(["push","pull","auth","connect"]),reason:ge.string()})),Ps=class extends Error{static{l(this,"PrjctError")}code;isOperational;constructor(e,t="PRJCT_ERROR"){super(e),this.name="PrjctError",this.code=t,this.isOperational=!0,Error.captureStackTrace?.(this,this.constructor)}},To=class r extends Ps{static{l(this,"ProjectError")}constructor(e,t="PROJECT_ERROR"){super(e,t),this.name="ProjectError"}static notInitialized(){return new r("Project not initialized. Run /p:init first.","PROJECT_NOT_INIT")}static notFound(e){return new r(`Project not found: ${e}`,"PROJECT_NOT_FOUND")}static invalidId(e){return new r(`Invalid project ID: ${e}`,"PROJECT_INVALID_ID")}},Eo=class r extends Ps{static{l(this,"TemplateError")}constructor(e,t="TEMPLATE_ERROR"){super(e,t),this.name="TemplateError"}static notFound(e){return new r(`Template not found: ${e}.md`,"TEMPLATE_NOT_FOUND")}static parseFailed(e){return new r(`Failed to parse template: ${e}`,"TEMPLATE_PARSE_ERROR")}},Sr=class r extends Ps{static{l(this,"AgentError")}constructor(e,t="AGENT_ERROR"){super(e,t),this.name="AgentError"}static notSupported(e){return new r(`Unsupported agent type: ${e}`,"AGENT_NOT_SUPPORTED")}static initFailed(e){return new r(`Agent initialization failed: ${e}`,"AGENT_INIT_FAILED")}};l(xw,"isPrjctError");l(Y,"getErrorMessage")});var U={};Ne(U,{calculateDuration:()=>Mw,formatDate:()=>jo,formatDuration:()=>br,formatMonth:()=>Ew,getDateKey:()=>jw,getDateRange:()=>Dw,getDaysAgo:()=>bn,getDaysFromNow:()=>Iw,getEndOfDay:()=>Ow,getStartOfDay:()=>Fw,getTimestamp:()=>b,getTodayKey:()=>Ao,getYearMonthDay:()=>_a,isToday:()=>Rw,isWithinLastDays:()=>$w,parseDate:()=>Aw,toRelative:()=>gt});import{formatDistanceToNowStrict as Tw}from"date-fns";function jo(r){let e=r.getFullYear(),t=(r.getMonth()+1).toString().padStart(2,"0"),n=r.getDate().toString().padStart(2,"0");return`${e}-${t}-${n}`}function Ew(r){let e=r.getFullYear(),t=(r.getMonth()+1).toString().padStart(2,"0");return`${e}-${t}`}function Ao(){return jo(new Date)}function jw(r){return jo(r)}function _a(r){return{year:r.getFullYear().toString(),month:(r.getMonth()+1).toString().padStart(2,"0"),day:r.getDate().toString().padStart(2,"0")}}function Aw(r){return new Date(r)}function b(){return new Date().toISOString()}function bn(r){let e=new Date;return e.setDate(e.getDate()-r),e}function Iw(r){let e=new Date;return e.setDate(e.getDate()+r),e}function Dw(r,e){let t=[],n=new Date(r);for(;n<=e;)t.push(new Date(n)),n=new Date(n.getFullYear(),n.getMonth(),n.getDate()+1);return t}function Rw(r){return jo(r)===Ao()}function $w(r,e){let t=bn(e);return r>=t}function br(r){let e=Math.floor(r/1e3),t=Math.floor(e/60),n=Math.floor(t/60),s=Math.floor(n/24);return s>0?`${s}d ${n%24}h`:n>0?`${n}h ${t%60}m`:t>0?`${t}m`:`${e}s`}function Mw(r,e=new Date){let t=e.getTime()-r.getTime();return br(t)}function Fw(r){let e=new Date(r);return e.setHours(0,0,0,0),e}function Ow(r){let e=new Date(r);return e.setHours(23,59,59,999),e}function gt(r){let e=typeof r=="string"?new Date(r):r;return Tw(e,{addSuffix:!0})}var ne=y(()=>{"use strict";l(jo,"formatDate");l(Ew,"formatMonth");l(Ao,"getTodayKey");l(jw,"getDateKey");l(_a,"getYearMonthDay");l(Aw,"parseDate");l(b,"getTimestamp");l(bn,"getDaysAgo");l(Iw,"getDaysFromNow");l(Dw,"getDateRange");l(Rw,"isToday");l($w,"isWithinLastDays");l(br,"formatDuration");l(Mw,"calculateDuration");l(Fw,"getStartOfDay");l(Ow,"getEndOfDay");l(gt,"toRelative")});var Ha={};Ne(Ha,{PACKAGE_ROOT:()=>ce,VERSION:()=>se,compareVersions:()=>Kp,getPackageInfo:()=>_w,getPackageRoot:()=>Ua,getVersion:()=>Cr,isCompatible:()=>Nw,needsMigration:()=>Lw});import Na from"node:fs";import Do from"node:path";function Ua(){if(Pr)return Pr;let r=__dirname;for(let e=0;e<5;e++){let t=Do.join(r,"package.json");if(Na.existsSync(t))try{if(JSON.parse(Na.readFileSync(t,"utf-8")).name==="prjct-cli")return Pr=r,r}catch{}r=Do.dirname(r)}return Pr=Do.join(__dirname,"..","..",".."),Pr}function Cr(){if(Io)return Io;try{let r=Do.join(Ua(),"package.json"),e=JSON.parse(Na.readFileSync(r,"utf-8"));return Io=e.version,La=e,Io}catch(r){return console.error("Failed to read version from package.json:",w(r)),"0.0.0"}}function _w(){return La||Cr(),La}function Kp(r,e){let t=r.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<Math.max(t.length,n.length);s++){let o=t[s]||0,i=n[s]||0;if(o>i)return 1;if(o<i)return-1}return 0}function Nw(r){let e=Cr(),[t,n]=e.split(".").map(Number),[s,o]=r.split(".").map(Number);return t===s&&n===o}function Lw(r,e=null){let t=e||Cr();return Kp(r,t)<0}var Io,La,Pr,se,ce,st=y(()=>{"use strict";M();Io=null,La=null,Pr=null;l(Ua,"getPackageRoot");l(Cr,"getVersion");l(_w,"getPackageInfo");l(Kp,"compareVersions");l(Nw,"isCompatible");l(Lw,"needsMigration");se=Cr(),ce=Ua()});import{exec as Uw}from"node:child_process";import{promisify as Hw}from"node:util";async function Ro(r){try{let{stdout:e}=await Gw(r,{timeout:5e3});return{success:!0,output:e.trim()}}catch{return{success:!1,output:""}}}async function zw(){let r=await Ro("gh api user --jq .login");return r.success&&r.output||(r=await Ro("git config --global github.user"),r.success&&r.output)?r.output:null}async function Jw(){let r=await Ro("git config user.name");return r.success&&r.output?r.output:null}async function Ww(){let r=await Ro("git config user.email");return r.success&&r.output?r.output:null}async function vs(){let[r,e,t]=await Promise.all([zw(),Jw(),Ww()]);return{github:r,email:t,name:e||r||"Unknown"}}var Gw,$o=y(()=>{"use strict";Gw=Hw(Uw);l(Ro,"execCommand");l(zw,"detectGitHubUsername");l(Jw,"detectGitName");l(Ww,"detectGitEmail");l(vs,"detect")});import Bw from"node:crypto";import Bt from"node:fs/promises";import za from"node:os";import O from"node:path";import{globSync as Vw}from"glob";var Ja,qw,P,ee=y(()=>{"use strict";ne();me();Ja=class{static{l(this,"PathManager")}globalBaseDir;globalProjectsDir;globalConfigDir;constructor(){let e=process.env.PRJCT_CLI_HOME?.trim();this.globalBaseDir=e?O.resolve(e):O.join(za.homedir(),".prjct-cli"),this.globalProjectsDir=O.join(this.globalBaseDir,"projects"),this.globalConfigDir=O.join(this.globalBaseDir,"config")}setGlobalBaseDir(e){this.globalBaseDir=O.resolve(e),this.globalProjectsDir=O.join(this.globalBaseDir,"projects"),this.globalConfigDir=O.join(this.globalBaseDir,"config")}generateProjectId(e){return Bw.randomUUID()}getGlobalBasePath(){return this.globalBaseDir}getGlobalProjectPath(e){return O.join(this.globalProjectsDir,e)}getLocalConfigPath(e){return O.join(e,".prjct","prjct.config.json")}getGlobalProjectConfigPath(e){return O.join(this.getGlobalProjectPath(e),"project.json")}getLegacyPrjctPath(e){return O.join(e,".prjct")}async hasLegacyStructure(e){let t=this.getLegacyPrjctPath(e);return await bo(t)}async hasConfig(e){let t=this.getLocalConfigPath(e);return await C(t)}async ensureGlobalStructure(){await dt(this.globalBaseDir),await dt(this.globalProjectsDir),await dt(this.globalConfigDir)}async ensureProjectStructure(e){await this.ensureGlobalStructure();let t=this.getGlobalProjectPath(e),n=["core","progress","planning","analysis","memory","agents"];for(let s of n)await dt(O.join(t,s));return await dt(O.join(t,"planning","tasks")),await dt(O.join(t,"sessions")),t}getSessionPath(e,t=new Date){let{year:n,month:s,day:o}=_a(t);return O.join(this.getGlobalProjectPath(e),"sessions",n,s,o)}getCurrentSessionPath(e){return this.getSessionPath(e,new Date)}async ensureSessionPath(e,t=new Date){let n=this.getSessionPath(e,t);return await dt(n),n}async listSessions(e,t=null,n=null){let s=O.join(this.getGlobalProjectPath(e),"sessions"),o=[];try{let i=await Bt.readdir(s,{withFileTypes:!0});for(let a of i){if(!a.isDirectory()||t&&a.name!==t.toString())continue;let c=O.join(s,a.name),u=await Bt.readdir(c,{withFileTypes:!0});for(let p of u){if(!p.isDirectory()||n&&p.name!==n.toString().padStart(2,"0"))continue;let m=O.join(c,p.name),d=await Bt.readdir(m,{withFileTypes:!0});for(let g of d)g.isDirectory()&&o.push({year:a.name,month:p.name,day:g.name,path:O.join(m,g.name),date:new Date(`${a.name}-${p.name}-${g.name}`)})}}return o.sort((a,c)=>c.date.getTime()-a.date.getTime()),o}catch{return[]}}async getSessionsInRange(e,t,n=new Date){return(await this.listSessions(e)).filter(o=>o.date>=t&&o.date<=n)}getFilePath(e,t,n){return O.join(this.getGlobalProjectPath(e),t,n)}async listProjects(){try{return await this.ensureGlobalStructure(),(await Bt.readdir(this.globalProjectsDir,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}async projectExists(e){let t=this.getGlobalProjectPath(e);return await bo(t)}getDisplayPath(e){let t=za.homedir();return e.startsWith(t)?e.replace(t,"~"):e}getAuthConfigPath(){return O.join(this.globalConfigDir,"auth.json")}getSyncPendingPath(e){return O.join(this.getGlobalProjectPath(e),"sync","pending.json")}getLastSyncPath(e){return O.join(this.getGlobalProjectPath(e),"sync","last-sync.json")}getRunningStatusPath(){return O.join(this.globalBaseDir,".running")}getDocsPath(){return O.join(this.globalBaseDir,"docs")}async getAgentDir(){return(await(He(),bt(mt)).getActiveProvider()).configDir}async getAgentSettingsPath(){let e=await(He(),bt(mt)).getActiveProvider();return(He(),bt(mt)).getGlobalSettingsPath(e.name)}getClaudeDir(){return O.join(za.homedir(),".claude")}getClaudeSettingsPath(){return O.join(this.getClaudeDir(),"settings.json")}getAgentsPath(e){return e?O.join(this.getGlobalProjectPath(e),"agents"):O.join(this.globalBaseDir,"agents")}getStoragePath(e,t){return O.join(this.getGlobalProjectPath(e),"storage",t)}getContextPath(e){return O.join(this.getGlobalProjectPath(e),"context")}async detectMonorepo(e){let t={isMonorepo:!1,type:null,rootPath:e,packages:[]},n=[{file:"pnpm-workspace.yaml",type:"pnpm"},{file:"lerna.json",type:"lerna"},{file:"nx.json",type:"nx"},{file:"rush.json",type:"rush"},{file:"turbo.json",type:"turborepo"}];for(let s of n){let o=O.join(e,s.file);if(await C(o)){t.isMonorepo=!0,t.type=s.type;break}}if(!t.isMonorepo){let s=O.join(e,"package.json");if(await C(s))try{let o=await Bt.readFile(s,"utf-8");JSON.parse(o).workspaces&&(t.isMonorepo=!0,t.type="npm")}catch{}}return t.isMonorepo&&(t.packages=await this.discoverMonorepoPackages(e,t.type)),t}async discoverMonorepoPackages(e,t){let n=[],s=[];try{if(t==="pnpm"){let i=(await Bt.readFile(O.join(e,"pnpm-workspace.yaml"),"utf-8")).match(/packages:\s*\n((?:\s*-\s*.+\n?)+)/);i&&(s=i[1].split(`
10
- `).map(a=>a.replace(/^\s*-\s*['"]?|['"]?\s*$/g,"")).filter(Boolean))}else if(t==="npm"||t==="lerna"){let o=O.join(e,"package.json"),i=await Bt.readFile(o,"utf-8"),a=JSON.parse(i);if(Array.isArray(a.workspaces)?s=a.workspaces:a.workspaces?.packages&&(s=a.workspaces.packages),t==="lerna"){let c=O.join(e,"lerna.json");if(await C(c)){let u=await Bt.readFile(c,"utf-8"),p=JSON.parse(u);p.packages&&(s=p.packages)}}}else if(t==="nx")s=["apps/*","libs/*","packages/*"];else if(t==="turborepo"){let o=O.join(e,"package.json"),i=await Bt.readFile(o,"utf-8"),a=JSON.parse(i);Array.isArray(a.workspaces)&&(s=a.workspaces)}s.length===0&&(s=["packages/*","apps/*","libs/*"]);for(let o of s){if(o.startsWith("!"))continue;let i=Vw(o,{cwd:e,absolute:!1});for(let a of i){let c=O.join(e,a),u=O.join(c,"package.json");if(await C(u))try{let p=await Bt.readFile(u,"utf-8"),m=JSON.parse(p),d=O.join(c,"PRJCT.md");n.push({name:m.name||O.basename(a),path:c,relativePath:a,hasPrjctMd:await C(d)})}catch{}}}}catch{}return n}async findContainingPackage(e,t){if(!t.isMonorepo)return null;let n=O.resolve(e);for(let s of t.packages){let o=O.resolve(s.path);if(n.startsWith(o))return s}return null}async findMonorepoRoot(e){let t=O.resolve(e),n=O.parse(t).root;for(;t!==n;){if((await this.detectMonorepo(t)).isMonorepo)return t;t=O.dirname(t)}return null}},qw=new Ja,P=qw});import Hn from"node:fs/promises";import Kw from"node:path";import*as Mo from"jsonc-parser";function Xp(r){let e=[],t=Mo.parse(r,e,{allowTrailingComma:!0,disallowComments:!1});if(e.length>0){let n=e[0];throw new SyntaxError(`JSON parse error at offset ${n.offset}: ${Mo.printParseErrorCode(n.error)}`)}return t}var Wa,Xw,I,Ye=y(()=>{"use strict";an();M();ne();st();$o();ee();l(Xp,"parseJsonc");Wa=class{static{l(this,"ConfigManager")}async readConfig(e){try{let t=P.getLocalConfigPath(e),n=await Hn.readFile(t,"utf-8");return Xp(n)}catch(t){return k(t)||console.warn(`Warning: Could not read config at ${e}: ${Y(t)}`),null}}async writeConfig(e,t){let n=P.getLocalConfigPath(e),s=P.getLegacyPrjctPath(e);await Hn.mkdir(s,{recursive:!0});let o=JSON.stringify(t,null,2);await Hn.writeFile(n,`${o}
11
- `,"utf-8")}async readGlobalConfig(e){try{let t=P.getGlobalProjectConfigPath(e),n=await Hn.readFile(t,"utf-8");return Xp(n)}catch(t){return k(t)||console.warn(`Warning: Could not read global config for ${e}: ${Y(t)}`),null}}async writeGlobalConfig(e,t){let n=P.getGlobalProjectConfigPath(e),s=P.getGlobalProjectPath(e);await Hn.mkdir(s,{recursive:!0});let o=JSON.stringify(t,null,2);await Hn.writeFile(n,`${o}
12
- `,"utf-8")}async ensureGlobalConfig(e){let t=await this.readGlobalConfig(e);if(!t){let n=b();t={projectId:e,authors:[],version:se,lastSync:n},await this.writeGlobalConfig(e,t)}return t}async createConfig(e,t){let n=P.generateProjectId(e),s=P.getGlobalProjectPath(n),o=P.getDisplayPath(s),i=b(),a={projectId:n,dataPath:o,showMetrics:!0};await this.writeConfig(e,a);let c={projectId:n,authors:[{name:t.name||"Unknown",email:t.email||"",github:t.github||"",firstContribution:i,lastActivity:i}],version:se,created:i,lastSync:i};return await this.writeGlobalConfig(n,c),a}async updateLastSync(e){let t=await this.getProjectId(e),n=await this.readGlobalConfig(t);n&&(n.lastSync=b(),await this.writeGlobalConfig(t,n))}validateConfig(e){return!(!e||!e.projectId||!e.dataPath)}async needsMigration(e){if(!await P.hasLegacyStructure(e))return!1;if(!await P.hasConfig(e))return!0;let s=await this.readConfig(e);if(!s||!s.projectId)return!0;let o=P.getGlobalProjectPath(s.projectId);try{return(await Hn.readdir(Kw.join(o,"core"))).length===0}catch(i){return k(i),!0}}async getProjectId(e){let t=await this.readConfig(e);return t?.projectId?t.projectId:P.generateProjectId(e)}async findAuthor(e,t){let n=await this.readGlobalConfig(e);return!n||!n.authors?null:n.authors.find(s=>s.github===t)||null}async addAuthor(e,t){let n=await this.ensureGlobalConfig(e);if(n.authors.some(i=>i.github===t.github))return;let o=b();n.authors.push({name:t.name||"Unknown",email:t.email||"",github:t.github||"",firstContribution:o,lastActivity:o}),n.lastSync=o,await this.writeGlobalConfig(e,n)}async updateAuthorActivity(e,t){let n=await this.readGlobalConfig(e);if(!n||!n.authors)return;let s=n.authors.find(o=>o.github===t);s&&(s.lastActivity=b(),n.lastSync=s.lastActivity,await this.writeGlobalConfig(e,n))}async getCurrentAuthor(e){let t=await vs(),n=await this.getProjectId(e);return await this.addAuthor(n,{name:t.name??void 0,email:t.email??void 0,github:t.github??void 0}),t.github||t.name||"Unknown"}async isConfigured(e){let t=await this.readConfig(e);return this.validateConfig(t)}async getShowMetrics(e){return(await this.readConfig(e))?.showMetrics??!0}async setShowMetrics(e,t){let n=await this.readConfig(e);n&&(n.showMetrics=t,await this.writeConfig(e,n))}async getConfigWithDefaults(e){let t=await this.readConfig(e);if(t)return t;let n=P.generateProjectId(e);return{projectId:n,dataPath:P.getDisplayPath(P.getGlobalProjectPath(n))}}},Xw=new Wa,I=Xw});import xs from"node:fs/promises";import Yw from"node:os";import Yp from"node:path";var Ba,Qw,Fo,Va=y(()=>{"use strict";M();Ba=class{static{l(this,"EditorsConfig")}homeDir;configDir;configFile;constructor(){this.homeDir=Yw.homedir(),this.configDir=Yp.join(this.homeDir,".prjct-cli","config"),this.configFile=Yp.join(this.configDir,"installed-editors.json")}async ensureConfigDir(){try{await xs.mkdir(this.configDir,{recursive:!0})}catch(e){console.error("[editors-config] Error creating config directory:",w(e))}}async loadConfig(){try{let e=await xs.readFile(this.configFile,"utf-8");return JSON.parse(e)}catch(e){return e.code==="ENOENT"||console.error("[editors-config] Error loading config:",w(e)),null}}async saveConfig(e,t,n="claude"){try{await this.ensureConfigDir();let s={version:e,editor:n,provider:n,lastInstall:new Date().toISOString(),path:t};return await xs.writeFile(this.configFile,JSON.stringify(s,null,2),"utf-8"),!0}catch(s){return console.error("[editors-config] Error saving config:",w(s)),!1}}async getProvider(){let e=await this.loadConfig();return e?e.provider||e.editor||"claude":null}async getLastVersion(){let e=await this.loadConfig();return e?e.version:null}async hasVersionChanged(e){let t=await this.getLastVersion();return t!==null&&t!==e}async updateVersion(e){try{let t=await this.loadConfig();return t?(t.version=e,t.lastInstall=new Date().toISOString(),await xs.writeFile(this.configFile,JSON.stringify(t,null,2),"utf-8"),!0):!1}catch(t){return console.error("[editors-config] Error updating version:",w(t)),!1}}async configExists(){try{return await xs.access(this.configFile),!0}catch{return!1}}async deleteConfig(){try{return await this.configExists()&&await xs.unlink(this.configFile),!0}catch(e){return console.error("[editors-config] Error deleting config:",w(e)),!1}}},Qw=new Ba,Fo=Qw});function tk(){let r=process.env.PRJCT_DEBUG||process.env.DEBUG||"";if(!r)return{level:-1,name:"disabled"};if(ek.has(r)||r.includes("prjct"))return{level:Ts.debug,name:"debug"};let e=Ts[r]??-1,t=e>=0?r:"disabled";return{level:e,name:t}}function Oo(r,e,t){return Qp>=r?(...n)=>console[t](e,...n):sk}var Ts,ek,Qp,nk,sk,rk,F,Gn=y(()=>{"use strict";Ts={error:0,warn:1,info:2,debug:3},ek=new Set(["1","true","*"]);l(tk,"getLogLevel");({level:Qp,name:nk}=tk()),sk=l(()=>{},"noop");l(Oo,"createLogMethod");rk={error:Oo(Ts.error,"[prjct:error]","error"),warn:Oo(Ts.warn,"[prjct:warn]","warn"),info:Oo(Ts.info,"[prjct:info]","log"),debug:Oo(Ts.debug,"[prjct:debug]","log"),isEnabled:l(()=>Qp>=0,"isEnabled"),level:l(()=>nk,"level")},F=rk});var Xa=y(()=>{"use strict"});import Jn from"chalk";var id,wk,kk,$t,ad=y(()=>{"use strict";He();id=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],wk=80,kk={name:"prjct",icon:"\u26A1",signature:"\u26A1 prjct",spinner:{frames:id,speed:wk},cli:{header:l(()=>`${Jn.cyan.bold("\u26A1")} ${Jn.cyan("prjct")}`,"header"),footer:l(()=>Jn.dim("\u26A1 prjct"),"footer"),spin:l((r,e)=>`${Jn.cyan("\u26A1")} ${Jn.cyan("prjct")} ${Jn.cyan(id[r%10])} ${Jn.dim(e||"")}`,"spin")},template:{header:"\u26A1 prjct",footer:"\u26A1 prjct"},commitFooter:"Generated with [p/](https://www.prjct.app/)",urls:{website:"https://prjct.app",docs:"https://prjct.app/docs"},getCommitFooter:l((r="claude")=>xo(r).commitFooter,"getCommitFooter"),getSignature:l((r="claude")=>xo(r).signature,"getSignature")},$t=kk});function Es(r){let e=`PRJCT_TIMEOUT_${r}`,t=process.env[e];if(t){let n=Number.parseInt(t,10);if(!Number.isNaN(n)&&n>0)return n}return Sk[r]}var te,Qa,Za,Lo,Sk,Ct,xr,cd,Tr,Kt=y(()=>{"use strict";te={GATHERING:"gathering",ANALYZING:"analyzing",PROPOSING:"proposing",PENDING_APPROVAL:"awaiting_approval",APPROVED:"approved",REJECTED:"rejected",EXECUTING:"executing",COMPLETED:"completed",ABORTED:"aborted"},Qa=["feature","spec","design","refactor","migrate"],Za=["ship","cleanup","git","migrate"],Lo=["Read","Glob","Grep","GetTimestamp","GetDate","GetDateTime"],Sk={TOOL_CHECK:5e3,GIT_OPERATION:1e4,GIT_CLONE:6e4,API_REQUEST:3e4,NPM_INSTALL:12e4,WORKFLOW_HOOK:6e4};l(Es,"getTimeout");Ct={SPINNER_MSG:45,DONE_MSG:50,FAIL_MSG:65,WARN_MSG:65,STEP_MSG:35,PROGRESS_TEXT:25,ISSUE_TITLE:50,FALLBACK_TRUNCATE:50,CLEAR_WIDTH:80},xr={JSONL_MAX_LINES:1e3,ROTATION_SIZE_MB:10,LARGE_FILE_WARN_MB:50},cd={HISTORY_MAX:100},Tr={NO_PREFERENCES:"No workflow preferences configured.",SET_EXAMPLE:"p. workflow before ship run the tests",MODIFY_EXAMPLE:"p. workflow before ship run npm test",REMOVE_EXAMPLE:"p. workflow remove the ship hook"}});var js,Uo=y(()=>{"use strict";js={NO_PROJECT:{message:"No prjct project found in this directory",hint:"Run 'prjct init' to set up a new project",file:".prjct/prjct.config.json"},NO_PROJECT_ID:{message:"Project ID not found",hint:"Run 'prjct init' or check .prjct/prjct.config.json",file:".prjct/prjct.config.json"},CONFIG_NOT_FOUND:{message:"Configuration file not found",hint:"Run 'prjct init' to create project configuration",file:".prjct/prjct.config.json"},CONFIG_INVALID:{message:"Invalid configuration file",hint:"Check JSON syntax or delete .prjct/ and run init again",file:".prjct/prjct.config.json"},GIT_NOT_FOUND:{message:"Git repository not detected",hint:"Run 'git init' first, then 'prjct init'"},GIT_NO_COMMITS:{message:"No commits in repository",hint:"Make an initial commit before using prjct"},GIT_DIRTY:{message:"Working directory has uncommitted changes",hint:"Commit or stash changes, or use '--force' to override"},GIT_ON_MAIN:{message:"Cannot ship from main/master branch",hint:"Create a feature branch first: git checkout -b feature/your-feature"},GIT_OPERATION_FAILED:{message:"Git operation failed",hint:"Check git status and resolve any conflicts"},GH_NOT_AUTHENTICATED:{message:"GitHub CLI not authenticated",hint:"Run 'gh auth login' to authenticate",docs:"https://cli.github.com/manual/gh_auth_login"},LINEAR_NOT_CONFIGURED:{message:"Linear integration not configured",hint:"Run 'p. linear setup' to configure Linear"},LINEAR_API_ERROR:{message:"Linear API error",hint:"Check your API key or network connection"},NO_ACTIVE_TASK:{message:"No active task",hint:`Start a task with 'p. task "description"'`},TASK_ALREADY_ACTIVE:{message:"A task is already in progress",hint:"Complete it with 'p. done' or pause with 'p. pause'"},SYNC_FAILED:{message:"Project sync failed",hint:"Check file permissions and try again"},NOTHING_TO_SHIP:{message:"Nothing to ship",hint:"Make some changes first, then run ship"},PR_CREATE_FAILED:{message:"Failed to create pull request",hint:"Check GitHub auth and remote configuration"},NO_AI_PROVIDER:{message:"No AI provider detected",hint:"Install Claude Code or Gemini CLI, then run 'prjct start'",docs:"https://prjct.app/docs"},PROVIDER_NOT_CONFIGURED:{message:"AI provider not configured for prjct",hint:"Run 'prjct start' to configure your provider"},UNKNOWN_COMMAND:{message:"Unknown command",hint:"Run 'prjct --help' to see available commands"},MISSING_PARAM:{message:"Missing required parameter",hint:"Check command usage below"},UNKNOWN:{message:"An unexpected error occurred",hint:"Check the error details and try again"}}});function Wn(r,e){return{...js[r],...e}}function Er(r,e,t){return{message:r,hint:e,...t}}var jr=y(()=>{"use strict";Uo();Uo();l(Wn,"getError");l(Er,"createError")});var ud={};Ne(ud,{ERRORS:()=>js,ICONS:()=>Pn,OUTPUT_TIERS:()=>ld,createError:()=>Er,default:()=>h,formatForHuman:()=>xk,getError:()=>Wn,getOutputTier:()=>Pk,getTierConfig:()=>Go,isQuietMode:()=>vk,limitLines:()=>Ho,setOutputTier:()=>bk,setQuietMode:()=>Ck});import Q from"chalk";function bk(r){Is=r}function Pk(){return Is}function Go(){return ld[Is]}function Ck(r){Ze=r}function vk(){return Ze}function Ho(r,e){let t=e??Go().maxLines;if(t===1/0||t===0)return r;let n=r.split(`
13
- `);if(n.length<=t)return r;let s=n.slice(0,t),o=n.length-t;return`${s.join(`
14
- `)}
15
- ${Q.dim(`...${o} more lines`)}`}function xk(r){let e=Go();if(Is==="silent")return"";if(Is==="verbose")return JSON.stringify(r,null,2);if(typeof r!="object"||r===null)return vt(String(r),e.maxCharsPerLine);let t=r;if("identifier"in t&&"title"in t){let o=[];return o.push(`${t.identifier}: ${vt(String(t.title),e.maxCharsPerLine-10)}`),t.status&&o.push(`Status: ${t.status}`),t.priority&&t.priority!=="none"&&o.push(`Priority: ${t.priority}`),t.url&&Is==="compact"&&o.push(Q.dim(String(t.url))),Ho(o.join(`
16
- `),e.maxLines)}if("issues"in t&&Array.isArray(t.issues)){let o=t.issues,i=o.slice(0,e.maxLines).map(a=>{let c=a.priority&&a.priority!=="none"?` [${a.priority}]`:"";return`${a.identifier} ${vt(String(a.title),Ct.ISSUE_TITLE)}${c}`});return o.length>e.maxLines&&i.push(Q.dim(`...${o.length-e.maxLines} more`)),i.join(`
17
- `)}let s=["id","name","title","status","message","success","error"].filter(o=>o in t);return s.length>0?Ho(s.map(o=>`${o}: ${vt(String(t[o]),e.maxCharsPerLine-o.length-2)}`).join(`
18
- `),e.maxLines):Ho(JSON.stringify(r,null,2),e.maxLines)}var TI,ec,ld,Is,Pn,As,tc,Ze,vt,Tk,Ek,h,Xt=y(()=>{"use strict";ad();Kt();jr();jr();TI=$t.spinner.frames,ec=$t.spinner.speed,ld={silent:{maxLines:0,maxCharsPerLine:0,showMetrics:!1},minimal:{maxLines:1,maxCharsPerLine:65,showMetrics:!1},compact:{maxLines:4,maxCharsPerLine:80,showMetrics:!0},verbose:{maxLines:1/0,maxCharsPerLine:1/0,showMetrics:!0}},Is="compact";l(bk,"setOutputTier");l(Pk,"getOutputTier");l(Go,"getTierConfig");Pn={success:Q.green("\u2713"),fail:Q.red("\u2717"),warn:Q.yellow("\u26A0"),info:Q.blue("\u2139"),debug:Q.dim("\u{1F527}"),bullet:Q.dim("\u2022"),arrow:Q.dim("\u2192"),check:Q.green("\u2713"),cross:Q.red("\u2717"),spinner:Q.cyan("\u25D0")},As=null,tc=0,Ze=!1;l(Ck,"setQuietMode");l(vk,"isQuietMode");vt=l((r,e)=>{let t=e??(Go().maxCharsPerLine||Ct.FALLBACK_TRUNCATE);return r&&r.length>t?`${r.slice(0,t-1)}\u2026`:r||""},"truncate");l(Ho,"limitLines");l(xk,"formatForHuman");Tk=l(()=>process.stdout.isTTY?process.stdout.write(`\r${" ".repeat(Ct.CLEAR_WIDTH)}\r`):!0,"clear"),Ek={start(){return Ze||console.log($t.cli.header()),this},end(){return Ze||console.log($t.cli.footer()),this},spin(r){return Ze?this:(this.stop(),process.stdout.isTTY?(As=setInterval(()=>{process.stdout.write(`\r${$t.cli.spin(tc++,vt(r,Ct.SPINNER_MSG))}`)},ec),this):(process.stdout.write(`${$t.cli.spin(0,vt(r,Ct.SPINNER_MSG))}
19
- `),this))},done(r,e){if(this.stop(),!Ze){let t="";if(e){let n=[];e.agents!==void 0&&n.push(`${e.agents}a`),e.reduction!==void 0&&n.push(`${e.reduction}%`),e.tokens!==void 0&&n.push(`${Math.round(e.tokens)}K`),n.length>0&&(t=Q.dim(` [${n.join(" | ")}]`))}console.log(`${Pn.success} ${vt(r,Ct.DONE_MSG)}${t}`)}return this},fail(r){return this.stop(),console.error(`${Pn.fail} ${vt(r,Ct.FAIL_MSG)}`),this},failWithHint(r){this.stop();let e=typeof r=="string"?Wn(r):r;return console.error(),console.error(`${Pn.fail} ${e.message}`),e.file&&console.error(Q.dim(` File: ${e.file}`)),e.hint&&console.error(Q.yellow(` \u{1F4A1} ${e.hint}`)),e.docs&&console.error(Q.dim(` Docs: ${e.docs}`)),console.error(),this},warn(r){return this.stop(),Ze||console.log(`${Pn.warn} ${vt(r,Ct.WARN_MSG)}`),this},info(r){return this.stop(),Ze||console.log(`${Pn.info} ${r}`),this},debug(r){this.stop();let e=process.env.DEBUG==="1"||process.env.DEBUG==="true";return!Ze&&e&&console.log(`${Pn.debug} ${Q.dim(r)}`),this},success(r,e){return this.done(r,e)},list(r,e={}){if(this.stop(),Ze)return this;let t=e.bullet||Pn.bullet,n=" ".repeat(e.indent||0);for(let s of r)console.log(`${n}${t} ${s}`);return this},table(r,e={}){if(this.stop(),Ze||r.length===0)return this;let t=Object.keys(r[0]),n={};for(let s of t){n[s]=s.length;for(let o of r){let i=String(o[s]??"");i.length>n[s]&&(n[s]=i.length)}}if(e.header!==!1){let s=t.map(o=>o.padEnd(n[o])).join(" ");console.log(Q.dim(s)),console.log(Q.dim("\u2500".repeat(s.length)))}for(let s of r){let o=t.map(i=>String(s[i]??"").padEnd(n[i])).join(" ");console.log(o)}return this},box(r,e){if(this.stop(),Ze)return this;let t=e.split(`
20
- `),n=Math.max(r.length,...t.map(o=>o.length)),s="\u2500".repeat(n+2);console.log(Q.dim(`\u250C${s}\u2510`)),console.log(`${Q.dim("\u2502")} ${Q.bold(r.padEnd(n))} ${Q.dim("\u2502")}`),console.log(Q.dim(`\u251C${s}\u2524`));for(let o of t)console.log(`${Q.dim("\u2502")} ${o.padEnd(n)} ${Q.dim("\u2502")}`);return console.log(Q.dim(`\u2514${s}\u2518`)),this},section(r){return this.stop(),Ze?this:(console.log(`
21
- ${Q.bold(r)}`),console.log(Q.dim("\u2500".repeat(r.length))),this)},stop(){return As&&(clearInterval(As),As=null,Tk()),this},step(r,e,t){if(Ze)return this;this.stop();let n=Q.dim(`[${r}/${e}]`);return process.stdout.isTTY?(As=setInterval(()=>{process.stdout.write(`\r${$t.cli.spin(tc++,`${n} ${vt(t,Ct.STEP_MSG)}`)}`)},ec),this):(process.stdout.write(`${$t.cli.spin(0,`${n} ${vt(t,Ct.STEP_MSG)}`)}
22
- `),this)},progress(r,e,t){if(Ze)return this;this.stop();let n=Math.round(r/e*100),s=Math.round(n/10),o=10-s,i=Q.cyan("\u2588".repeat(s))+Q.dim("\u2591".repeat(o)),a=t?` ${vt(t,Ct.PROGRESS_TEXT)}`:"";return process.stdout.isTTY?(As=setInterval(()=>{process.stdout.write(`\r${$t.cli.spin(tc++,`[${i}] ${n}%${a}`)}`)},ec),this):(process.stdout.write(`${$t.cli.spin(0,`[${i}] ${n}%${a}`)}
23
- `),this)}},h=Ek});var md={};Ne(md,{default:()=>Dk,sessionTracker:()=>Cn});import nc from"node:fs/promises";import jk from"node:path";var Ak,Ik,pd,dd,sc,Cn,Dk,zo=y(()=>{"use strict";ee();M();ne();Ak="session.json",Ik=1800*1e3,pd=50,dd=200,sc=class{static{l(this,"SessionTracker")}getPath(e){return P.getStoragePath(e,Ak)}async read(e){let t=this.getPath(e);try{let n=await nc.readFile(t,"utf-8");return JSON.parse(n)}catch(n){if(k(n)||n instanceof SyntaxError)return this.getDefault();throw n}}async write(e,t){let n=this.getPath(e);await nc.mkdir(jk.dirname(n),{recursive:!0}),await nc.writeFile(n,JSON.stringify(t,null,2),"utf-8")}getDefault(){return{current:null,config:{idleTimeoutMs:Ik}}}isExpired(e,t){let n=new Date(e.lastActivity).getTime();return Date.now()-n>t}async touch(e){let t=await this.read(e),n=b();if(t.current&&!this.isExpired(t.current,t.config.idleTimeoutMs))return t.current.lastActivity=n,await this.write(e,t),t.current;let s={id:crypto.randomUUID(),projectId:e,status:"active",createdAt:n,lastActivity:n,commands:[],files:[]};return t.current=s,await this.write(e,t),s}async trackCommand(e,t,n){let s=await this.read(e);if(!s.current)return;let o=b();s.current.lastActivity=o,s.current.commands.push({command:t,timestamp:o,durationMs:n}),s.current.commands.length>pd&&(s.current.commands=s.current.commands.slice(-pd)),await this.write(e,s)}async trackFile(e,t,n){let s=await this.read(e);if(!s.current)return;let o=b();s.current.lastActivity=o,s.current.files.push({path:t,operation:n,timestamp:o}),s.current.files.length>dd&&(s.current.files=s.current.files.slice(-dd)),await this.write(e,s)}async getInfo(e){let t=await this.read(e);if(!t.current||this.isExpired(t.current,t.config.idleTimeoutMs))return{active:!1,id:null,duration:null,idleSince:null,idleMs:0,expiresIn:null,commandCount:0,commands:[],filesRead:0,filesWritten:0};let n=t.current,s=Date.now(),o=new Date(n.createdAt).getTime(),i=new Date(n.lastActivity).getTime(),a=s-i,c=t.config.idleTimeoutMs,u=Math.max(0,c-a),p=n.commands.map(g=>g.command),m=new Set(n.files.filter(g=>g.operation==="read").map(g=>g.path)).size,d=new Set(n.files.filter(g=>g.operation==="write").map(g=>g.path)).size;return{active:!0,id:n.id,duration:br(s-o),idleSince:n.lastActivity,idleMs:a,expiresIn:br(u),commandCount:n.commands.length,commands:p,filesRead:m,filesWritten:d}}async expire(e){let t=await this.read(e);t.current&&(t.current.status="expired",t.current=null,await this.write(e,t))}async expireIfStale(e){let t=await this.read(e);return t.current&&this.isExpired(t.current,t.config.idleTimeoutMs)?(t.current=null,await this.write(e,t),!0):!1}},Cn=new sc,Dk=Cn});var Mt={};Ne(Mt,{appendJsonLine:()=>Ds,appendJsonLineWithRotation:()=>Rs,appendJsonLines:()=>Mk,checkFileSizeWarning:()=>Lk,countJsonLines:()=>fd,filterJsonLines:()=>oc,getFileSizeMB:()=>ac,getFirstJsonLines:()=>Fk,getLastJsonLines:()=>ic,isJsonLinesEmpty:()=>_k,mergeJsonLines:()=>Ok,parseJsonLines:()=>gd,readJsonLines:()=>ln,readJsonLinesStreaming:()=>Nk,rotateJsonLinesIfNeeded:()=>hd,stringifyJsonLines:()=>rc,writeJsonLines:()=>Jo});import Rk from"node:fs";import Vn from"node:fs/promises";import Bn from"node:path";import $k from"node:readline";function gd(r){let e=r.split(`
24
- `).filter(n=>n.trim()),t=[];for(let n of e)try{t.push(JSON.parse(n))}catch{}return t}function rc(r){return`${r.map(e=>JSON.stringify(e)).join(`
25
- `)}
26
- `}async function ln(r){try{let e=await Vn.readFile(r,"utf-8");return gd(e)}catch(e){if(k(e))return[];throw e}}async function Jo(r,e){let t=rc(e);await Vn.writeFile(r,t,"utf-8")}async function Ds(r,e){let t=`${JSON.stringify(e)}
27
- `;await Vn.appendFile(r,t,"utf-8")}async function Mk(r,e){let t=rc(e);await Vn.appendFile(r,t,"utf-8")}async function oc(r,e){return(await ln(r)).filter(e)}async function fd(r){try{return(await Vn.readFile(r,"utf-8")).split(`
28
- `).filter(n=>n.trim()).length}catch(e){if(k(e))return 0;throw e}}async function ic(r,e){return(await ln(r)).slice(-e)}async function Fk(r,e){return(await ln(r)).slice(0,e)}async function Ok(r){let e=[];for(let t of r){let n=await ln(t);e.push(...n)}return e}async function _k(r){return await fd(r)===0}async function Nk(r,e=xr.JSONL_MAX_LINES){try{let t=Rk.createReadStream(r),n=$k.createInterface({input:t,crlfDelay:1/0}),s=[];for await(let o of n)if(o.trim()){try{s.push(JSON.parse(o))}catch{}s.length>e&&s.shift()}return s}catch(t){if(k(t))return[];throw t}}async function ac(r){try{return(await Vn.stat(r)).size/(1024*1024)}catch(e){if(k(e))return 0;throw e}}async function hd(r,e=xr.ROTATION_SIZE_MB){let t=await ac(r);if(t<e)return!1;let n=new Date().toISOString().split("T")[0],s=Bn.dirname(r),o=Bn.extname(r),i=Bn.basename(r,o),a=Bn.join(s,`${i}-${n}${o}`);return await Vn.rename(r,a),console.log(`\u{1F4E6} Rotated ${Bn.basename(r)} (${t.toFixed(1)}MB) \u2192 ${Bn.basename(a)}`),!0}async function Rs(r,e,t=xr.ROTATION_SIZE_MB){await hd(r,t),await Ds(r,e)}async function Lk(r,e=xr.LARGE_FILE_WARN_MB){let t=await ac(r),n=t>e;return n&&console.warn(`\u26A0\uFE0F Large file detected: ${Bn.basename(r)} (${t.toFixed(1)}MB). Reading may use significant memory.`),{sizeMB:t,isLarge:n}}var Ar=y(()=>{"use strict";M();Kt();l(gd,"parseJsonLines");l(rc,"stringifyJsonLines");l(ln,"readJsonLines");l(Jo,"writeJsonLines");l(Ds,"appendJsonLine");l(Mk,"appendJsonLines");l(oc,"filterJsonLines");l(fd,"countJsonLines");l(ic,"getLastJsonLines");l(Fk,"getFirstJsonLines");l(Ok,"mergeJsonLines");l(_k,"isJsonLinesEmpty");l(Nk,"readJsonLinesStreaming");l(ac,"getFileSizeMB");l(hd,"rotateJsonLinesIfNeeded");l(Rs,"appendJsonLineWithRotation");l(Lk,"checkFileSizeWarning")});var wd={};Ne(wd,{default:()=>qn,performanceTracker:()=>yd});import Uk from"node:fs/promises";import Hk from"node:path";var Gk,Wo,cc,yd,qn,Bo=y(()=>{"use strict";ne();Ar();ee();Gk="performance.jsonl",Wo=5,cc=class{static{l(this,"PerformanceTracker")}marks=new Map;getPath(e){return P.getStoragePath(e,Gk)}async ensureDir(e){let t=this.getPath(e);await Uk.mkdir(Hk.dirname(t),{recursive:!0})}markStart(e){this.marks.set(e,process.hrtime.bigint())}markEnd(e){let t=this.marks.get(e);if(t===void 0)return null;let n=process.hrtime.bigint();return this.marks.delete(e),Number(n-t)/1e6}async recordTiming(e,t,n,s){await this.ensureDir(e);let o={timestamp:b(),metric:t,value:Math.round(n*100)/100,unit:"ms",context:s};await Rs(this.getPath(e),o,Wo)}snapshotMemory(){let e=process.memoryUsage();return{heapUsed:e.heapUsed,heapTotal:e.heapTotal,rss:e.rss,external:e.external}}async recordMemory(e,t){await this.ensureDir(e);let n=this.snapshotMemory(),s=this.getPath(e),o=b(),i=[{timestamp:o,metric:"heap_used",value:n.heapUsed,unit:"bytes",context:t},{timestamp:o,metric:"heap_total",value:n.heapTotal,unit:"bytes",context:t},{timestamp:o,metric:"rss",value:n.rss,unit:"bytes",context:t},{timestamp:o,metric:"external_memory",value:n.external,unit:"bytes",context:t}];for(let a of i)await Rs(s,a,Wo);return n}async recordContextCorrectness(e,t){await this.ensureDir(e);let n={timestamp:b(),metric:"context_correctness",...t};await Rs(this.getPath(e),n,Wo)}async recordSubtaskHandoff(e,t){await this.ensureDir(e);let n={timestamp:b(),metric:"subtask_handoff",...t};await Rs(this.getPath(e),n,Wo)}async getMetrics(e,t){let n=this.getPath(e);t||(t=new Date,t.setDate(t.getDate()-7));let s=t.toISOString();return oc(n,o=>o.timestamp>=s)}async getReport(e,t=7){let n=new Date;n.setDate(n.getDate()-t);let s=await this.getMetrics(e,n),o={period:`${t}d`},i=s.filter(d=>"metric"in d&&d.metric==="startup_time");if(i.length>0){let d=i.map(g=>g.value);o.startup={avg:Math.round(d.reduce((g,f)=>g+f,0)/d.length),min:Math.min(...d),max:Math.max(...d),count:d.length,unit:"ms"}}let a=s.filter(d=>"metric"in d&&d.metric==="heap_used"),c=s.filter(d=>"metric"in d&&d.metric==="rss");if(a.length>0){let d=l(S=>Math.round(S/1048576*10)/10,"toMB"),g=a.map(S=>S.value),f=c.map(S=>S.value);o.memory={avgHeapMB:d(g.reduce((S,E)=>S+E,0)/g.length),peakHeapMB:d(Math.max(...g)),avgRssMB:f.length>0?d(f.reduce((S,E)=>S+E,0)/f.length):0}}let u=s.filter(d=>"metric"in d&&d.metric==="context_correctness");if(u.length>0){let d=u.filter(g=>g.receivedSync).length;o.contextCorrectness={total:u.length,receivedSync:d,rate:Math.round(d/u.length*100)}}let p=s.filter(d=>"metric"in d&&d.metric==="subtask_handoff");if(p.length>0){let d=p.filter(g=>g.outputPopulated).length;o.subtaskHandoff={total:p.length,outputPopulated:d,rate:Math.round(d/p.length*100)}}let m=s.filter(d=>"metric"in d&&d.metric==="command_duration");if(m.length>0){let d={};for(let g of m){let f=g.context?.command||"unknown";d[f]||(d[f]=[]),d[f].push(g.value)}o.commandDurations={};for(let[g,f]of Object.entries(d))o.commandDurations[g]={avg:Math.round(f.reduce((S,E)=>S+E,0)/f.length),min:Math.min(...f),max:Math.max(...f),count:f.length,unit:"ms"}}return o}},yd=new cc,qn=yd});var Sd={};Ne(Sd,{runStart:()=>Yk});import Ft from"node:fs/promises";import lc from"node:os";import un from"node:path";import _ from"chalk";function Wk(){console.clear(),console.log(zk),console.log(Jk)}function kd(r,e){console.log(`
29
- ${_.bold(" Select AI providers to configure:")}
30
- `),console.log(` ${_.dim("(Use arrow keys to navigate, space to toggle, enter to confirm)")}
31
- `),r.forEach((t,n)=>{let s=n===e?_.cyan("\u276F"):" ",o=t.selected?_.green("[\u2713]"):_.dim("[ ]"),i=t.installed?_.green("(installed)"):_.yellow("(will install)"),a=n===e?_.bold(t.displayName):t.displayName;console.log(` ${s} ${o} ${a} ${i}`)}),console.log("")}async function Bk(){let r=await Pt(),e=[{name:"claude",displayName:"Claude Code",installed:r.claude.installed,selected:r.claude.installed},{name:"gemini",displayName:"Gemini CLI",installed:r.gemini.installed,selected:r.gemini.installed}];return e.some(t=>t.selected)||(e[0].selected=!0),process.stdin.isTTY?new Promise(t=>{let n=0,s=l(()=>{process.stdout.write("\x1B[8A"),process.stdout.write("\x1B[0J"),kd(e,n)},"render");kd(e,n),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");let o=l(()=>{process.stdin.setRawMode(!1),process.stdin.removeListener("data",i),process.stdin.pause()},"cleanup"),i=l(a=>{if(a===""&&(o(),console.log(`
32
- Cancelled.
33
- `),process.exit(0)),a==="\r"||a===`
34
- `){o();let c=e.filter(u=>u.selected).map(u=>u.name);t(c.length>0?c:["claude"]);return}a==="\x1B[A"&&(n=Math.max(0,n-1),s()),a==="\x1B[B"&&(n=Math.min(e.length-1,n+1),s()),a===" "&&(e[n].selected=!e[n].selected,s())},"handleKey");process.stdin.on("data",i)}):(console.log(`
35
- ${_.bold(" Detected providers:")}
36
- `),e.forEach(t=>{t.installed&&console.log(` ${_.green("\u2713")} ${t.displayName}`)}),console.log(""),e.filter(t=>t.selected).map(t=>t.name))}async function Vk(r){let e=$e[r];if(!e.configDir)return!1;try{let t=un.join(e.configDir,"commands");await Ft.mkdir(t,{recursive:!0});let{getPackageRoot:n}=await Promise.resolve().then(()=>(st(),Ha)),s=n(),o=r==="claude"?"p.md":"p.toml",i=un.join(s,"templates","commands",o),a=un.join(t,o);return await C(i)?(await Ft.copyFile(i,a),!0):!1}catch(t){return console.error(` ${_.yellow("\u26A0")} Failed to install ${r} router: ${w(t)}`),!1}}async function qk(r){let e=$e[r];if(!e.configDir)return!1;try{await Ft.mkdir(e.configDir,{recursive:!0});let{getPackageRoot:t}=await Promise.resolve().then(()=>(st(),Ha)),n=t(),s=r==="claude"?"CLAUDE.md":"GEMINI.md",o=un.join(n,"templates","global",s),i=un.join(e.configDir,s);if(await C(o)){let a=await Ft.readFile(o,"utf-8");if(await C(i)){let c=await Ft.readFile(i,"utf-8"),u="<!-- prjct:start - DO NOT REMOVE THIS MARKER -->",p="<!-- prjct:end - DO NOT REMOVE THIS MARKER -->";if(c.includes(u)&&c.includes(p)){let m=c.substring(0,c.indexOf(u)),d=c.substring(c.indexOf(p)+p.length),g=a.substring(a.indexOf(u),a.indexOf(p)+p.length);await Ft.writeFile(i,m+g+d)}else await Ft.writeFile(i,`${c}
37
-
38
- ${a}`)}else await Ft.writeFile(i,a);return!0}return!1}catch(t){return console.error(` ${_.yellow("\u26A0")} Failed to install ${r} config: ${w(t)}`),!1}}async function Kk(r){let e=un.join(lc.homedir(),".prjct-cli","config");await Ft.mkdir(e,{recursive:!0});let t=un.join(e,"installed-editors.json"),n={version:se,providers:r,editor:r[0],provider:r[0],lastInstall:new Date().toISOString(),path:un.join(lc.homedir(),`.${r[0]}`,"commands")};await Ft.writeFile(t,JSON.stringify(n,null,2))}function Xk(r){console.log(`
39
- ${_.green.bold(" \u2713 Setup complete!")}
40
- `),console.log(` ${_.dim("Configured providers:")}`),r.forEach(e=>{let t=$e[e];console.log(` ${_.green("\u2713")} ${t.displayName}`)}),console.log(`
41
- ${_.bold("Next steps:")}
42
-
43
- ${_.cyan("1.")} Navigate to your project directory
44
- ${_.cyan("2.")} Run ${_.bold("p. init")} to initialize prjct for that project
45
- ${_.cyan("3.")} Start tracking with ${_.bold('p. task "your task"')}
46
-
47
- ${_.dim("Tips:")}
48
- ${_.dim("\u2022")} Use ${_.bold("p. sync")} to analyze your codebase
49
- ${_.dim("\u2022")} Use ${_.bold("p. done")} to complete tasks
50
- ${_.dim("\u2022")} Use ${_.bold("p. ship")} to create PRs
51
-
52
- ${_.dim("Learn more: https://prjct.app/docs")}
53
- `)}async function Yk(){Wk();let r=un.join(lc.homedir(),".prjct-cli","config","installed-editors.json");if(await C(r)&&JSON.parse(await Ft.readFile(r,"utf-8")).version===se&&(console.log(` ${_.yellow("\u2139")} Already configured for v${se}`),console.log(` ${_.dim("Run with --force to reconfigure")}
54
- `),!process.argv.includes("--force")))return;let e=await Bk();console.log(`
55
- ${_.cyan("Setting up...")}
56
- `);for(let t of e){let n=$e[t];process.stdout.write(` ${_.dim("\u2022")} ${n.displayName}... `);let s=await Vk(t),o=await qk(t);console.log(s&&o?_.green("\u2713"):s||o?_.yellow("partial"):_.yellow("skipped"))}await Kk(e),Xk(e)}var $s,Ms,Fs,Os,_s,zk,Jk,bd=y(()=>{"use strict";He();M();me();st();$s=_.rgb(0,255,255),Ms=_.rgb(80,180,255),Fs=_.rgb(140,120,255),Os=_.rgb(200,80,220),_s=_.rgb(255,80,180),zk=`
57
-
58
- ${$s(" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 ")}${Ms(" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 ")}${Fs(" \u2588\u2588\u2557")}${Os(" \u2588\u2588\u2588\u2588\u2588\u2588\u2557")}${_s("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")}
59
- ${$s(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557")}${Ms(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557")}${Fs(" \u2588\u2588\u2551")}${Os("\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D")}${_s("\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D")}
60
- ${$s(" \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D")}${Ms(" \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D")}${Fs(" \u2588\u2588\u2551")}${Os("\u2588\u2588\u2551 ")}${_s(" \u2588\u2588\u2551 ")}
61
- ${$s(" \u2588\u2588\u2554\u2550\u2550\u2550\u255D ")}${Ms(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557")}${Fs("\u2588\u2588 \u2588\u2588\u2551")}${Os("\u2588\u2588\u2551 ")}${_s(" \u2588\u2588\u2551 ")}
62
- ${$s(" \u2588\u2588\u2551 ")}${Ms(" \u2588\u2588\u2551 \u2588\u2588\u2551")}${Fs("\u255A\u2588\u2588\u2588\u2588\u2588\u2554\u255D")}${Os("\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557")}${_s(" \u2588\u2588\u2551 ")}
63
- ${$s(" \u255A\u2550\u255D ")}${Ms(" \u255A\u2550\u255D \u255A\u2550\u255D")}${Fs(" \u255A\u2550\u2550\u2550\u2550\u255D ")}${Os(" \u255A\u2550\u2550\u2550\u2550\u2550\u255D")}${_s(" \u255A\u2550\u255D ")}
64
-
65
- `,Jk=` ${_.white("Context Layer for AI Agents")} ${_.dim(`v${se}`)}
66
-
67
- ${_.dim(`Project context layer for AI coding agents.
68
- Works with Claude Code, Gemini CLI, and more.`)}
69
- ${_.cyan("https://prjct.app")}
70
- `;l(Wk,"showBanner");l(kd,"showProviderSelection");l(Bk,"selectProviders");l(Vk,"installRouter");l(qk,"installGlobalConfig");l(Kk,"saveSetupConfig");l(Xk,"showCompletion");l(Yk,"runStart")});import{z as Ae}from"zod";function uc(r,e="default"){let t=Pd[e]||Pd.default;return r/1e3*t}function Ns(r){return r<.01?`$${(r*100).toFixed(2)}\xA2`:`$${r.toFixed(2)}`}var Qk,Zk,Cd,vd,Pd,Vo=y(()=>{"use strict";Qk=Ae.object({date:Ae.string(),tokensSaved:Ae.number(),syncs:Ae.number(),avgCompressionRate:Ae.number(),totalDuration:Ae.number()}),Zk=Ae.object({agentName:Ae.string(),usageCount:Ae.number(),tokensSaved:Ae.number()}),Cd=Ae.object({totalTokensSaved:Ae.number(),avgCompressionRate:Ae.number(),syncCount:Ae.number(),watchTriggers:Ae.number(),avgSyncDuration:Ae.number(),totalSyncDuration:Ae.number(),agentUsage:Ae.array(Zk),dailyStats:Ae.array(Qk),firstSync:Ae.string(),lastUpdated:Ae.string()}),vd={totalTokensSaved:0,avgCompressionRate:0,syncCount:0,watchTriggers:0,avgSyncDuration:0,totalSyncDuration:0,agentUsage:[],dailyStats:[],firstSync:"",lastUpdated:""},Pd={"claude-opus-4.5":.005,"claude-sonnet-4.5":.003,"claude-haiku-4.5":.001,"claude-opus-4":.015,"claude-sonnet-4":.003,"claude-3-opus":.015,"claude-3-sonnet":.003,"gpt-4o":.0025,"gpt-4":.01,"gemini-pro":.00125,default:.003};l(uc,"estimateCostSaved");l(Ns,"formatCost")});var xd=y(()=>{"use strict"});var qo,Td=y(()=>{"use strict";qo={SESSION_STARTED:"session.started",SESSION_PAUSED:"session.paused",SESSION_RESUMED:"session.resumed",SESSION_COMPLETED:"session.completed",TASK_CREATED:"task.created",TASK_COMPLETED:"task.completed",TASK_UPDATED:"task.updated",FEATURE_ADDED:"feature.added",FEATURE_SHIPPED:"feature.shipped",FEATURE_UPDATED:"feature.updated",IDEA_CAPTURED:"idea.captured",IDEA_PROMOTED:"idea.promoted",SNAPSHOT_CREATED:"snapshot.created",SNAPSHOT_RESTORED:"snapshot.restored",COMMIT_CREATED:"git.commit",PUSH_COMPLETED:"git.push",PROJECT_INITIALIZED:"project.init",PROJECT_SYNCED:"project.sync",ANALYSIS_COMPLETED:"analysis.completed",ALL:"*"}});var Ed=y(()=>{"use strict"});var jd=y(()=>{"use strict";Ed()});function Ko(r,e=!1){return e||r>=6?"high":r>=3?"medium":"low"}var R,Ad,Ls=y(()=>{"use strict";R={CODE_STYLE:"code_style",NAMING_CONVENTION:"naming_convention",FILE_STRUCTURE:"file_structure",COMMIT_STYLE:"commit_style",BRANCH_NAMING:"branch_naming",TEST_BEHAVIOR:"test_behavior",SHIP_WORKFLOW:"ship_workflow",TECH_STACK:"tech_stack",ARCHITECTURE:"architecture",DEPENDENCIES:"dependencies",OUTPUT_VERBOSITY:"output_verbosity",CONFIRMATION_LEVEL:"confirmation_level",AGENT_PREFERENCE:"agent_preference"},Ad=["frontend","backend","devops","docs","testing","database","general"];l(Ko,"calculateConfidence")});var pc=y(()=>{"use strict";xd();Td();Uo();M();jd();Ls();Xa()});import Id from"node:fs/promises";import Dd from"node:path";var Xo,nS,Rd=y(()=>{"use strict";an();ee();pc();Kt();Gn();Xo=class{static{l(this,"EventBus")}listeners;onceListeners;history;historyLimit;projectId;constructor(){this.listeners=new Map,this.onceListeners=new Map,this.history=[],this.historyLimit=cd.HISTORY_MAX,this.projectId=null}async initialize(e){this.projectId=e}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){return this.onceListeners.has(e)||this.onceListeners.set(e,new Set),this.onceListeners.get(e).add(t),()=>{let n=this.onceListeners.get(e);n&&n.delete(t)}}off(e,t){let n=this.listeners.get(e);n&&n.delete(t)}async emit(e,t={}){let n=new Date().toISOString(),s={type:e,timestamp:n,projectId:this.projectId,...t};this.history.push(s),this.history.length>this.historyLimit&&this.history.shift(),this.projectId&&await this.logEvent(s);let o=this.getMatchingListeners(e);(await Promise.allSettled(o.map(u=>this.executeCallback(u,s)))).forEach(u=>{u.status==="rejected"&&F.error(`Event listener error for ${e}:`,u.reason)});let a=this.onceListeners.get(e);if(a){for(let u of a)await this.executeCallback(u,s);this.onceListeners.delete(e)}let c=this.onceListeners.get(qo.ALL);if(c)for(let u of c)await this.executeCallback(u,s)}getMatchingListeners(e){let t=[],n=this.listeners.get(e);n&&t.push(...n);let s=this.listeners.get(qo.ALL);s&&t.push(...s);let o=e.split(".")[0],i=this.listeners.get(`${o}.*`);return i&&t.push(...i),t}async executeCallback(e,t){try{let n=e(t);n instanceof Promise&&await n}catch(n){throw F.error("Event callback error:",n),n}}async logEvent(e){try{let t=P.getGlobalProjectPath(this.projectId),n=Dd.join(t,"memory","events.jsonl");await Id.mkdir(Dd.dirname(n),{recursive:!0});let s=`${JSON.stringify(e)}
71
- `;await Id.appendFile(n,s)}catch(t){F.debug("Failed to log event:",Y(t))}}getHistory(e=10,t=null){let n=this.history;return t&&(n=n.filter(s=>s.type===t||s.type.startsWith(t))),n.slice(-e)}clear(){this.listeners.clear(),this.onceListeners.clear()}flush(){this.history=[],this.onceListeners.clear()}removeAllListeners(e){e?(this.listeners.delete(e),this.onceListeners.delete(e)):(this.listeners.clear(),this.onceListeners.clear())}listenerCount(e){let t=this.listeners.get(e);return t?t.size:0}getRegisteredEvents(){return Array.from(this.listeners.keys())}},nS=new Xo});function Qo(r,e){let t=r[0];return e==="delete"?`${t}.deleted`:`${t}.updated`}var Yo,Us,$d=y(()=>{"use strict";ee();ne();me();l(Qo,"inferEventType");Yo=class{static{l(this,"SyncEventBus")}async publish(e){let t=P.getSyncPendingPath(e.projectId),n=await Un(t,[])??[];n.push(e),await kr(t,n)}async getPending(e){let t=P.getSyncPendingPath(e);return await Un(t,[])??[]}async clearPending(e){let t=P.getSyncPendingPath(e);await kr(t,[])}async updateLastSync(e){let t=P.getLastSyncPath(e),n={timestamp:b(),success:!0};await kr(t,n)}async getLastSync(e){let t=P.getLastSyncPath(e);return await Un(t,null)}},Us=new Yo});var dc=y(()=>{"use strict";Rd();$d()});var Ot,Zo=y(()=>{"use strict";Ot=class{static{l(this,"TTLCache")}cache=new Map;ttl;maxSize;constructor(e={}){this.ttl=e.ttl??5e3,this.maxSize=e.maxSize??50}isValid(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp<this.ttl:!1}get(e){let t=this.cache.get(e);return t?this.isValid(e)?t.data:(this.cache.delete(e),null):null}set(e,t){this.cache.set(e,{data:t,timestamp:Date.now()}),this.evictOldEntries()}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}has(e){return this.cache.has(e)}get size(){return this.cache.size}evictOldEntries(){if(this.cache.size<=this.maxSize)return;let t=Array.from(this.cache.entries()).sort((n,s)=>n[1].timestamp-s[1].timestamp).slice(0,this.cache.size-this.maxSize);for(let[n]of t)this.cache.delete(n)}stats(){return{size:this.cache.size,maxSize:this.maxSize,ttl:this.ttl}}prune(){let e=0;for(let t of this.cache.keys())this.isValid(t)||(this.cache.delete(t),e++);return e}}});import{Database as sS}from"bun:sqlite";import mc from"node:fs";import Md from"node:path";var rS,ei,V,xt,Yt=y(()=>{"use strict";ee();rS=[{version:1,name:"initial-schema",up:l(r=>{r.run(`
72
- -- =======================================================================
73
- -- Document storage (backward-compatible with JSON file pattern)
74
- -- =======================================================================
75
- -- Each row replaces one JSON file (state.json, queue.json, etc.)
76
- -- StorageManager reads/writes entire documents via key lookup.
77
- CREATE TABLE kv_store (
78
- key TEXT PRIMARY KEY,
79
- data TEXT NOT NULL,
80
- updated_at TEXT NOT NULL
81
- );
82
-
83
- -- =======================================================================
84
- -- Normalized: Tasks
85
- -- =======================================================================
86
- CREATE TABLE tasks (
87
- id TEXT PRIMARY KEY,
88
- description TEXT NOT NULL,
89
- type TEXT,
90
- status TEXT NOT NULL,
91
- parent_description TEXT,
92
- branch TEXT,
93
- linear_id TEXT,
94
- linear_uuid TEXT,
95
- session_id TEXT,
96
- feature_id TEXT,
97
- started_at TEXT NOT NULL,
98
- completed_at TEXT,
99
- shipped_at TEXT,
100
- paused_at TEXT,
101
- pause_reason TEXT,
102
- pr_url TEXT,
103
- expected_value TEXT,
104
- data TEXT
105
- );
106
-
107
- CREATE INDEX idx_tasks_status ON tasks(status);
108
- CREATE INDEX idx_tasks_type ON tasks(type);
109
- CREATE INDEX idx_tasks_branch ON tasks(branch);
110
- CREATE INDEX idx_tasks_linear_id ON tasks(linear_id);
111
-
112
- -- =======================================================================
113
- -- Normalized: Subtasks
114
- -- =======================================================================
115
- CREATE TABLE subtasks (
116
- id TEXT PRIMARY KEY,
117
- task_id TEXT NOT NULL,
118
- description TEXT NOT NULL,
119
- status TEXT NOT NULL,
120
- domain TEXT,
121
- agent TEXT,
122
- sort_order INTEGER NOT NULL,
123
- depends_on TEXT,
124
- started_at TEXT,
125
- completed_at TEXT,
126
- output TEXT,
127
- summary TEXT,
128
- FOREIGN KEY (task_id) REFERENCES tasks(id)
129
- );
130
-
131
- CREATE INDEX idx_subtasks_task_id ON subtasks(task_id);
132
- CREATE INDEX idx_subtasks_status ON subtasks(status);
133
-
134
- -- =======================================================================
135
- -- Normalized: Queue Tasks
136
- -- =======================================================================
137
- CREATE TABLE queue_tasks (
138
- id TEXT PRIMARY KEY,
139
- description TEXT NOT NULL,
140
- type TEXT,
141
- priority TEXT,
142
- section TEXT,
143
- created_at TEXT NOT NULL,
144
- completed INTEGER DEFAULT 0,
145
- completed_at TEXT,
146
- feature_id TEXT,
147
- feature_name TEXT
148
- );
149
-
150
- CREATE INDEX idx_queue_tasks_section ON queue_tasks(section);
151
- CREATE INDEX idx_queue_tasks_priority ON queue_tasks(priority);
152
- CREATE INDEX idx_queue_tasks_completed ON queue_tasks(completed);
153
-
154
- -- =======================================================================
155
- -- Normalized: Ideas
156
- -- =======================================================================
157
- CREATE TABLE ideas (
158
- id TEXT PRIMARY KEY,
159
- text TEXT NOT NULL,
160
- status TEXT NOT NULL DEFAULT 'pending',
161
- priority TEXT NOT NULL DEFAULT 'medium',
162
- tags TEXT,
163
- added_at TEXT NOT NULL,
164
- converted_to TEXT,
165
- details TEXT,
166
- data TEXT
167
- );
168
-
169
- CREATE INDEX idx_ideas_status ON ideas(status);
170
- CREATE INDEX idx_ideas_priority ON ideas(priority);
171
-
172
- -- =======================================================================
173
- -- Normalized: Shipped Features
174
- -- =======================================================================
175
- CREATE TABLE shipped_features (
176
- id TEXT PRIMARY KEY,
177
- name TEXT NOT NULL,
178
- shipped_at TEXT NOT NULL,
179
- version TEXT NOT NULL,
180
- description TEXT,
181
- type TEXT,
182
- duration TEXT,
183
- data TEXT
184
- );
185
-
186
- CREATE INDEX idx_shipped_version ON shipped_features(version);
187
- CREATE INDEX idx_shipped_at ON shipped_features(shipped_at);
188
-
189
- -- =======================================================================
190
- -- Events (replaces events.jsonl)
191
- -- =======================================================================
192
- CREATE TABLE events (
193
- id INTEGER PRIMARY KEY AUTOINCREMENT,
194
- type TEXT NOT NULL,
195
- task_id TEXT,
196
- data TEXT,
197
- timestamp TEXT NOT NULL
198
- );
199
-
200
- CREATE INDEX idx_events_type ON events(type);
201
- CREATE INDEX idx_events_task_id ON events(task_id);
202
- CREATE INDEX idx_events_timestamp ON events(timestamp);
203
-
204
- -- =======================================================================
205
- -- Analysis (draft + sealed)
206
- -- =======================================================================
207
- CREATE TABLE analysis (
208
- id TEXT PRIMARY KEY,
209
- status TEXT NOT NULL,
210
- commit_hash TEXT,
211
- signature TEXT,
212
- sealed_at TEXT,
213
- analyzed_at TEXT,
214
- data TEXT NOT NULL
215
- );
216
-
217
- -- =======================================================================
218
- -- Index: File scores and checksums
219
- -- =======================================================================
220
- CREATE TABLE index_files (
221
- path TEXT PRIMARY KEY,
222
- score REAL,
223
- size INTEGER,
224
- mtime TEXT,
225
- language TEXT,
226
- categories TEXT,
227
- domain TEXT
228
- );
229
-
230
- CREATE INDEX idx_index_files_domain ON index_files(domain);
231
- CREATE INDEX idx_index_files_score ON index_files(score);
232
-
233
- CREATE TABLE index_checksums (
234
- path TEXT PRIMARY KEY,
235
- checksum TEXT NOT NULL,
236
- size INTEGER,
237
- mtime TEXT
238
- );
239
-
240
- -- =======================================================================
241
- -- Index: Metadata (project-index, domains, categories-cache)
242
- -- =======================================================================
243
- CREATE TABLE index_meta (
244
- key TEXT PRIMARY KEY,
245
- data TEXT NOT NULL,
246
- updated_at TEXT NOT NULL
247
- );
248
-
249
- -- =======================================================================
250
- -- Memory (key-value with domain tagging)
251
- -- =======================================================================
252
- CREATE TABLE memory (
253
- key TEXT PRIMARY KEY,
254
- domain TEXT,
255
- value TEXT,
256
- confidence REAL DEFAULT 1.0,
257
- updated_at TEXT NOT NULL
258
- );
259
-
260
- CREATE INDEX idx_memory_domain ON memory(domain);
261
-
262
- -- =======================================================================
263
- -- Metrics: Daily stats for trend analysis
264
- -- =======================================================================
265
- CREATE TABLE metrics_daily (
266
- date TEXT PRIMARY KEY,
267
- tokens_saved INTEGER NOT NULL DEFAULT 0,
268
- syncs INTEGER NOT NULL DEFAULT 0,
269
- avg_compression_rate REAL NOT NULL DEFAULT 0,
270
- total_duration INTEGER NOT NULL DEFAULT 0
271
- );
272
-
273
- -- =======================================================================
274
- -- Velocity: Sprint data
275
- -- =======================================================================
276
- CREATE TABLE velocity_sprints (
277
- sprint_number INTEGER PRIMARY KEY,
278
- points_completed REAL NOT NULL DEFAULT 0,
279
- tasks_completed INTEGER NOT NULL DEFAULT 0,
280
- estimation_accuracy REAL NOT NULL DEFAULT 0,
281
- avg_variance REAL NOT NULL DEFAULT 0,
282
- started_at TEXT,
283
- ended_at TEXT
284
- );
285
- `)},"up")},{version:2,name:"archives-table",up:l(r=>{r.run(`
286
- -- =======================================================================
287
- -- Archives: Stale data moved out of active storage (PRJ-267)
288
- -- =======================================================================
289
- CREATE TABLE archives (
290
- id TEXT PRIMARY KEY,
291
- entity_type TEXT NOT NULL,
292
- entity_id TEXT NOT NULL,
293
- entity_data TEXT NOT NULL,
294
- summary TEXT,
295
- archived_at TEXT NOT NULL,
296
- reason TEXT NOT NULL
297
- );
298
-
299
- CREATE INDEX idx_archives_entity_type ON archives(entity_type);
300
- CREATE INDEX idx_archives_archived_at ON archives(archived_at);
301
- CREATE INDEX idx_archives_entity_id ON archives(entity_id);
302
- `)},"up")}],ei=class{static{l(this,"PrjctDatabase")}connections=new Map;getDbPath(e){return Md.join(P.getGlobalProjectPath(e),"prjct.db")}getDb(e){let t=this.connections.get(e);if(t)return t;let n=this.getDbPath(e),s=Md.dirname(n);mc.existsSync(s)||mc.mkdirSync(s,{recursive:!0});let o=new sS(n,{create:!0});return o.run("PRAGMA journal_mode = WAL"),o.run("PRAGMA synchronous = NORMAL"),o.run("PRAGMA cache_size = -2000"),o.run("PRAGMA temp_store = MEMORY"),o.run("PRAGMA mmap_size = 268435456"),this.runMigrations(o),this.connections.set(e,o),o}close(e){if(e){let t=this.connections.get(e);t&&(t.close(),this.connections.delete(e))}else this.connections.forEach(t=>{t.close()}),this.connections.clear()}exists(e){return mc.existsSync(this.getDbPath(e))}getDoc(e,t){let s=this.getDb(e).prepare("SELECT data FROM kv_store WHERE key = ?").get(t);return s?JSON.parse(s.data):null}setDoc(e,t,n){let s=this.getDb(e),o=JSON.stringify(n),i=new Date().toISOString();s.prepare("INSERT OR REPLACE INTO kv_store (key, data, updated_at) VALUES (?, ?, ?)").run(t,o,i)}deleteDoc(e,t){this.getDb(e).prepare("DELETE FROM kv_store WHERE key = ?").run(t)}hasDoc(e,t){return this.getDb(e).prepare("SELECT 1 FROM kv_store WHERE key = ?").get(t)!==null}appendEvent(e,t,n,s){let o=this.getDb(e),i=new Date().toISOString();o.prepare("INSERT INTO events (type, task_id, data, timestamp) VALUES (?, ?, ?, ?)").run(t,s??null,JSON.stringify(n),i)}getEvents(e,t,n=100){let s=this.getDb(e);return t?s.prepare("SELECT * FROM events WHERE type = ? ORDER BY id DESC LIMIT ?").all(t,n):s.prepare("SELECT * FROM events ORDER BY id DESC LIMIT ?").all(n)}query(e,t,...n){return this.getDb(e).prepare(t).all(...n)}run(e,t,...n){this.getDb(e).prepare(t).run(...n)}get(e,t,...n){return this.getDb(e).prepare(t).get(...n)??null}transaction(e,t){let n=this.getDb(e);return n.transaction(t)(n)}runMigrations(e){e.run(`
303
- CREATE TABLE IF NOT EXISTS _migrations (
304
- version INTEGER PRIMARY KEY,
305
- name TEXT NOT NULL,
306
- applied_at TEXT NOT NULL
307
- )
308
- `);let t=new Set(e.prepare("SELECT version FROM _migrations").all().map(n=>n.version));for(let n of rS)t.has(n.version)||e.transaction(()=>{n.up(e),e.prepare("INSERT INTO _migrations (version, name, applied_at) VALUES (?, ?, ?)").run(n.version,n.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}},V=new ei,xt=V});import Fd from"node:fs/promises";import oS from"node:path";var Le,Qt=y(()=>{"use strict";dc();ee();Zo();ne();Yt();Le=class{static{l(this,"StorageManager")}filename;cache;constructor(e,t){this.filename=e,this.cache=new Ot({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}getContextPath(e,t){let n=this.getLayer();return P.getFilePath(e,n,t)}async read(e){let t=this.cache.get(e);if(t!==null)return t;try{let n=V.getDoc(e,this.getStoreKey());if(n!==null)return this.cache.set(e,n),n}catch{}return this.getDefault()}async write(e,t){let n=this.getContextPath(e,this.getMdFilename());await Fd.mkdir(oS.dirname(n),{recursive:!0}),V.setDoc(e,this.getStoreKey(),t);let s=this.toMarkdown(t);await Fd.writeFile(n,s,"utf-8"),this.cache.set(e,t)}async update(e,t){let n=await this.read(e),s=t(n);return await this.write(e,s),s}async publishEvent(e,t,n){let s={type:t,path:[this.filename.replace(".json","")],data:n,timestamp:b(),projectId:e};await Us.publish(s)}async publishEntityEvent(e,t,n,s){let o=`${t}.${n}`,i={...s,timestamp:b()};await this.publishEvent(e,o,i)}async exists(e){try{return V.hasDoc(e,this.getStoreKey())}catch{return!1}}clearCache(e){e?this.cache.delete(e):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});var gc,pn,Ir=y(()=>{"use strict";Vo();ne();Qt();gc=class extends Le{static{l(this,"MetricsStorage")}constructor(){super("metrics.json",Cd)}getDefault(){return{...vd}}getMdFilename(){return"metrics.md"}getLayer(){return"context"}getEventType(e){return`metrics.${e}d`}toMarkdown(e){let t=["# Value Dashboard \u{1F4CA}",""];if(e.syncCount===0)return t.push("_No metrics yet. Run `prjct sync` to start tracking._"),t.push(""),t.join(`
309
- `);if(t.push("## \u{1F4B0} Token Savings"),t.push(""),t.push(`- **Total saved**: ${this.formatTokens(e.totalTokensSaved)} tokens`),t.push(`- **Compression**: ${(e.avgCompressionRate*100).toFixed(0)}% average reduction`),t.push(`- **Estimated cost saved**: ${Ns(uc(e.totalTokensSaved))}`),t.push(""),t.push("## \u26A1 Performance"),t.push(""),t.push(`- **Syncs completed**: ${e.syncCount.toLocaleString()}`),t.push(`- **Avg sync time**: ${this.formatDuration(e.avgSyncDuration)}`),e.watchTriggers>0&&t.push(`- **Watch triggers**: ${e.watchTriggers.toLocaleString()} auto-syncs`),t.push(""),e.agentUsage.length>0){t.push("## \u{1F916} Agent Usage"),t.push("");let n=[...e.agentUsage].sort((o,i)=>i.usageCount-o.usageCount),s=n.reduce((o,i)=>o+i.usageCount,0);n.slice(0,5).forEach(o=>{let i=s>0?(o.usageCount/s*100).toFixed(0):0;t.push(`- **${o.agentName}**: ${i}% (${o.usageCount} uses)`)}),t.push("")}if(e.dailyStats.length>0){t.push("## \u{1F4C8} 30-Day Trend"),t.push("");let n=this.getLast30Days(e.dailyStats),s=n.reduce((o,i)=>o+i.tokensSaved,0);t.push(`- **Tokens saved**: ${this.formatTokens(s)}`),t.push(`- **Syncs**: ${n.reduce((o,i)=>o+i.syncs,0)}`),t.push(""),t.push("```"),t.push(this.generateSparkline(n)),t.push("```"),t.push("")}return t.push("---"),t.push(""),e.firstSync&&t.push(`_Tracking since ${new Date(e.firstSync).toLocaleDateString()}_`),t.push(""),t.join(`
310
- `)}async recordSync(e,t){let n=Math.max(0,t.originalSize-t.filteredSize),s=t.originalSize>0?n/t.originalSize:0,o=new Date().toISOString().split("T")[0];await this.update(e,i=>{let a=i.syncCount+1,c=i.totalTokensSaved+n,u=i.totalSyncDuration+t.duration,p=i.syncCount===0?s:(i.avgCompressionRate*i.syncCount+s)/a,m=[...i.dailyStats],d=m.findIndex(x=>x.date===o);if(d>=0){let x=m[d];m[d]={...x,tokensSaved:x.tokensSaved+n,syncs:x.syncs+1,avgCompressionRate:(x.avgCompressionRate*x.syncs+s)/(x.syncs+1),totalDuration:x.totalDuration+t.duration}}else m.push({date:o,tokensSaved:n,syncs:1,avgCompressionRate:s,totalDuration:t.duration});let g=new Date;g.setDate(g.getDate()-90);let f=g.toISOString().split("T")[0],S=m.filter(x=>x.date>=f),E=[...i.agentUsage];if(t.agents)for(let x of t.agents){let $=E.findIndex(z=>z.agentName===x);$>=0?E[$]={...E[$],usageCount:E[$].usageCount+1,tokensSaved:E[$].tokensSaved+Math.floor(n/t.agents.length)}:E.push({agentName:x,usageCount:1,tokensSaved:Math.floor(n/t.agents.length)})}return{totalTokensSaved:c,avgCompressionRate:p,syncCount:a,watchTriggers:i.watchTriggers+(t.isWatch?1:0),avgSyncDuration:u/a,totalSyncDuration:u,agentUsage:E,dailyStats:S,firstSync:i.firstSync||b(),lastUpdated:b()}})}async getSummary(e){let t=await this.read(e),n=this.getLast30Days(t.dailyStats),s=this.getPrev30Days(t.dailyStats),o=n.reduce((c,u)=>c+u.tokensSaved,0),i=s.reduce((c,u)=>c+u.tokensSaved,0),a=i>0?(o-i)/i*100:0;return{totalTokensSaved:t.totalTokensSaved,estimatedCostSaved:uc(t.totalTokensSaved),compressionRate:t.avgCompressionRate,syncCount:t.syncCount,avgSyncDuration:t.avgSyncDuration,topAgents:[...t.agentUsage].sort((c,u)=>u.usageCount-c.usageCount).slice(0,5),last30DaysTokens:o,trend:a}}async getDailyStats(e,t=30){let n=await this.read(e),s=new Date;s.setDate(s.getDate()-t);let o=s.toISOString().split("T")[0];return n.dailyStats.filter(i=>i.date>=o).sort((i,a)=>i.date.localeCompare(a.date))}getLast30Days(e){let t=new Date;t.setDate(t.getDate()-30);let n=t.toISOString().split("T")[0];return e.filter(s=>s.date>=n)}getPrev30Days(e){let t=new Date;t.setDate(t.getDate()-30);let n=new Date;n.setDate(n.getDate()-60);let s=n.toISOString().split("T")[0],o=t.toISOString().split("T")[0];return e.filter(i=>i.date>=s&&i.date<o)}formatTokens(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}formatDuration(e){return e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}generateSparkline(e){if(e.length===0)return"";let t="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",n=e.map(o=>o.tokensSaved),s=Math.max(...n,1);return n.map(o=>{let i=Math.min(Math.floor(o/s*(t.length-1)),t.length-1);return t[i]}).join("")}},pn=new gc});import{exec as iS}from"node:child_process";import aS from"node:fs/promises";import ti from"node:path";import{promisify as cS}from"node:util";async function Dr(r,e,t={}){let n=Date.now(),s=t.maxFiles??30,o=t.minScore??.1,i=t.includeTests??!1,a=mS(r),c=await gS(e),u=await fS(e),p=[];for(let d of c){if(!i&&yS(d))continue;let g=hS(d,a,u);g.score>=o&&p.push(g)}p.sort((d,g)=>g.score-d.score);let m=p.slice(0,s);return{files:m,metrics:{filesScanned:c.length,filesReturned:m.length,scanDuration:Date.now()-n}}}function mS(r){let e=r.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean),t=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 e.filter(n=>!t.has(n)&&n.length>2)}async function gS(r){let e=[];async function t(n,s=""){try{let o=await aS.readdir(n,{withFileTypes:!0});for(let i of o){let a=ti.join(n,i.name),c=ti.join(s,i.name);if(i.isDirectory()){if(dS.has(i.name)||i.name.startsWith("."))continue;await t(a,c)}else if(i.isFile()){let u=ti.extname(i.name).toLowerCase();pS.has(u)&&e.push(c)}}}catch(o){k(o)}}return l(t,"walk"),await t(r),e}async function fS(r){let e=new Map;try{let{stdout:t}=await lS(`git log -30 --pretty=format:"%H %ct" --name-only | awk '
311
- /^[a-f0-9]{40}/ { commit=$1; timestamp=$2; next }
312
- NF { files[$0]++; if (!lastmod[$0]) lastmod[$0]=timestamp }
313
- END { for (f in files) print files[f], lastmod[f], f }
314
- '`,{cwd:r,maxBuffer:10485760}),n=Math.floor(Date.now()/1e3),s=t.trim().split(`
315
- `).filter(Boolean);for(let o of s){let i=o.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(i){let a=parseInt(i[1],10),c=parseInt(i[2],10),u=i[3],p=Math.floor((n-c)/86400);e.set(u,{commits:a,daysAgo:p})}}}catch{}return e}function hS(r,e,t){let n=[],s=0,o=0,i=0,a=0,c=r.toLowerCase(),u=c.split("/").join(" ").split(/[^a-z0-9]+/);for(let g of e){c.includes(g)&&(s+=.3,n.push(`keyword:${g}`));for(let f of u)if(f.includes(g)||g.includes(f)){s+=.15;break}}s=Math.min(1,s);for(let[g,f]of Object.entries(uS))for(let S of f)if(c.includes(S)&&e.some(x=>f.includes(x)||x.includes(g)||g.includes(x))){o+=.4,n.push(`domain:${g}`);break}o=Math.min(1,o);let p=t.get(r);p&&(p.daysAgo<=1?(i=1,n.push("recent:1d")):p.daysAgo<=3?(i=.8,n.push("recent:3d")):p.daysAgo<=7?(i=.6,n.push("recent:1w")):p.daysAgo<=30&&(i=.3,n.push("recent:1m")),p.commits>=5&&(i=Math.min(1,i+.2)));let m=ti.basename(r).toLowerCase();(m.includes("index")||m.includes("main")||m.includes("app")||m.includes("entry"))&&(a=.5,n.push("import:0")),(c.includes("/core/")||c.includes("/shared/")||c.includes("/lib/"))&&(a=Math.max(a,.3),n.some(g=>g.startsWith("import:"))||n.push("import:1"));let d=s*.6+o*.2+i*.15+a*.05;return{path:r,score:Math.min(1,d),reasons:[...new Set(n)]}}function yS(r){let e=r.toLowerCase();return e.includes(".test.")||e.includes(".spec.")||e.includes("__tests__")||e.includes("__mocks__")||e.includes("/tests/")||e.includes("/test/")||e.endsWith("_test.go")||e.endsWith("_test.py")}var lS,uS,pS,dS,fc=y(()=>{"use strict";M();lS=cS(iS),uS={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"]},pS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".swift",".rb",".php",".c",".cpp",".h",".hpp",".cs",".vue",".svelte"]),dS=new Set(["node_modules",".git","dist","build",".next",".nuxt",".output","coverage",".cache","__pycache__",".pytest_cache","vendor","target",".turbo",".vercel"]);l(Dr,"findRelevantFiles");l(mS,"extractKeywords");l(gS,"getAllCodeFiles");l(fS,"getGitRecency");l(hS,"scoreFile");l(yS,"isTestFile")});import{exec as wS}from"node:child_process";import Nd from"node:fs/promises";import Zt from"node:path";import{promisify as kS}from"node:util";async function Hs(r,e=process.cwd(),t={}){let n=Zt.isAbsolute(r)?r:Zt.join(e,r),s;try{s=await Nd.readFile(n,"utf-8")}catch(g){if(k(g))return{file:r,imports:[],importedBy:[],metrics:{totalImports:0,externalImports:0,internalImports:0,importedByCount:0}};throw g}let o=Zt.extname(r).toLowerCase(),i=vS[o]||"unknown",a=CS[i]||[],c=await xS(s,a,n,e),u=[];t.reverse&&(u=await ES(r,e));let p;t.depth&&t.depth>0&&(p=await Ld(r,e,t.depth));let m=c.filter(g=>g.isExternal).length,d=c.filter(g=>!g.isExternal).length;return{file:r,imports:c,importedBy:u,dependencyTree:p,metrics:{totalImports:c.length,externalImports:m,internalImports:d,importedByCount:u.length}}}async function xS(r,e,t,n){let s=[],o=new Set;for(let i of e){i.pattern.lastIndex=0;let a;for(;(a=i.pattern.exec(r))!==null;){let c=a[i.sourceIndex];if(!c||o.has(c))continue;o.add(c);let u;if(i.namesIndex!==void 0){let d=a[i.namesIndex];d&&(u=d.split(",").map(g=>g.trim().split(" as ")[0].trim()).filter(Boolean))}let p=!c.startsWith(".")&&!c.startsWith("/")&&!c.startsWith("@/"),m=null;p||(m=await TS(c,t,n)),s.push({source:c,resolved:m,isExternal:p,importedNames:u,isDefault:i.isDefault,isNamespace:i.isNamespace})}}return s}async function TS(r,e,t){let n=Zt.dirname(e);if(r.startsWith("@/")){let o=Zt.join(t,"src",r.slice(2));return _d(o,t)}let s=Zt.resolve(n,r);return _d(s,t)}async function _d(r,e){let t=["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let n of t){let s=r+n;try{if((await Nd.stat(s)).isFile())return Zt.relative(e,s)}catch{}}return null}async function ES(r,e){let t=[],n=Zt.basename(r,Zt.extname(r)),s=Zt.dirname(r);try{let i=[`from ['"].*${n}['"]`,`from ['"]\\./${n}['"]`,`import\\(['"'].*${n}['"]`,`require\\(['"'].*${n}['"]`].join("|"),{stdout:a}=await SS(`grep -r -l -E '${i}' --include='*.ts' --include='*.tsx' --include='*.js' --include='*.jsx' . 2>/dev/null || true`,{cwd:e,maxBuffer:10*1024*1024}),c=a.trim().split(`
316
- `).filter(Boolean).map(u=>u.replace(/^\.\//,"")).filter(u=>u!==r);for(let u of c)t.push({file:u})}catch{}return t}async function Ld(r,e,t,n=0,s=new Set){let o={file:r,imports:[],depth:n};if(n>=t||s.has(r))return o;s.add(r);let i=await Hs(r,e,{reverse:!1,depth:0});for(let a of i.imports)if(!a.isExternal&&a.resolved){let c=await Ld(a.resolved,e,t,n+1,s);o.imports.push(c)}return o}var SS,Od,bS,PS,CS,vS,hc=y(()=>{"use strict";M();SS=kS(wS),Od=[{pattern:/import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,sourceIndex:2,namesIndex:1},{pattern:/import\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,sourceIndex:2,namesIndex:1,isDefault:!0},{pattern:/import\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,sourceIndex:2,namesIndex:1,isNamespace:!0},{pattern:/import\s*['"]([^'"]+)['"]/g,sourceIndex:1},{pattern:/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,sourceIndex:1},{pattern:/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,sourceIndex:1}],bS=[{pattern:/from\s+([\w.]+)\s+import\s+([^;\n]+)/g,sourceIndex:1,namesIndex:2},{pattern:/^import\s+([\w.]+)(?:\s+as\s+\w+)?$/gm,sourceIndex:1}],PS=[{pattern:/import\s*"([^"]+)"/g,sourceIndex:1},{pattern:/import\s*\([^)]*"([^"]+)"[^)]*\)/g,sourceIndex:1}],CS={typescript:Od,javascript:Od,python:bS,go:PS},vS={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".go":"go"};l(Hs,"analyzeImports");l(xS,"extractImports");l(TS,"resolveImport");l(_d,"tryResolve");l(ES,"findImportedBy");l(Ld,"buildDependencyTree")});import{exec as jS}from"node:child_process";import{promisify as AS}from"node:util";async function $r(r=process.cwd(),e={}){let t=e.commits??30,n=e.maxFiles??50,s=e.branch??!1;try{let o=[],i=[],a=`${t} commits`;if(s){let c=await RS(r);o=c.hotFiles,i=c.branchOnlyFiles,a=c.analysisWindow}else o=await DS(r,t);return o=o.filter(c=>!$S(c.path)).slice(0,n),{hotFiles:o,branchOnlyFiles:i,metrics:{commitsAnalyzed:t,totalFilesChanged:o.length,filesReturned:Math.min(o.length,n),analysisWindow:a}}}catch{return{hotFiles:[],branchOnlyFiles:[],metrics:{commitsAnalyzed:0,totalFilesChanged:0,filesReturned:0,analysisWindow:"N/A (git error)"}}}}async function DS(r,e){let{stdout:t}=await Rr(`git log -${e} --pretty=format:"%ct" --name-only | awk '
317
- /^[0-9]+$/ { timestamp=$1; next }
318
- NF {
319
- count[$0]++
320
- if (!lastmod[$0] || timestamp > lastmod[$0]) lastmod[$0]=timestamp
321
- }
322
- END {
323
- for (f in count) print count[f], lastmod[f], f
324
- }
325
- ' | sort -rn`,{cwd:r,maxBuffer:10485760}),n=[],s=t.trim().split(`
326
- `).filter(Boolean),o=Math.floor(Date.now()/1e3),i=1;for(let a of s){let c=a.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(c){let u=parseInt(c[1],10);u>i&&(i=u)}}for(let a of s){let c=a.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(!c)continue;let u=parseInt(c[1],10),p=parseInt(c[2],10),m=c[3],d=o-p,g=Math.floor(d/86400),f=Math.floor(d/3600),S=Math.max(0,1-g/30),E=u/i,x=S*.6+E*.4,$;f<1?$="just now":f<24?$=`${f}h ago`:g<7?$=`${g}d ago`:g<30?$=`${Math.floor(g/7)}w ago`:$=`${Math.floor(g/30)}mo ago`,n.push({path:m,changes:u,heatScore:Math.round(x*100)/100,lastChanged:$,lastChangedAt:new Date(p*1e3).toISOString()})}return n.sort((a,c)=>c.heatScore-a.heatScore)}async function RS(r){let{stdout:e}=await Rr("git branch --show-current",{cwd:r}),t=e.trim(),n="main";try{await Rr("git rev-parse --verify main",{cwd:r})}catch{n="master"}let{stdout:s}=await Rr(`git diff --name-only ${n}...HEAD`,{cwd:r}),o=s.trim().split(`
327
- `).filter(Boolean),{stdout:i}=await Rr(`git log ${n}..HEAD --pretty=format:"%ct" --name-only | awk '
328
- /^[0-9]+$/ { timestamp=$1; next }
329
- NF {
330
- count[$0]++
331
- if (!lastmod[$0] || timestamp > lastmod[$0]) lastmod[$0]=timestamp
332
- }
333
- END {
334
- for (f in count) print count[f], lastmod[f], f
335
- }
336
- '`,{cwd:r,maxBuffer:10*1024*1024}),a=[],c=i.trim().split(`
337
- `).filter(Boolean),u=Math.floor(Date.now()/1e3),p=1;for(let m of c){let d=m.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(d){let g=parseInt(d[1],10);g>p&&(p=g)}}for(let m of c){let d=m.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(!d)continue;let g=parseInt(d[1],10),f=parseInt(d[2],10),S=d[3],E=u-f,x=Math.floor(E/86400),$=Math.floor(E/3600),z=Math.max(0,1-x/14),_e=g/p,nt=z*.5+_e*.5,Dt;$<1?Dt="just now":$<24?Dt=`${$}h ago`:Dt=`${x}d ago`,a.push({path:S,changes:g,heatScore:Math.round(nt*100)/100,lastChanged:Dt,lastChangedAt:new Date(f*1e3).toISOString()})}return{hotFiles:a.sort((m,d)=>d.heatScore-m.heatScore),branchOnlyFiles:o,analysisWindow:`${n}..HEAD`}}function $S(r){let e=r.split("/").pop()||"";for(let t of IS)if(t.startsWith("*.")){if(e.endsWith(t.slice(1)))return!0}else if(e===t)return!0;return!1}var Rr,IS,yc=y(()=>{"use strict";Rr=AS(jS),IS=["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb",".gitignore",".env",".env.local","*.md","CHANGELOG.md","LICENSE"];l($r,"getRecentFiles");l(DS,"getHotFilesFromCommits");l(RS,"getBranchOnlyFiles");l($S,"shouldIgnore")});function ni(r){return!r||r.length===0?0:Math.ceil(r.length/4)}function Ud(r,e){let t=MS[e],n=r/1e3*t.input,s=r/1e3*t.output*.3;return{inputSaved:n,outputPotential:s,total:n+s}}function kc(r){return r<.001?"<$0.01":r<.01?`$${r.toFixed(3)}`:`$${r.toFixed(2)}`}function Mr(r,e){let t=ni(r),n=ni(e),s=Math.max(0,t-n),o=t>0?(t-n)/t:0,i=Ud(s,FS),a=wc.map(c=>({model:c,...Ud(s,c)}));return{tokens:{original:t,filtered:n,saved:s},compression:Math.max(0,Math.min(1,o)),cost:{saved:i.total,formatted:kc(i.total),byModel:a}}}function Kn(r){let e=ni(r);return{tokens:{original:e,filtered:e,saved:0},compression:0,cost:{saved:0,formatted:"$0.00",byModel:wc.map(t=>({model:t,inputSaved:0,outputPotential:0,total:0}))}}}function si(r){if(r.length===0)return Kn("");let e=r.reduce((a,c)=>a+c.tokens.original,0),t=r.reduce((a,c)=>a+c.tokens.filtered,0),n=r.reduce((a,c)=>a+c.tokens.saved,0),s=e>0?(e-t)/e:0,o=wc.map(a=>{let c=r.map(u=>u.cost.byModel.find(p=>p.model===a)||{inputSaved:0,outputPotential:0,total:0});return{model:a,inputSaved:c.reduce((u,p)=>u+p.inputSaved,0),outputPotential:c.reduce((u,p)=>u+p.outputPotential,0),total:c.reduce((u,p)=>u+p.total,0)}}),i=r.reduce((a,c)=>a+c.cost.saved,0);return{tokens:{original:e,filtered:t,saved:n},compression:s,cost:{saved:i,formatted:kc(i),byModel:o}}}function OS(r){return r>=1e6?`${(r/1e6).toFixed(1)}M`:r>=1e3?`${(r/1e3).toFixed(1)}K`:r.toLocaleString()}function _S(r){return`${Math.round(r*100)}%`}var MS,FS,wc,Fr=y(()=>{"use strict";MS={"claude-opus-4.5":{input:.005,output:.025},"claude-sonnet-4.5":{input:.003,output:.015},"claude-haiku-4.5":{input:.001,output:.005},"claude-opus-4":{input:.015,output:.075},"claude-opus-4-6":{input:.015,output:.075},"gpt-4o":{input:.0025,output:.01},"gpt-4-turbo":{input:.01,output:.03},"gpt-4o-mini":{input:15e-5,output:6e-4},"gemini-1.5-pro":{input:.00125,output:.005},"gemini-1.5-flash":{input:75e-6,output:3e-4}},FS="claude-sonnet-4.5";l(ni,"countTokens");wc=["claude-sonnet-4.5","claude-opus-4.5","claude-opus-4-6","gpt-4o","gemini-1.5-pro"];l(Ud,"calculateModelCost");l(kc,"formatCostSaved");l(Mr,"measureCompression");l(Kn,"noCompression");l(si,"combineMetrics");l(OS,"formatTokenCount");l(_S,"formatCompressionRate")});import zd from"node:fs/promises";import vn from"node:path";async function xn(r,e=process.cwd()){let t=vn.isAbsolute(r)?r:vn.join(e,r),n;try{n=await zd.readFile(t,"utf-8")}catch(u){if(k(u))return{file:r,language:"unknown",signatures:[],fallback:!0,fallbackReason:"File not found",metrics:Kn("")};throw u}let s=vn.extname(r).toLowerCase(),o=Jd[s]||"unknown",i=HS[o];if(!i||i.length===0)return{file:r,language:o,signatures:[],fallback:!0,fallbackReason:`No extraction patterns for ${o}`,metrics:Kn(n)};let a=GS(n,i),c=a.map(u=>`${u.exported?"export ":""}${u.type} ${u.name}: ${u.signature}`).join(`
338
- `);return{file:r,language:o,signatures:a,fallback:!1,metrics:Mr(n,c)}}async function Sc(r,e=process.cwd(),t={}){let n=vn.isAbsolute(r)?r:vn.join(e,r),s=[];async function o(i){let a=await zd.readdir(i,{withFileTypes:!0});for(let c of a){let u=vn.join(i,c.name),p=vn.relative(e,u);if(c.isDirectory()){if(c.name==="node_modules"||c.name===".git"||c.name.startsWith("."))continue;t.recursive&&await o(u)}else if(c.isFile()){let m=vn.extname(c.name).toLowerCase();if(Jd[m]){let d=await xn(p,e);s.push(d)}}}}return l(o,"processDir"),await o(n),s}function GS(r,e){let t=[],n=r.split(`
339
- `),s=new Set;for(let o of e){o.pattern.lastIndex=0;let i;for(;(i=o.pattern.exec(r))!==null;){let a=i[o.nameIndex];if(!a)continue;let c=`${o.type}:${a}`;if(s.has(c))continue;s.add(c);let u=i.index,p=r.substring(0,u).split(`
340
- `).length,m=i[0].trim(),d;if(p>1){let g=n[p-2]?.trim();(g?.startsWith("/**")||g?.startsWith("///")||g?.startsWith("#"))&&(d=g)}t.push({type:o.type,name:a,signature:zS(m),exported:o.exported||!1,line:p,docstring:d})}}return t.sort((o,i)=>o.line-i.line)}function zS(r){return r.replace(/\{$/,"").replace(/\s+/g," ").trim()}var Jd,Hd,NS,LS,US,Gd,HS,ri=y(()=>{"use strict";M();Fr();Jd={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".go":"go",".rs":"rust",".java":"java",".cs":"csharp",".php":"php",".rb":"ruby"},Hd=[{type:"function",pattern:/^export\s+(?:async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)\s*(?::\s*([^{;]+))?/gm,nameIndex:1,exported:!0},{type:"function",pattern:/^export\s+const\s+(\w+)\s*(?::\s*[^=]+)?\s*=\s*(?:async\s+)?\([^)]*\)\s*(?::\s*[^=]+)?\s*=>/gm,nameIndex:1,exported:!0},{type:"function",pattern:/^(?:async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)\s*(?::\s*([^{;]+))?/gm,nameIndex:1},{type:"function",pattern:/^const\s+(\w+)\s*(?::\s*[^=]+)?\s*=\s*(?:async\s+)?\([^)]*\)\s*(?::\s*[^=]+)?\s*=>/gm,nameIndex:1},{type:"interface",pattern:/^export\s+interface\s+(\w+)(?:<[^>]+>)?\s*(?:extends\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"interface",pattern:/^interface\s+(\w+)(?:<[^>]+>)?\s*(?:extends\s+[^{]+)?\s*\{/gm,nameIndex:1},{type:"type",pattern:/^export\s+type\s+(\w+)(?:<[^>]+>)?\s*=/gm,nameIndex:1,exported:!0},{type:"type",pattern:/^type\s+(\w+)(?:<[^>]+>)?\s*=/gm,nameIndex:1},{type:"class",pattern:/^export\s+(?:abstract\s+)?class\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+[^{]+)?(?:\s+implements\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"class",pattern:/^(?:abstract\s+)?class\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+[^{]+)?(?:\s+implements\s+[^{]+)?\s*\{/gm,nameIndex:1},{type:"enum",pattern:/^export\s+enum\s+(\w+)\s*\{/gm,nameIndex:1,exported:!0},{type:"enum",pattern:/^enum\s+(\w+)\s*\{/gm,nameIndex:1},{type:"const",pattern:/^export\s+const\s+(\w+)\s*(?::\s*([^=]+))?\s*=/gm,nameIndex:1,exported:!0}],NS=[{type:"function",pattern:/^def\s+(\w+)\s*\(([^)]*)\)\s*(?:->\s*([^:]+))?\s*:/gm,nameIndex:1},{type:"function",pattern:/^async\s+def\s+(\w+)\s*\(([^)]*)\)\s*(?:->\s*([^:]+))?\s*:/gm,nameIndex:1},{type:"class",pattern:/^class\s+(\w+)(?:\(([^)]*)\))?\s*:/gm,nameIndex:1}],LS=[{type:"function",pattern:/^func\s+(\w+)\s*\(([^)]*)\)\s*(?:\(([^)]*)\)|([^\s{]+))?\s*\{/gm,nameIndex:1},{type:"method",pattern:/^func\s+\([^)]+\)\s+(\w+)\s*\(([^)]*)\)\s*(?:\(([^)]*)\)|([^\s{]+))?\s*\{/gm,nameIndex:1},{type:"type",pattern:/^type\s+(\w+)\s+(?:struct|interface)\s*\{/gm,nameIndex:1}],US=[{type:"function",pattern:/^pub\s+(?:async\s+)?fn\s+(\w+)(?:<[^>]+>)?\s*\(([^)]*)\)\s*(?:->\s*([^{]+))?\s*\{/gm,nameIndex:1,exported:!0},{type:"function",pattern:/^(?:async\s+)?fn\s+(\w+)(?:<[^>]+>)?\s*\(([^)]*)\)\s*(?:->\s*([^{]+))?\s*\{/gm,nameIndex:1},{type:"class",pattern:/^pub\s+struct\s+(\w+)(?:<[^>]+>)?\s*(?:\{|;)/gm,nameIndex:1,exported:!0},{type:"class",pattern:/^struct\s+(\w+)(?:<[^>]+>)?\s*(?:\{|;)/gm,nameIndex:1},{type:"interface",pattern:/^pub\s+trait\s+(\w+)(?:<[^>]+>)?\s*(?:\{|:)/gm,nameIndex:1,exported:!0},{type:"interface",pattern:/^trait\s+(\w+)(?:<[^>]+>)?\s*(?:\{|:)/gm,nameIndex:1},{type:"enum",pattern:/^pub\s+enum\s+(\w+)(?:<[^>]+>)?\s*\{/gm,nameIndex:1,exported:!0},{type:"enum",pattern:/^enum\s+(\w+)(?:<[^>]+>)?\s*\{/gm,nameIndex:1}],Gd=[{type:"class",pattern:/^(?:public\s+)?(?:abstract\s+)?(?:final\s+)?class\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+\w+)?(?:\s+implements\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"interface",pattern:/^(?:public\s+)?interface\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"method",pattern:/^\s+(?:public|private|protected)?\s*(?:static\s+)?(?:final\s+)?(?:synchronized\s+)?(?:<[^>]+>\s+)?(\w+(?:<[^>]+>)?)\s+(\w+)\s*\([^)]*\)\s*(?:throws\s+[^{]+)?\s*\{/gm,nameIndex:2}],HS={typescript:Hd,javascript:Hd,python:NS,go:LS,rust:US,java:Gd,csharp:Gd,php:[],ruby:[],unknown:[]};l(xn,"extractSignatures");l(Sc,"extractDirectorySignatures");l(GS,"extractFromContent");l(zS,"cleanSignature")});import Wd from"node:fs/promises";import en from"node:path";async function oi(r,e=process.cwd()){let t=en.isAbsolute(r)?r:en.join(e,r),n;try{n=await Wd.readFile(t,"utf-8")}catch(d){if(k(d))return{file:r,purpose:"File not found",publicAPI:[],dependencies:[],metrics:Kn("")};throw d}let s=en.extname(r).toLowerCase(),o=Bd[s]||"unknown",i=await xn(r,e),a=await Hs(r,e),c=WS(n,o),u=i.signatures.filter(d=>d.exported).map(d=>({name:d.name,type:d.type,signature:d.signature,description:d.docstring?BS(d.docstring):void 0})),p=a.imports.filter(d=>!d.isExternal&&d.resolved).map(d=>d.resolved).slice(0,10),m=VS(c,u,p);return{file:r,purpose:c,publicAPI:u,dependencies:p,metrics:Mr(n,m)}}async function bc(r,e=process.cwd(),t={}){let n=en.isAbsolute(r)?r:en.join(e,r),s=[];async function o(i){let a=await Wd.readdir(i,{withFileTypes:!0});for(let c of a){let u=en.join(i,c.name),p=en.relative(e,u);if(c.isDirectory()){if(c.name==="node_modules"||c.name===".git"||c.name.startsWith("."))continue;t.recursive&&await o(u)}else if(c.isFile()){let m=en.extname(c.name).toLowerCase();if(Bd[m]){let d=await oi(p,e);s.push(d)}}}}return l(o,"processDir"),await o(n),s}function WS(r,e){let t=JS[e]||[],n=r.split(`
341
- `);for(let o=0;o<Math.min(30,n.length);o++){let i=n[o].trim();for(let a of t)if(a.start.test(i)){if(a.singleLine){let c=[],u=o;for(;u<n.length&&a.start.test(n[u].trim());)c.push(n[u].trim().replace(a.start,"").trim()),u++;if(c.length>0)return c.slice(0,3).join(" ").trim()}else if(a.end){let c="",u=o;for(;u<n.length&&(c+=`${n[u]}
342
- `,!a.end.test(n[u]));)u++;let p=c.replace(a.start,"").replace(a.end,"").split(`
343
- `).map(m=>m.replace(/^\s*\*\s?/,"").trim()).filter(m=>m.length>0&&!m.startsWith("@"));if(p.length>0)return p.slice(0,2).join(" ").trim()}}if(i.length>0&&!i.startsWith("//")&&!i.startsWith("#")&&!i.startsWith("/*")&&!i.startsWith("*")&&!i.startsWith("'")&&!i.startsWith('"'))break}let s=r.split(`
344
- `)[0]||"";return`Module: ${en.basename(s,en.extname(s))}`}function BS(r){return r.replace(/^\/\*\*\s*/,"").replace(/\*\/$/,"").replace(/^\/\/\/?\s*/,"").replace(/^#\s*/,"").replace(/^"""\s*/,"").replace(/"""\s*$/,"").trim().split(`
345
- `)[0].trim()}function VS(r,e,t){let n=[];if(n.push(`Purpose: ${r}`),n.push(""),e.length>0){n.push("Public API:");for(let s of e){let o=s.description?` - ${s.description}`:"";n.push(` ${s.type} ${s.name}: ${s.signature}${o}`)}n.push("")}return t.length>0&&n.push(`Dependencies: ${t.join(", ")}`),n.join(`
346
- `)}var JS,Bd,Vd=y(()=>{"use strict";M();hc();ri();Fr();JS={typescript:[{start:/\/\*\*/,end:/\*\//},{start:/\/\/\//,end:null,singleLine:!0}],javascript:[{start:/\/\*\*/,end:/\*\//}],python:[{start:/"""/,end:/"""/},{start:/'''/,end:/'''/}],go:[{start:/\/\//,end:null,singleLine:!0}],rust:[{start:/\/\/\//,end:null,singleLine:!0},{start:/\/\/!/,end:null,singleLine:!0}]},Bd={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".py":"python",".go":"go",".rs":"rust"};l(oi,"summarizeFile");l(bc,"summarizeDirectory");l(WS,"extractFilePurpose");l(BS,"extractDescriptionFromDocstring");l(VS,"buildSummaryText")});var qd=y(()=>{"use strict"});var Kd={};Ne(Kd,{analyzeImports:()=>Hs,combineMetrics:()=>si,countTokens:()=>ni,extractDirectorySignatures:()=>Sc,extractSignatures:()=>xn,findRelevantFiles:()=>Dr,formatCompressionRate:()=>_S,formatCostSaved:()=>kc,formatTokenCount:()=>OS,getRecentFiles:()=>$r,measureCompression:()=>Mr,noCompression:()=>Kn,runContextTool:()=>qS,summarizeDirectory:()=>bc,summarizeFile:()=>oi});async function qS(r,e,t){let n=Date.now(),[s,...o]=r;try{let i;switch(s){case"files":i=await KS(o,t);break;case"signatures":i=await XS(o,t);break;case"imports":i=await YS(o,t);break;case"recent":i=await QS(o,t);break;case"summary":i=await ZS(o,t);break;case"help":return{tool:"error",result:{error:sb(),code:"HELP"}};default:return{tool:"error",result:{error:`Unknown tool: ${s}. Use 'prjct context help' for usage.`,code:"UNKNOWN_TOOL"}}}let a=Date.now()-n,c=eb(i),u=tb(i);return await nb(e,{tool:s,timestamp:b(),inputArgs:o.join(" "),tokensSaved:c,compressionRate:u,duration:a}),i}catch(i){return{tool:"error",result:{error:w(i),code:"EXECUTION_ERROR"}}}}async function KS(r,e){let t={},n=[];for(let i=0;i<r.length;i++)r[i]==="--max"&&r[i+1]?t.maxFiles=parseInt(r[++i],10):r[i]==="--min-score"&&r[i+1]?t.minScore=parseFloat(r[++i]):r[i]==="--include-tests"?t.includeTests=!0:n.push(r[i]);let s=n.join(" ");return s?{tool:"files",result:await Dr(s,e,t)}:{tool:"error",result:{error:'Usage: prjct context files "<task description>"',code:"MISSING_ARG"}}}async function XS(r,e){let t=r[0];if(!t)return{tool:"error",result:{error:"Usage: prjct context signatures <file_or_directory>",code:"MISSING_ARG"}};let n=await import("node:fs/promises"),s=await import("node:path"),o=s.isAbsolute(t)?t:s.join(e,t);try{if((await n.stat(o)).isDirectory()){let c=await Sc(t,e,{recursive:r.includes("--recursive")||r.includes("-r")}),u=si(c.map(m=>m.metrics));return{tool:"signatures",result:{file:t,language:"multiple",signatures:c.flatMap(m=>m.signatures.map(d=>({...d,file:m.file}))),fallback:!1,metrics:u}}}}catch{}return{tool:"signatures",result:await xn(t,e)}}async function YS(r,e){let t=r[0];if(!t)return{tool:"error",result:{error:"Usage: prjct context imports <file> [--reverse] [--depth N]",code:"MISSING_ARG"}};let n={};for(let o=1;o<r.length;o++)r[o]==="--reverse"||r[o]==="-r"?n.reverse=!0:(r[o]==="--depth"||r[o]==="-d")&&r[o+1]&&(n.depth=parseInt(r[++o],10));return{tool:"imports",result:await Hs(t,e,n)}}async function QS(r,e){let t={};for(let s=0;s<r.length;s++)r[s]==="--branch"||r[s]==="-b"?t.branch=!0:r[s]==="--max"&&r[s+1]?t.maxFiles=parseInt(r[++s],10):/^\d+$/.test(r[s])&&(t.commits=parseInt(r[s],10));return{tool:"recent",result:await $r(e,t)}}async function ZS(r,e){let t=r[0];if(!t)return{tool:"error",result:{error:"Usage: prjct context summary <file_or_directory> [--recursive]",code:"MISSING_ARG"}};let n=await import("node:fs/promises"),s=await import("node:path"),o=s.isAbsolute(t)?t:s.join(e,t);try{if((await n.stat(o)).isDirectory()){let c=await bc(t,e,{recursive:r.includes("--recursive")||r.includes("-r")});return{tool:"summary",result:{file:t,purpose:`Directory with ${c.length} files`,publicAPI:c.flatMap(p=>p.publicAPI.map(m=>({...m,file:p.file}))),dependencies:[...new Set(c.flatMap(p=>p.dependencies))],metrics:si(c.map(p=>p.metrics))}}}}catch{}return{tool:"summary",result:await oi(t,e)}}function eb(r){if(r.tool==="error")return 0;switch(r.tool){case"signatures":case"summary":return r.result.metrics.tokens.saved;case"files":return r.result.metrics.filesScanned*50-r.result.metrics.filesReturned*50;case"imports":return r.result.metrics.totalImports*20;case"recent":return r.result.metrics.totalFilesChanged*30;default:return 0}}function tb(r){if(r.tool==="error")return 0;switch(r.tool){case"signatures":case"summary":return r.result.metrics.compression;case"files":{let e=r.result.metrics.filesScanned,t=r.result.metrics.filesReturned;return e>0?(e-t)/e:0}default:return 0}}async function nb(r,e){try{await pn.recordSync(r,{originalSize:e.tokensSaved+100,filteredSize:100,duration:e.duration,isWatch:!1,agents:[`context-${e.tool}`]})}catch{}}function sb(){return`
347
- Context Tools - Smart context filtering for AI agents
348
-
349
- USAGE:
350
- prjct context <tool> [args] [options]
351
-
352
- TOOLS:
353
-
354
- files <task>
355
- Find files relevant to a task description.
356
- Options:
357
- --max N Maximum files to return (default: 30)
358
- --min-score N Minimum relevance score 0-1 (default: 0.1)
359
- --include-tests Include test files
360
-
361
- Example:
362
- prjct context files "add user authentication"
363
-
364
- signatures <path>
365
- Extract code structure without implementation (~90% compression).
366
- Path can be a file or directory.
367
- Options:
368
- --recursive, -r Process directories recursively
369
-
370
- Example:
371
- prjct context signatures core/auth/service.ts
372
- prjct context signatures core/auth/ --recursive
373
-
374
- imports <file>
375
- Analyze import/dependency relationships.
376
- Options:
377
- --reverse, -r Show files that import this file
378
- --depth N, -d N Build dependency tree to depth N
379
-
380
- Example:
381
- prjct context imports core/auth/service.ts --reverse
382
- prjct context imports core/auth/service.ts --depth 2
383
-
384
- recent [commits]
385
- Find recently modified "hot" files.
386
- Options:
387
- --branch, -b Only files changed in current branch vs main
388
- --max N Maximum files to return (default: 50)
389
-
390
- Example:
391
- prjct context recent
392
- prjct context recent 50
393
- prjct context recent --branch
394
-
395
- summary <path>
396
- Generate intelligent file summary (public API + docs).
397
- Options:
398
- --recursive, -r Process directories recursively
399
-
400
- Example:
401
- prjct context summary core/auth/service.ts
402
- prjct context summary core/services/ --recursive
403
-
404
- OUTPUT:
405
- All tools output JSON for easy parsing by AI agents.
406
- Each output includes metrics showing token savings.
407
- `.trim()}var Xd=y(()=>{"use strict";Ir();M();ne();fc();hc();yc();ri();Vd();Fr();Fr();qd();l(qS,"runContextTool");l(KS,"runFilesTool");l(XS,"runSignaturesTool");l(YS,"runImportsTool");l(QS,"runRecentTool");l(ZS,"runSummaryTool");l(eb,"getTokensSaved");l(tb,"getCompressionRate");l(nb,"recordToolUsage");l(sb,"getHelpText")});var em={};Ne(em,{hooksService:()=>ub});import ke from"node:fs/promises";import he from"node:path";import ht from"chalk";function Qd(){return`#!/bin/sh
408
- # prjct auto-sync hook (post-commit)
409
- # Syncs project context after each commit
410
- # Installed by: prjct hooks install
411
-
412
- # Rate limit: skip if synced within last 30 seconds
413
- LOCK_FILE="\${TMPDIR:-/tmp}/prjct-sync-$(pwd | md5sum 2>/dev/null | cut -d' ' -f1 || md5 -q -s "$(pwd)").lock"
414
- if [ -f "$LOCK_FILE" ]; then
415
- LOCK_AGE=$(( $(date +%s) - $(stat -f%m "$LOCK_FILE" 2>/dev/null || stat -c%Y "$LOCK_FILE" 2>/dev/null || echo 0) ))
416
- if [ "$LOCK_AGE" -lt 30 ]; then
417
- exit 0
418
- fi
419
- fi
420
-
421
- # Run sync in background, suppress all output
422
- if command -v prjct >/dev/null 2>&1; then
423
- touch "$LOCK_FILE"
424
- prjct sync --quiet --yes >/dev/null 2>&1 &
425
- fi
426
-
427
- exit 0
428
- `}function Zd(){return`#!/bin/sh
429
- # prjct auto-sync hook (post-checkout)
430
- # Syncs project context after branch switch
431
- # Installed by: prjct hooks install
432
-
433
- # Only run on branch checkout (not file checkout)
434
- # $3 is the checkout type flag: 1 = branch, 0 = file
435
- if [ "$3" != "1" ]; then
436
- exit 0
437
- fi
438
-
439
- # Skip if old and new refs are the same (no actual branch change)
440
- if [ "$1" = "$2" ]; then
441
- exit 0
442
- fi
443
-
444
- # Rate limit: skip if synced within last 30 seconds
445
- LOCK_FILE="\${TMPDIR:-/tmp}/prjct-sync-$(pwd | md5sum 2>/dev/null | cut -d' ' -f1 || md5 -q -s "$(pwd)").lock"
446
- if [ -f "$LOCK_FILE" ]; then
447
- LOCK_AGE=$(( $(date +%s) - $(stat -f%m "$LOCK_FILE" 2>/dev/null || stat -c%Y "$LOCK_FILE" 2>/dev/null || echo 0) ))
448
- if [ "$LOCK_AGE" -lt 30 ]; then
449
- exit 0
450
- fi
451
- fi
452
-
453
- # Run sync in background, suppress all output
454
- if command -v prjct >/dev/null 2>&1; then
455
- touch "$LOCK_FILE"
456
- prjct sync --quiet --yes >/dev/null 2>&1 &
457
- fi
458
-
459
- exit 0
460
- `}async function Pc(r){let e=[];return(await C(he.join(r,"lefthook.yml"))||await C(he.join(r,"lefthook.yaml")))&&e.push("lefthook"),(await C(he.join(r,".husky"))||await C(he.join(r,".husky","_")))&&e.push("husky"),await C(he.join(r,".git"))&&e.push("direct"),e}function Yd(r){return r.includes("lefthook")?"lefthook":r.includes("husky")?"husky":"direct"}async function rb(r,e){let t=await C(he.join(r,"lefthook.yml"))?"lefthook.yml":"lefthook.yaml",n=he.join(r,t),s=await ke.readFile(n,"utf-8");for(let o of e){let i=o,a=`prjct-sync-${o}`;if(s.includes(a))continue;let c=`
461
- ${i}:
462
- commands:
463
- ${a}:
464
- run: prjct sync --quiet --yes
465
- fail_text: "prjct sync failed (non-blocking)"
466
- `,u=new RegExp(`^${i}:\\s*$`,"m");u.test(s)?s=s.replace(u,`${i}:
467
- commands:
468
- ${a}:
469
- run: prjct sync --quiet --yes
470
- fail_text: "prjct sync failed (non-blocking)"`):s=`${s.trimEnd()}
471
- ${c}`}return await ke.writeFile(n,s,"utf-8"),!0}async function ob(r,e){let t=he.join(r,".husky");for(let n of e){let s=he.join(t,n),o=n==="post-commit"?Qd():Zd();if(await C(s)){if((await ke.readFile(s,"utf-8")).includes("prjct sync"))continue;await ke.appendFile(s,`
472
- # prjct auto-sync
473
- prjct sync --quiet --yes &
474
- `)}else await ke.writeFile(s,o,{mode:493})}return!0}async function ib(r,e){let t=he.join(r,".git","hooks");await C(t)||await ke.mkdir(t,{recursive:!0});for(let n of e){let s=he.join(t,n),o=n==="post-commit"?Qd():Zd();if(await C(s)){if((await ke.readFile(s,"utf-8")).includes("prjct sync"))continue;await ke.appendFile(s,`
475
- # prjct auto-sync
476
- ${o.split(`
477
- `).slice(1).join(`
478
- `)}`)}else await ke.writeFile(s,o,{mode:493})}return!0}async function ab(r){let e=await C(he.join(r,"lefthook.yml"))?"lefthook.yml":"lefthook.yaml",t=he.join(r,e);if(!await C(t))return!1;let n=await ke.readFile(t,"utf-8");return n=n.replace(/\s*prjct-sync-[\w-]+:[\s\S]*?(?=\n\S|\n*$)/g,""),n=n.replace(/^(post-commit|post-checkout):\s*commands:\s*$/gm,""),await ke.writeFile(t,`${n.trimEnd()}
479
- `,"utf-8"),!0}async function cb(r){let e=he.join(r,".husky");for(let t of["post-commit","post-checkout"]){let n=he.join(e,t);if(!await C(n))continue;let s=await ke.readFile(n,"utf-8");if(!s.includes("prjct sync"))continue;let o=s.split(`
480
- `).filter(i=>!i.includes("prjct sync")&&!i.includes("prjct auto-sync")).join(`
481
- `);o.trim()==="#!/bin/sh"||o.trim()==="#!/usr/bin/env sh"?await ke.unlink(n):await ke.writeFile(n,o,{mode:493})}return!0}async function lb(r){let e=he.join(r,".git","hooks");for(let t of["post-commit","post-checkout"]){let n=he.join(e,t);if(!await C(n))continue;let s=await ke.readFile(n,"utf-8");if(s.includes("prjct sync"))if(s.includes("Installed by: prjct hooks install"))await ke.unlink(n);else{let o=s.split(`
482
- `).filter(i=>!i.includes("prjct sync")&&!i.includes("prjct auto-sync")).join(`
483
- `);await ke.writeFile(n,o,{mode:493})}}return!0}var Cc,ub,tm=y(()=>{"use strict";Ye();M();me();Xt();l(Qd,"getPostCommitScript");l(Zd,"getPostCheckoutScript");l(Pc,"detectHookManagers");l(Yd,"selectStrategy");l(rb,"installLefthook");l(ob,"installHusky");l(ib,"installDirect");l(ab,"uninstallLefthook");l(cb,"uninstallHusky");l(lb,"uninstallDirect");Cc=class{static{l(this,"HooksService")}async install(e,t={}){let n=t.hooks||["post-commit","post-checkout"],s=await Pc(e);if(s.length===0)return{success:!1,strategy:"direct",hooksInstalled:[],error:'Not a git repository. Run "git init" first.'};let o=t.strategy||Yd(s);try{let i=!1;switch(o){case"lefthook":i=await rb(e,n);break;case"husky":i=await ob(e,n);break;case"direct":i=await ib(e,n);break}return i&&await this.saveHookConfig(e,{enabled:!0,strategy:o,hooks:n,installedAt:new Date().toISOString()}),{success:i,strategy:o,hooksInstalled:i?n:[]}}catch(i){return{success:!1,strategy:o,hooksInstalled:[],error:w(i)}}}async uninstall(e){try{let n=(await this.getHookConfig(e))?.strategy||"direct",s=!1;switch(n){case"lefthook":s=await ab(e);break;case"husky":s=await cb(e);break;case"direct":s=await lb(e);break}return s&&await this.saveHookConfig(e,{enabled:!1,strategy:n,hooks:[]}),{success:s}}catch(t){return{success:!1,error:w(t)}}}async status(e){let t=await Pc(e),n=await this.getHookConfig(e),s=["post-commit","post-checkout"],o=await Promise.all(s.map(async i=>({name:i,installed:await this.isHookInstalled(e,i,n?.strategy||null),path:await this.getHookPath(e,i,n?.strategy||null)})));return{installed:o.some(i=>i.installed),strategy:n?.strategy||null,hooks:o,detectedManagers:t}}async run(e,t){if(!await I.getProjectId(e))return console.error('No prjct project found. Run "prjct init" first.'),1;switch(t){case"install":return this.runInstall(e);case"uninstall":return this.runUninstall(e);case"status":return this.runStatus(e);default:return this.runStatus(e)}}async runInstall(e){h.start(),h.section("Git Hooks Installation");let t=await Pc(e),n=Yd(t);console.log(` Strategy: ${ht.cyan(n)}`),console.log(` Hooks: ${ht.dim("post-commit, post-checkout")}`),console.log("");let s=await this.install(e,{strategy:n});if(s.success){h.done(`Hooks installed via ${s.strategy}`),console.log("");for(let o of s.hooksInstalled)console.log(` ${ht.green("\u2713")} ${o}`);console.log(""),console.log(ht.dim(" Context will auto-sync on commit and branch switch.")),console.log(ht.dim(" Remove with: prjct hooks uninstall"))}else h.fail(s.error||"Failed to install hooks");return console.log(""),h.end(),s.success?0:1}async runUninstall(e){h.start(),h.section("Git Hooks Removal");let t=await this.uninstall(e);return t.success?h.done("Hooks removed"):h.fail(t.error||"Failed to remove hooks"),console.log(""),h.end(),t.success?0:1}async runStatus(e){h.start(),h.section("Git Hooks Status");let t=await this.status(e);t.installed?(console.log(` Status: ${ht.green("Active")}`),console.log(` Strategy: ${ht.cyan(t.strategy)}`)):console.log(` Status: ${ht.dim("Not installed")}`),console.log("");for(let n of t.hooks){let s=n.installed?ht.green("\u2713"):ht.dim("\u25CB"),o=n.installed?n.name:ht.dim(n.name);console.log(` ${s} ${o}`)}return t.detectedManagers.length>0&&(console.log(""),console.log(` ${ht.dim("Available managers:")} ${t.detectedManagers.join(", ")}`)),t.installed||(console.log(""),console.log(ht.dim(" Install with: prjct hooks install"))),console.log(""),h.end(),0}async isHookInstalled(e,t,n){if(n==="lefthook"){let o=await C(he.join(e,"lefthook.yml"))?"lefthook.yml":"lefthook.yaml",i=he.join(e,o);return await C(i)?(await ke.readFile(i,"utf-8")).includes(`prjct-sync-${t}`):!1}if(n==="husky"){let o=he.join(e,".husky",t);return await C(o)?(await ke.readFile(o,"utf-8")).includes("prjct sync"):!1}let s=he.join(e,".git","hooks",t);return await C(s)?(await ke.readFile(s,"utf-8")).includes("prjct sync"):!1}async getHookPath(e,t,n){return n==="lefthook"?await C(he.join(e,"lefthook.yml"))?"lefthook.yml":"lefthook.yaml":n==="husky"?`.husky/${t}`:`.git/hooks/${t}`}async getHookConfig(e){let t=await I.getProjectId(e);if(!t)return null;try{let n=he.join(process.env.HOME||"",".prjct-cli","projects",t,"project.json");return await C(n)&&JSON.parse(await ke.readFile(n,"utf-8")).hooks||null}catch{return null}}async saveHookConfig(e,t){let n=await I.getProjectId(e);if(n)try{let s=he.join(process.env.HOME||"",".prjct-cli","projects",n,"project.json");if(!await C(s))return;let o=JSON.parse(await ke.readFile(s,"utf-8"));o.hooks=t,await ke.writeFile(s,JSON.stringify(o,null,2))}catch{}}},ub=new Cc});var nm={};Ne(nm,{DoctorService:()=>ii,doctorService:()=>pb});import{execSync as vc}from"node:child_process";import xc from"node:fs/promises";import Tc from"node:path";import Tn from"chalk";var ii,pb,sm=y(()=>{"use strict";Ye();ee();Xt();st();ii=class{static{l(this,"DoctorService")}projectPath="";projectId=null;globalPath="";async check(e=process.cwd()){this.projectPath=e,this.projectId=await I.getProjectId(e),this.projectId&&(this.globalPath=P.getGlobalProjectPath(this.projectId));let t=await this.checkTools(),n=await this.checkProject(),s=this.generateRecommendations(t,n),o=[...t,...n].some(a=>a.status==="error"&&!a.optional),i=[...t,...n].some(a=>a.status==="warn"||a.status==="error"&&a.optional);return{success:!o,tools:t,project:n,recommendations:s,hasErrors:o,hasWarnings:i}}async run(e=process.cwd()){let t=await this.check(e);return this.printHeader(),this.printSection("System Tools",t.tools),this.printSection("Project Status",t.project),t.recommendations.length>0&&this.printRecommendations(t.recommendations),this.printSummary(t),t.hasErrors?1:0}async checkTools(){let e=[];return e.push(this.checkCommand("git","git --version",/git version ([\d.]+)/,!1)),e.push(this.checkCommand("node","node --version",/v([\d.]+)/,!1)),e.push(this.checkCommand("bun","bun --version",/([\d.]+)/,!0)),e.push(this.checkCommand("gh","gh --version",/gh version ([\d.]+)/,!0,"needed for PR commands")),e.push(this.checkCommand("claude","claude --version",/claude ([\d.]+)/,!0,"Anthropic Claude Code CLI")),e.push(this.checkCommand("gemini","gemini --version",/gemini ([\d.]+)/,!0,"Google Gemini CLI")),e}checkCommand(e,t,n,s,o){try{let a=vc(t,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).match(n),c=a?a[1]:"unknown";return{name:e,status:"ok",version:c,optional:s}}catch{return{name:e,status:"error",message:o?`not found (${o})`:"not found",optional:s}}}async checkProject(){let e=[];return e.push(await this.checkPrjctConfig()),e.push(await this.checkClaudeMd()),e.push(await this.checkGitRepo()),e.push(await this.checkStateFile()),e}async checkPrjctConfig(){let e=Tc.join(this.projectPath,".prjct","prjct.config.json");try{return await xc.access(e),{name:"prjct config",status:"ok",message:"initialized"}}catch{return{name:"prjct config",status:"error",message:'not initialized - run "prjct init"'}}}async checkClaudeMd(){if(!this.globalPath)return{name:"CLAUDE.md",status:"warn",message:"project not initialized"};let e=Tc.join(this.globalPath,"context","CLAUDE.md");try{let t=await xc.stat(e),n=Date.now()-t.mtimeMs,s=Math.floor(n/(1e3*60*60)),o=Math.floor(s/24),i;return o>0?i=`${o} day${o>1?"s":""} ago`:s>0?i=`${s} hour${s>1?"s":""} ago`:i="recently",s>24?{name:"CLAUDE.md",status:"warn",message:`stale (last sync: ${i})`}:{name:"CLAUDE.md",status:"ok",message:`synced ${i}`}}catch{return{name:"CLAUDE.md",status:"error",message:'not found - run "prjct sync"'}}}async checkGitRepo(){try{vc("git rev-parse --git-dir",{cwd:this.projectPath,stdio:["pipe","pipe","pipe"]});let e=vc("git status --porcelain",{cwd:this.projectPath,encoding:"utf-8"});if(e.trim().length>0){let n=e.trim().split(`
484
- `).filter(Boolean);return{name:"git repo",status:"ok",message:`${n.length} uncommitted change${n.length>1?"s":""}`}}return{name:"git repo",status:"ok",message:"clean"}}catch{return{name:"git repo",status:"warn",message:"not a git repository"}}}async checkStateFile(){if(!this.globalPath)return{name:"task state",status:"warn",message:"project not initialized"};let e=Tc.join(this.globalPath,"storage","state.json");try{let t=await xc.readFile(e,"utf-8"),n=JSON.parse(t);return n.currentTask?{name:"task state",status:"ok",message:`active: ${n.currentTask.description?.slice(0,30)}...`}:{name:"task state",status:"ok",message:"no active task"}}catch{return{name:"task state",status:"ok",message:"no state file (normal for new projects)",optional:!0}}}generateRecommendations(e,t){let n=[];e.find(c=>c.name==="gh"&&c.status==="error")&&n.push("Install GitHub CLI (gh) for PR commands: https://cli.github.com");let o=t.find(c=>c.name==="CLAUDE.md");o?.status==="warn"&&o.message?.includes("stale")&&n.push('Run "prjct sync" to update context');let i=t.find(c=>c.name==="prjct config");return i?.status==="error"&&n.push('Run "prjct init" to initialize this project'),t.find(c=>c.name==="CLAUDE.md"&&c.status==="error")&&!i?.status?.includes("error")&&n.push('Run "prjct sync" to generate context files'),n}printHeader(){h.section(`prjct doctor v${se}`)}printSection(e,t){h.section(e);let n=t.map(s=>{let o=this.getStatusIcon(s.status,s.optional),i=s.name.padEnd(14),a=s.version||s.message||"",c=s.optional&&s.status==="error"?Tn.dim(" (optional)"):"";return`${o} ${i} ${Tn.dim(a)}${c}`});for(let s of n)console.log(` ${s}`)}printRecommendations(e){h.section("Recommendations"),h.list(e,{bullet:Tn.yellow("\u2022")})}printSummary(e){console.log(""),console.log(Tn.dim("\u2500".repeat(40))),e.hasErrors?h.fail("Some required checks failed"):e.hasWarnings?h.warn("All required checks passed (some warnings)"):h.done("All checks passed"),console.log("")}getStatusIcon(e,t){switch(e){case"ok":return Tn.green("\u2713");case"warn":return Tn.yellow("\u26A0");case"error":return t?Tn.dim("\u25CB"):Tn.red("\u2717")}}},pb=new ii});import jc from"node:fs";import db from"node:fs/promises";import ai from"node:path";function Ac(){if(rm)return Ec;rm=!0;let r=ai.join(ce,"dist","templates.json");try{let e=jc.readFileSync(r,"utf-8");return Ec=JSON.parse(e),Ec}catch{return null}}function gb(r){let e=Xn.indexOf(r);e>-1&&Xn.splice(e,1),Xn.push(r)}function fb(){for(;Gs.size>=mb&&Xn.length>0;){let r=Xn.shift();r&&Gs.delete(r)}}function ci(r){let e=/^---\n([\s\S]+?)\n---\n([\s\S]*)$/,t=r.match(e);if(!t)return{frontmatter:{},content:r.trim()};let[,n,s]=t,o={};return n.split(`
485
- `).forEach(i=>{let[a,...c]=i.split(":");if(a&&c.length>0){let u=c.join(":").trim();u.startsWith("[")&&u.endsWith("]")?o[a.trim()]=u.slice(1,-1).split(",").map(p=>p.trim()):o[a.trim()]=u.replace(/^["']|["']$/g,"")}}),{frontmatter:o,content:s.trim()}}async function om(r){if(Gs.has(r))return gb(r),Gs.get(r);let e,t=Ac();if(t){let s=`commands/${r}.md`;e=t[s]}if(!e){let s=ai.join(ce,"templates","commands",`${r}.md`);try{e=await db.readFile(s,"utf-8")}catch{throw Eo.notFound(r)}}let n=ci(e);return fb(),Gs.set(r,n),Xn.push(r),n}async function hb(r){return(await om(r)).frontmatter["allowed-tools"]||[]}function yb(){Gs.clear(),Xn.length=0}function Se(r){let e=Ac();if(e&&e[r])return e[r];let t=ai.join(ce,"templates",r);try{return jc.readFileSync(t,"utf-8")}catch{return null}}function zs(r){let e=Ac();if(e)return Object.keys(e).filter(n=>n.startsWith(r));let t=ai.join(ce,"templates",r);try{return jc.readdirSync(t).map(s=>`${r}${s}`)}catch{return[]}}var mb,Gs,Xn,Ec,rm,wb,Ic,Yn=y(()=>{"use strict";an();st();mb=50,Gs=new Map,Xn=[],Ec=null,rm=!1;l(Ac,"loadBundle");l(gb,"updateLruOrder");l(fb,"evictLru");l(ci,"parseFrontmatter");l(om,"load");l(hb,"getAllowedTools");l(yb,"clearCache");l(Se,"getTemplateContent");l(zs,"listTemplates");wb={load:om,parseFrontmatter:ci,getAllowedTools:hb,clearCache:yb,getTemplateContent:Se,listTemplates:zs},Ic=wb});import J from"node:fs/promises";import Rc from"node:os";import X from"node:path";async function kb(){try{let r=Se("global/modules/module-config.json");if(r)return JSON.parse(r);let e=X.join(ce,"templates/global/modules/module-config.json"),t=await J.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async function Sb(r){let e=await kb();if(!e){let i=Se("global/CLAUDE.md");if(i)return i;let a=X.join(ce,"templates/global/CLAUDE.md");return J.readFile(a,"utf-8")}let t=r||e.default,n=e.profiles[t];if(!n&&!e.profiles[e.default]){let a=Se("global/CLAUDE.md");if(a)return a;let c=X.join(ce,"templates/global/CLAUDE.md");return J.readFile(c,"utf-8")}let s=(n||e.profiles[e.default]).modules,o=[];o.push("<!-- prjct:start - DO NOT REMOVE THIS MARKER -->");for(let i of s){let a=Se(`global/modules/${i}`);if(a)o.push(""),o.push(a);else try{let c=X.join(ce,"templates/global/modules",i),u=await J.readFile(c,"utf-8");o.push(""),o.push(u)}catch{console.warn(`Module not found: ${i}`)}}return o.push(""),o.push("<!-- prjct:end - DO NOT REMOVE THIS MARKER -->"),o.push(""),o.join(`
486
- `)}async function bb(){try{let r=X.join(Rc.homedir(),".prjct-cli","docs");await J.mkdir(r,{recursive:!0});let e=zs("global/docs/");if(e.length>0){for(let s of e)if(s.endsWith(".md")){let o=Se(s);if(o){let i=X.basename(s);await J.writeFile(X.join(r,i),o,"utf-8")}}return{success:!0}}let t=X.join(ce,"templates/global/docs"),n=await J.readdir(t);for(let s of n)if(s.endsWith(".md")){let o=X.join(t,s),i=X.join(r,s),a=await J.readFile(o,"utf-8");await J.writeFile(i,a,"utf-8")}return{success:!0}}catch(r){return{success:!1,error:w(r)}}}async function Pb(){let r=(He(),bt(mt)),e=await r.getActiveProvider(),t=e.name;if(!(await r.detectProvider(t)).installed&&!e.configDir)return{success:!1,error:`${e.displayName} not detected`,action:"skipped"};try{await J.mkdir(e.configDir,{recursive:!0});let s=X.join(e.configDir,e.contextFile),o=X.join(ce,"templates","global",e.contextFile),i="";try{let u=Se(`global/${e.contextFile}`);u?i=u:i=await J.readFile(o,"utf-8")}catch{if(t==="claude")try{i=await Sb("standard")}catch{let p=Se("global/CLAUDE.md");if(p)i=p;else{let m=X.join(ce,"templates/global/CLAUDE.md");i=await J.readFile(m,"utf-8")}}else{let p=Se("global/CLAUDE.md");if(p)i=p;else{let m=X.join(ce,"templates/global/CLAUDE.md");i=await J.readFile(m,"utf-8")}t==="gemini"&&(i=i.replace(/Claude/g,"Gemini"))}}let a="",c=!1;try{a=await J.readFile(s,"utf-8"),c=!0}catch(u){if(k(u))c=!1;else throw u}if(c){let u="<!-- prjct:start - DO NOT REMOVE THIS MARKER -->",p="<!-- prjct:end - DO NOT REMOVE THIS MARKER -->";if(a.includes(u)&&a.includes(p)){let d=a.substring(0,a.indexOf(u)),g=a.substring(a.indexOf(p)+p.length),f=i.substring(i.indexOf(u),i.indexOf(p)+p.length),S=d+f+g;return await J.writeFile(s,S,"utf-8"),{success:!0,action:"updated",path:s}}else{let d=`${a}
487
-
488
- ${i}`;return await J.writeFile(s,d,"utf-8"),{success:!0,action:"appended",path:s}}}else return await J.writeFile(s,i,"utf-8"),{success:!0,action:"created",path:s}}catch(s){return{success:!1,error:w(s),action:"failed"}}}function im(){let r=Rc.homedir();return{claude:{commands:X.join(r,".claude","commands","p"),config:X.join(r,".claude"),router:X.join(r,".claude","commands","p.md")},gemini:{commands:X.join(r,".gemini","commands"),config:X.join(r,".gemini"),router:X.join(r,".gemini","commands","p.toml")}}}var Dc,Cb,be,En=y(()=>{"use strict";Yn();M();st();l(kb,"loadModuleConfig");l(Sb,"composeGlobalTemplate");l(bb,"installDocs");l(Pb,"installGlobalConfig");Dc=class{static{l(this,"CommandInstaller")}homeDir;claudeCommandsPath="";claudeConfigPath="";templatesDir;_initialized=!1;constructor(){this.homeDir=Rc.homedir(),this.templatesDir=X.join(ce,"templates","commands")}async ensureInit(){if(this._initialized)return;let t=await(He(),bt(mt)).getActiveProvider();t.name==="gemini"?this.claudeCommandsPath=X.join(t.configDir,"commands"):this.claudeCommandsPath=X.join(t.configDir,"commands","p"),this.claudeConfigPath=t.configDir,this._initialized=!0}async detectActiveProvider(){await this.ensureInit();try{return await J.access(this.claudeConfigPath),!0}catch(e){if(k(e))return!1;throw e}}async detectClaude(){return this.detectActiveProvider()}async getCommandFiles(){let e=zs("commands/");if(e.length>0)return e.filter(t=>t.endsWith(".md")).map(t=>t.replace("commands/",""));try{return(await J.readdir(this.templatesDir)).filter(n=>n.endsWith(".md"))}catch{return["init.md","now.md","done.md","ship.md","next.md","idea.md","recap.md","progress.md","stuck.md","context.md","analyze.md","sync.md","roadmap.md","task.md","git.md","fix.md","test.md","cleanup.md","design.md"]}}async installCommands(){let e=await this.detectActiveProvider(),n=await(He(),bt(mt)).getActiveProvider();if(!e)return{success:!1,error:`${n.displayName} not detected. Please install it first.`};try{await this.installRouter(),await J.mkdir(this.claudeCommandsPath,{recursive:!0});let s=await this.getCommandFiles(),o=[],i=[];for(let a of s)try{let c=X.join(this.claudeCommandsPath,a),u=Se(`commands/${a}`);if(u)await J.writeFile(c,u,"utf-8");else{let p=X.join(this.templatesDir,a),m=await J.readFile(p,"utf-8");await J.writeFile(c,m,"utf-8")}o.push(a.replace(".md",""))}catch(c){i.push({file:a,error:w(c)})}return{success:!0,installed:o,errors:i,path:this.claudeCommandsPath}}catch(s){return{success:!1,error:w(s)}}}async uninstallCommands(){try{let e=await this.getCommandFiles(),t=[],n=[];for(let s of e)try{let o=X.join(this.claudeCommandsPath,s);await J.unlink(o),t.push(s.replace(".md",""))}catch(o){o.code!=="ENOENT"&&n.push({file:s,error:w(o)})}try{await J.rmdir(this.claudeCommandsPath)}catch{}return{success:!0,uninstalled:t,errors:n}}catch(e){return{success:!1,error:w(e)}}}async checkInstallation(){if(!await this.detectClaude())return{installed:!1,claudeDetected:!1};try{await J.access(this.claudeCommandsPath);let n=(await J.readdir(this.claudeCommandsPath)).filter(s=>s.endsWith(".md")).map(s=>s.replace(".md",""));return{installed:n.length>0,claudeDetected:!0,commands:n,path:this.claudeCommandsPath}}catch(t){if(k(t))return{installed:!1,claudeDetected:!0,commands:[]};throw t}}async updateCommands(){console.log("Updating commands with latest templates...");let e=await this.installCommands();return e.success&&e.installed&&console.log(`Updated ${e.installed.length} commands`),e}async installToAll(){return await this.installCommands()}async getInstallPath(){return await this.ensureInit(),this.claudeCommandsPath}async verifyTemplate(e){if(Se(`commands/${e}.md`))return!0;try{let n=X.join(this.templatesDir,`${e}.md`);return await J.access(n),!0}catch(n){if(k(n))return!1;throw n}}async installRouter(){let t=await(He(),bt(mt)).getActiveProvider(),n=t.name==="gemini"?"p.toml":"p.md";try{let s=X.join(t.configDir,"commands",n);await J.mkdir(X.dirname(s),{recursive:!0});let o=Se(`commands/${n}`);if(o)return await J.writeFile(s,o,"utf-8"),!0;let i=X.join(this.templatesDir,n),a=await J.readFile(i,"utf-8");return await J.writeFile(s,a,"utf-8"),!0}catch(s){if(k(s))return!1;throw s}}async removeLegacyCommands(){let t=await(He(),bt(mt)).getActiveProvider(),n=X.join(t.configDir,"commands"),s=0;try{let i=(await J.readdir(n)).filter(a=>a.startsWith("p.")&&a.endsWith(".md"));for(let a of i)try{await J.unlink(X.join(n,a)),s++}catch{}}catch{}return s}async syncCommands(){if(!await this.detectActiveProvider())return{success:!1,error:"AI agent not detected",added:0,updated:0,removed:0};try{await this.installRouter(),await J.mkdir(this.claudeCommandsPath,{recursive:!0});let t=await this.getCommandFiles(),n=[];try{n=await J.readdir(this.claudeCommandsPath),n=n.filter(o=>o.endsWith(".md"))}catch(o){if(k(o))n=[];else throw o}let s={success:!0,added:0,updated:0,removed:0,errors:[]};for(let o of t)try{let i=X.join(this.claudeCommandsPath,o),a=n.includes(o),c=Se(`commands/${o}`);if(c)await J.writeFile(i,c,"utf-8");else{let u=X.join(this.templatesDir,o),p=await J.readFile(u,"utf-8");await J.writeFile(i,p,"utf-8")}a?s.updated++:s.added++}catch(i){s.errors.push({file:o,error:w(i)})}return await this.removeLegacyCommands(),s}catch(t){return{success:!1,error:w(t),added:0,updated:0,removed:0}}}async installGlobalConfig(){return Pb()}async installDocs(){return bb()}};l(im,"getProviderPaths");Cb=new Dc,be=Cb});import tn from"chalk";function vb(r){return am[r.toLowerCase()]||am.default}var am,$c,li,cm=y(()=>{"use strict";am={database:"\u{1F4BE}",backend:"\u{1F527}",frontend:"\u{1F4E6}",testing:"\u{1F9EA}",devops:"\u{1F680}",uxui:"\u{1F3A8}",security:"\u{1F512}",docs:"\u{1F4DD}",api:"\u{1F310}",default:"\u26A1"};l(vb,"getIcon");$c=class{static{l(this,"AgentStream")}currentAgent=null;startTime=0;quiet=!1;setQuiet(e){this.quiet=e}orchestrate(e){this.quiet||console.log(tn.cyan(`
489
- \u{1F3AF} Orchestrating: ${e.join(", ")} domains detected
490
- `))}startAgent(e,t,n){if(this.quiet)return;this.currentAgent=e,this.startTime=Date.now();let s=vb(t);console.log(tn.cyan(`\u250C\u2500 ${s} ${e} (${t})`)),n&&console.log(tn.dim(`\u2502 ${n}`))}progress(e){this.quiet||!this.currentAgent||console.log(tn.dim(`\u2502 \u2514\u2500\u2500 ${e}`))}progressList(e){if(!(this.quiet||!this.currentAgent))for(let t of e)console.log(tn.dim(`\u2502 \u2514\u2500\u2500 ${t}`))}endAgent(e=!0){if(this.quiet||!this.currentAgent)return;let t=Date.now()-this.startTime,n=this.formatDuration(t),s=e?tn.green("\u2713"):tn.red("\u2717");console.log(`\u2514\u2500 ${s} ${e?"Complete":"Failed"} ${tn.dim(`(${n})`)}
491
- `),this.currentAgent=null}status(e,t){this.quiet||console.log(`${e} ${t}`)}complete(e,t){if(this.quiet)return;let n=t?` ${tn.dim(`[${this.formatDuration(t)}]`)}`:"";console.log(tn.green(`\u2705 ${e}${n}`))}formatDuration(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}},li=new $c});import Be from"chalk";function xb(r){let e=0;for(let n of r)e=(e<<5)-e+n.charCodeAt(0),e=e&e;let t=Math.abs(e)%lm.length;return lm[t]}function Tb(r,e,t="\u25B6"){let n=Be.dim(String(r+1).padStart(2)),o=xb(e.domain)(e.domain.padEnd(10)),i=e.description.length>32?`${e.description.slice(0,29)}...`:e.description.padEnd(32),a;switch(e.status){case"completed":a=Be.green("\u2713 Complete");break;case"in_progress":a=Be.yellow(`${t} Working...`);break;case"pending":a=Be.gray("\u25CB Pending");break;case"failed":a=Be.red("\u2717 Failed");break;case"blocked":a=Be.gray("\u2298 Blocked");break;default:a=Be.gray(`\u25CB ${e.status}`)}return` ${n} ${o} ${i} ${a}`}function Eb(r){if(r.length===0)return"";let e=[];e.push(""),e.push(` ${Be.bold.white("SUBTASK PROGRESS")}`),e.push(` ${Be.dim("\u2500".repeat(58))}`);for(let t=0;t<r.length;t++)e.push(Tb(t,r[t]));return e.push(""),e.join(`
492
- `)}function um(r){console.log(Eb(r))}var lm,pm=y(()=>{"use strict";lm=[Be.cyan,Be.magenta,Be.yellow,Be.blue,Be.green,Be.redBright,Be.magentaBright,Be.cyanBright];l(xb,"getDomainColor");l(Tb,"formatSubtaskLine");l(Eb,"renderSubtaskProgress");l(um,"printSubtaskProgress")});function jb(r){return dm.includes(r)}async function Ab(r,e,t){let n=[],s=[],o=[];switch(r){case"ship":t.now&&!t.now.includes("No current task")?n.push({step:"Has active task",passed:!0}):(n.push({step:"Has active task",passed:!1,details:"No active task to ship"}),o.push("No active task")),t.shipped?n.push({step:"Shipped log accessible",passed:!0}):n.push({step:"Shipped log accessible",passed:!1,details:"shipped.md not found"}),s.push("Read current task from now.md"),s.push("Calculate duration"),s.push("Append to shipped.md"),s.push("Clear now.md"),s.push("Update metrics");break;case"feature":e.params.description||e.params.feature?n.push({step:"Has feature description",passed:!0}):(n.push({step:"Has feature description",passed:!1,details:"No description provided"}),o.push("Missing feature description")),t.analysis?n.push({step:"Project analyzed",passed:!0}):n.push({step:"Project analyzed",passed:!1,details:"Run /p:sync first"}),s.push("Parse feature description"),s.push("Generate tasks breakdown"),s.push("Add to roadmap.md"),s.push("Add tasks to next.md"),s.push("Suggest starting first task");break;case"spec":e.params.feature||e.params.name?n.push({step:"Has spec name",passed:!0}):(n.push({step:"Has spec name",passed:!1,details:"No spec name provided"}),o.push("Missing spec name")),s.push("Generate spec template"),s.push("Analyze requirements"),s.push("Create spec file"),s.push("Link to roadmap");break;case"cleanup":t.analysis?n.push({step:"Has code analysis",passed:!0}):n.push({step:"Has code analysis",passed:!1,details:"Run /p:analyze first"}),s.push("Scan for unused code"),s.push("Identify dead imports"),s.push("List files to clean"),s.push("Show preview"),s.push("Wait for approval"),s.push("Execute cleanup");break;case"migrate":n.push({step:"Migration safety check",passed:!0,details:"Will require manual approval"}),s.push("Analyze current state"),s.push("Generate migration plan"),s.push("Show affected files"),s.push("Request approval"),s.push("Execute migration"),s.push("Verify results");break;default:s.push("Execute command");break}let i=n.filter(u=>u.passed).length,a=n.length,c=a>0?i/a:1;return{commandName:r,reasoning:n.length>0?{steps:n,allPassed:o.length===0,criticalIssues:o}:null,plan:s,confidence:c}}function Ib(r){let e=[];return e.push(`\u{1F4CB} Chain of Thought: ${r.commandName}`),e.push(""),r.reasoning&&(e.push("Steps:"),r.reasoning.steps.forEach(t=>{let n=t.passed?"\u2705":"\u274C";e.push(` ${n} ${t.step}`),t.details&&e.push(` ${t.details}`)}),e.push(""),r.reasoning.criticalIssues.length>0&&(e.push("Critical Issues:"),r.reasoning.criticalIssues.forEach(t=>{e.push(` \u26A0\uFE0F ${t}`)}),e.push(""))),r.plan.length>0&&(e.push("Plan:"),r.plan.forEach((t,n)=>{e.push(` ${n+1}. ${t}`)}),e.push("")),e.push(`Confidence: ${Math.round(r.confidence*100)}%`),e.join(`
493
- `)}var dm,Db,ui,mm=y(()=>{"use strict";dm=["ship","feature","spec","cleanup","migrate"];l(jb,"requiresReasoning");l(Ab,"reason");l(Ib,"formatPlan");Db={requiresReasoning:jb,reason:Ab,formatPlan:Ib,REASONING_REQUIRED_COMMANDS:dm},ui=Db});import Or from"node:fs/promises";var Mc,Rb,rt,Fc=y(()=>{"use strict";Ye();ee();M();Zo();Mc=class{static{l(this,"ContextBuilder")}_cache;_currentProjectId;constructor(){this._cache=new Ot({ttl:5e3,maxSize:200}),this._currentProjectId=null}async build(e,t={}){let n=await I.getProjectId(e),s=P.getGlobalProjectPath(n);return this._currentProjectId!==null&&this._currentProjectId!==n&&this._cache.clear(),this._currentProjectId=n,{projectId:n,projectPath:e,globalPath:s,paths:{now:P.getFilePath(n,"core","now.md"),next:P.getFilePath(n,"core","next.md"),context:P.getFilePath(n,"core","context.md"),shipped:P.getFilePath(n,"progress","shipped.md"),metrics:P.getFilePath(n,"progress","metrics.md"),ideas:P.getFilePath(n,"planning","ideas.md"),roadmap:P.getFilePath(n,"planning","roadmap.md"),specs:P.getFilePath(n,"planning","specs"),memory:P.getFilePath(n,"memory","context.jsonl"),patterns:P.getFilePath(n,"memory","patterns.json"),analysis:P.getFilePath(n,"analysis","repo-summary.md"),codePatterns:P.getFilePath(n,"analysis","patterns.md")},params:t,timestamp:new Date().toISOString(),date:new Date().toISOString().split("T")[0]}}async loadState(e,t=null){let n={},s=Object.entries(e.paths),o=t?s.filter(([a])=>t.includes(a)):s;for(let[,a]of o){let c=this._cache.get(a);if(c!==null)try{let u=await Or.stat(a);(!c.mtime||u.mtimeMs>c.mtime)&&this._cache.delete(a)}catch(u){if(k(u))this._cache.delete(a);else throw u}}let i=[];for(let[a,c]of o){let u=this._cache.get(c);u!==null?n[a]=u.content:i.push([a,c])}if(i.length>0){let a=i.map(async([u,p])=>{try{let[m,d]=await Promise.all([Or.readFile(p,"utf-8"),Or.stat(p)]);return{key:u,filePath:p,content:m,mtime:d.mtimeMs}}catch(m){if(k(m))return{key:u,filePath:p,content:null,mtime:null};throw m}}),c=await Promise.all(a);for(let{key:u,filePath:p,content:m,mtime:d}of c)n[u]=m,this._cache.set(p,{content:m,mtime:d})}return n}async loadStateForCommand(e,t){let n={now:["now","next","analysis","codePatterns"],done:["now","next","metrics","analysis"],next:["next","analysis"],ship:["now","shipped","metrics","analysis"],recap:["shipped","metrics","now","analysis"],progress:["shipped","metrics","analysis"],idea:["ideas","next","analysis"],feature:["roadmap","next","ideas","analysis","codePatterns"],roadmap:["roadmap","analysis"],spec:["roadmap","next","specs","analysis","codePatterns"],analyze:["analysis","context","codePatterns"],sync:["analysis","context","now","codePatterns"],work:["now","next","analysis","context","codePatterns"],build:["now","next","analysis","context","codePatterns"],design:["analysis","context","codePatterns"],cleanup:["analysis","context","codePatterns"],fix:["analysis","context","codePatterns"],test:["analysis","context","codePatterns"],default:["analysis","codePatterns"]},s=n[t]||n.default;return this.loadState(e,s)}async batchRead(e){let t=new Map,n=[];for(let s of e){let o=this._cache.get(s);o!==null?t.set(s,o.content):n.push(s)}if(n.length>0){let s=n.map(async i=>{try{let a=await Or.readFile(i,"utf-8");return{filePath:i,content:a}}catch(a){if(k(a))return{filePath:i,content:null};throw a}}),o=await Promise.all(s);for(let{filePath:i,content:a}of o)t.set(i,a),this._cache.set(i,{content:a,mtime:null})}return t}invalidateCache(e){this._cache.delete(e)}clearCache(){this._cache.clear(),this._currentProjectId=null}async fileExists(e){try{return await Or.access(e),!0}catch(t){if(k(t))return!1;throw t}}getCacheStats(){return this._cache.stats()}},Rb=new Mc,rt=Rb});import{exec as $b}from"node:child_process";import Pe from"node:fs/promises";import gm from"node:os";import jn from"node:path";import{promisify as Mb}from"node:util";function fm(r){let e=Math.floor(r/36e5),t=Math.floor(r%(1e3*60*60)/(1e3*60));return e>0?`${e}h ${t}m`:`${t}m`}function Oc(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ob(r){if(r.verified||r.warnings.length===0)return null;let e=` Ground Truth Warnings:
494
- `;return r.warnings.forEach(t=>{e+=` - ${t}
495
- `}),r.recommendations.length>0&&(e+=`
496
- Recommendations:
497
- `,r.recommendations.forEach(t=>{e+=` -> ${t}
498
- `})),e}async function hm(r){let e=[],t=[],n={},s=r.paths.now;try{let a=await Pe.readFile(s,"utf-8");n.nowExists=!0,n.nowContent=a.trim(),n.nowLength=a.length,(a.includes("No current task")||a.match(/^#\s*NOW\s*$/m))&&(e.push("now.md appears to be empty or placeholder"),t.push('Start a task first with /p:now "task"'));let c=a.match(/Started:\s*(.+)/i);if(c){n.startedAt=c[1];let u=new Date(c[1]);Number.isNaN(u.getTime())||(n.durationMs=Date.now()-u.getTime(),n.durationFormatted=fm(n.durationMs))}}catch(a){if(k(a))n.nowExists=!1,e.push("now.md does not exist"),t.push('Create a task with /p:now "task"');else throw a}let o=r.paths.next;try{let a=await Pe.readFile(o,"utf-8");n.nextExists=!0;let c=a.match(/- \[ \]/g)||[];n.pendingTasks=c.length}catch(a){if(k(a))n.nextExists=!1,n.pendingTasks=0;else throw a}let i=r.paths.metrics;try{await Pe.access(jn.dirname(i),Pe.constants.W_OK),n.metricsWritable=!0}catch(a){if(k(a))n.metricsWritable=!1,e.push("Cannot write to metrics directory");else throw a}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function ym(r){let e=[],t=[],n={};try{let{stdout:i}=await Fb("git status --porcelain",{cwd:r.projectPath});n.hasUncommittedChanges=i.trim().length>0,n.uncommittedFiles=i.trim().split(`
499
- `).filter(Boolean).length,n.hasUncommittedChanges&&(e.push(`${n.uncommittedFiles} uncommitted file(s)`),t.push("Commit changes before shipping"))}catch{n.gitAvailable=!1}let s=jn.join(r.projectPath,"package.json");try{let i=await Pe.readFile(s,"utf-8"),a=JSON.parse(i);n.currentVersion=a.version,n.hasPackageJson=!0}catch(i){if(k(i))n.hasPackageJson=!1;else if(i instanceof SyntaxError)n.hasPackageJson=!1,e.push("package.json has invalid JSON");else throw i}let o=r.paths.shipped;try{let i=await Pe.readFile(o,"utf-8");n.shippedExists=!0;let a=r.params.feature||r.params.description;if(a){let c=new Date().toISOString().split("T")[0];new RegExp(`${c}.*${Oc(a)}`,"i").test(i)&&(e.push(`Feature "${a}" already shipped today`),t.push("Use a different feature name or skip /p:ship"))}}catch(i){if(k(i))n.shippedExists=!1;else throw i}if(n.hasPackageJson)try{let i=await Pe.readFile(s,"utf-8"),a=JSON.parse(i);n.hasTestScript=!!a.scripts?.test}catch(i){if(k(i)||i instanceof SyntaxError)n.hasTestScript=!1;else throw i}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function wm(r){let e=[],t=[],n={},s=r.paths.next;try{let a=await Pe.readFile(s,"utf-8");n.nextExists=!0;let c=a.match(/- \[[ x]\]/g)||[];n.taskCount=c.length,n.pendingTasks=(a.match(/- \[ \]/g)||[]).length,n.taskCount>=90&&(e.push(`Queue nearly full (${n.taskCount}/100 tasks)`),t.push("Complete some tasks before adding more"))}catch(a){if(k(a))n.nextExists=!1,n.taskCount=0;else throw a}let o=r.paths.roadmap;try{let a=await Pe.readFile(o,"utf-8");n.roadmapExists=!0;let c=r.params.description||r.params.feature;c&&new RegExp(Oc(c),"i").test(a)&&(e.push(`Feature "${c}" may already exist in roadmap`),t.push("Check roadmap for duplicates with /p:roadmap"))}catch(a){if(k(a))n.roadmapExists=!1;else throw a}let i=r.paths.now;try{let a=await Pe.readFile(i,"utf-8");n.hasActiveTask=a.trim().length>0&&!a.includes("No current task"),n.hasActiveTask&&t.push("Consider completing current task first with /p:done")}catch(a){if(k(a))n.hasActiveTask=!1;else throw a}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function km(r){let e=[],t=[],n={},s=r.paths.now;try{let i=await Pe.readFile(s,"utf-8");n.nowExists=!0,n.nowContent=i.trim();let a=i.trim().length>0&&!i.includes("No current task")&&!i.match(/^#\s*NOW\s*$/m);if(n.hasActiveTask=a,a&&r.params.task){let c=i.substring(0,50).replace(/\n/g," ");e.push(`Replacing existing task: "${c}..."`),t.push("Use /p:done first to track completion")}}catch(i){if(k(i))n.nowExists=!1,n.hasActiveTask=!1;else throw i}let o=r.paths.next;try{let a=((await Pe.readFile(o,"utf-8")).match(/- \[ \]/g)||[]).length;n.pendingTasks=a,!r.params.task&&a>0&&t.push(`${a} tasks available in queue`)}catch(i){if(k(i))n.pendingTasks=0;else throw i}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function Sm(r){let e=[],t=[],n={},s=jn.join(r.projectPath,".prjct/prjct.config.json");try{let i=await Pe.readFile(s,"utf-8");n.alreadyInitialized=!0,n.existingConfig=JSON.parse(i),e.push("Project already initialized"),t.push("Use /p:analyze to refresh analysis or delete .prjct/ to reinitialize")}catch(i){if(k(i))n.alreadyInitialized=!1;else if(i instanceof SyntaxError)n.alreadyInitialized=!1,e.push("Existing config has invalid JSON");else throw i}let o=jn.join(gm.homedir(),".prjct-cli");try{await Pe.access(o,Pe.constants.W_OK),n.globalPathWritable=!0}catch(i){if(k(i))try{await Pe.mkdir(o,{recursive:!0}),n.globalPathWritable=!0,n.globalPathCreated=!0}catch{n.globalPathWritable=!1,e.push("Cannot write to ~/.prjct-cli"),t.push("Check directory permissions")}else n.globalPathWritable=!1,e.push("Cannot write to ~/.prjct-cli"),t.push("Check directory permissions")}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function bm(r){let e=[],t=[],n={},s=jn.join(r.projectPath,".prjct/prjct.config.json");try{let a=await Pe.readFile(s,"utf-8");n.hasConfig=!0,n.config=JSON.parse(a)}catch(a){if(k(a))return n.hasConfig=!1,e.push("Project not initialized"),t.push("Run /p:init first"),{verified:!1,actual:n,warnings:e,recommendations:t};if(a instanceof SyntaxError)return n.hasConfig=!1,e.push("Config file has invalid JSON"),t.push("Delete .prjct/ and run /p:init"),{verified:!1,actual:n,warnings:e,recommendations:t};throw a}let o=n.config?.projectId,i=jn.join(gm.homedir(),".prjct-cli/projects",o||"");try{await Pe.access(i),n.globalStorageExists=!0}catch(a){if(k(a))n.globalStorageExists=!1,e.push("Global storage missing"),t.push("Run /p:init to recreate");else throw a}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function Pm(r){let e=[],t=[],n={},s=["package.json","Cargo.toml","go.mod","requirements.txt","Gemfile","pom.xml"];n.detectedFiles=[];for(let i of s)try{await Pe.access(jn.join(r.projectPath,i)),n.detectedFiles.push(i)}catch(a){if(!k(a))throw a}n.detectedFiles.length===0&&(e.push("No recognizable project files detected"),t.push("Analysis may be limited without package.json or similar"));let o=["src","lib","app","core","components"];n.detectedSrcDirs=[];for(let i of o)try{(await Pe.stat(jn.join(r.projectPath,i))).isDirectory()&&n.detectedSrcDirs.push(i)}catch(a){if(!k(a))throw a}return{verified:!0,actual:n,warnings:e,recommendations:t}}async function Cm(r){let e=[],t=[],n={},s=r.paths.specs;try{await Pe.access(s),n.specsExists=!0;let i=await Pe.readdir(s);n.existingSpecs=i.filter(a=>a.endsWith(".md")),n.specCount=n.existingSpecs.length}catch(i){if(k(i))n.specsExists=!1,n.specCount=0;else throw i}let o=r.params.feature||r.params.name||r.params.description;if(o&&n.existingSpecs){let i=o.toLowerCase().replace(/\s+/g,"-");n.existingSpecs.includes(`${i}.md`)&&(e.push(`Spec "${o}" already exists`),t.push("Use a different name or edit existing spec"))}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function xm(r,e,t){let n=vm[r];if(!n)return{verified:!0,actual:{},warnings:[],recommendations:[]};try{return await n(e,t)}catch(s){return{verified:!1,actual:{},warnings:[`Verification error: ${w(s)}`],recommendations:["Check file permissions and project configuration"]}}}async function _b(r,e,t){let n=await xm(r,e,t);return{...e,groundTruth:{...n,verifiedAt:new Date().toISOString(),command:r}}}function Nb(r){return["done","ship","feature","spec","now","init","sync","analyze"].includes(r)}var Fb,vm,Lb,pi,Tm=y(()=>{"use strict";M();Fb=Mb($b);l(fm,"formatDuration");l(Oc,"escapeRegex");l(Ob,"formatWarnings");l(hm,"verifyDone");l(ym,"verifyShip");l(wm,"verifyFeature");l(km,"verifyNow");l(Sm,"verifyInit");l(bm,"verifySync");l(Pm,"verifyAnalyze");l(Cm,"verifySpec");vm={done:hm,ship:ym,feature:wm,now:km,init:Sm,sync:bm,analyze:Pm,spec:Cm};l(xm,"verify");l(_b,"prepareCommand");l(Nb,"requiresVerification");Lb={verify:xm,prepareCommand:_b,requiresVerification:Nb,verifiers:vm,formatWarnings:Ob,formatDuration:fm,escapeRegex:Oc,verifyDone:hm,verifyShip:ym,verifyFeature:wm,verifyNow:km,verifyInit:Sm,verifySync:bm,verifyAnalyze:Pm,verifySpec:Cm},pi=Lb});function Hb(r){return{contradiction:"Verify file/resource state before reporting. Use Read tool to check actual state.",state:"Check current task state from now.md before assuming completion.",invented:"Verify prerequisites exist (package.json, git remote) before claiming actions."}[r]||"Verify actual state before proceeding."}function Gb(r){if(!r||typeof r!="string")return{detected:!1};for(let{pattern:e,type:t,description:n}of Ub)if(e.test(r))return{detected:!0,type:t,pattern:e.source,description:n,message:`Potential hallucination detected: ${n}`,suggestion:Hb(t)};return{detected:!1}}function zb(r,e){if(!r||!e)return!1;let t=l(n=>n.toLowerCase().replace(/[0-9]+/g,"N").replace(/['"`]/g,"").replace(/\s+/g," ").trim(),"normalize");return t(r)===t(e)}function Jb(r){if(!r||r.length===0)return{type:"unknown",description:"No error information"};let e=r[r.length-1]?.message?.toLowerCase()||"";return e.includes("permission")||e.includes("access denied")?{type:"permission",description:"File or directory permission issue"}:e.includes("not found")||e.includes("no such file")?{type:"not_found",description:"File or resource not found"}:e.includes("syntax")||e.includes("parse")?{type:"syntax",description:"Syntax or parsing error"}:e.includes("timeout")||e.includes("timed out")?{type:"timeout",description:"Operation timed out"}:e.includes("network")||e.includes("connection")?{type:"network",description:"Network or connection issue"}:e.includes("config")||e.includes("configuration")?{type:"config",description:"Configuration issue"}:e.includes("validation")||e.includes("invalid")?{type:"validation",description:"Validation failed"}:{type:"unknown",description:"Unrecognized error pattern"}}function Wb(r,e,t){let n={permission:`I've tried ${r} ${t} times but keep hitting permission issues.`,not_found:`After ${t} attempts, I still can't find the required file or resource.`,syntax:`I'm encountering repeated syntax errors with ${r}.`,timeout:`The operation keeps timing out after ${t} attempts.`,network:`Network issues are preventing ${r} from completing.`,validation:`Validation keeps failing for ${r}.`,config:`There seems to be a configuration issue affecting ${r}.`,unknown:`I've tried ${r} ${t} times without success.`};return n[e.type]||n.unknown}function Bb(r){let e={permission:"Check file permissions. Try: chmod -R u+w ~/.prjct-cli/",not_found:"Verify the file path exists. Run /p:init if project not initialized.",syntax:"Check the file format. There may be invalid JSON or markdown.",timeout:"Check your network connection or try again in a moment.",network:"Verify internet connection and try again.",validation:"Review the input parameters and try with different values.",config:"Check .prjct/prjct.config.json for issues. Try /p:init to reinitialize.",unknown:"Can you check the issue manually and provide more context?"};return e[r.type]||e.unknown}var Ub,_c,Vb,Js,Em=y(()=>{"use strict";Ub=[{pattern:/file.*not found.*created/i,type:"contradiction",description:"Claims file created but also not found"},{pattern:/created.*but.*error/i,type:"contradiction",description:"Claims success but also error"},{pattern:/successfully.*failed/i,type:"contradiction",description:"Contradictory success/failure"},{pattern:/already.*completed.*completing/i,type:"state",description:"Completing already-completed task"},{pattern:/no task.*marking complete/i,type:"state",description:"Completing non-existent task"},{pattern:/no.*active.*done with/i,type:"state",description:"Finishing task that doesnt exist"},{pattern:/version.*updated.*no package/i,type:"invented",description:"Version update without package.json"},{pattern:/committed.*nothing to commit/i,type:"invented",description:"Commit without changes"},{pattern:/pushed.*no remote/i,type:"invented",description:"Push without remote"}];l(Hb,"getHallucinationSuggestion");l(Gb,"detectHallucination");l(zb,"isSimilarError");l(Jb,"analyzeErrorPattern");l(Wb,"generateEscalationMessage");l(Bb,"generateSuggestion");_c=class{static{l(this,"LoopDetector")}_attempts;_errorPatterns;maxAttempts;sessionTimeout;constructor(){this._attempts=new Map,this._errorPatterns=new Map,this.maxAttempts=3,this.sessionTimeout=300*1e3}_getKey(e,t=""){return`${e}:${t}`.toLowerCase()}recordAttempt(e,t="",n={}){let s=this._getKey(e,t),o=Date.now(),i=this._attempts.get(s);return(!i||o-i.lastAttempt>this.sessionTimeout)&&(i={command:e,context:t,attempts:0,errors:[],firstAttempt:o,lastAttempt:o,success:!1}),i.attempts++,i.lastAttempt=o,i.success=n.success||!1,n.error&&i.errors.push({message:n.error,timestamp:o}),this._attempts.set(s,i),{attemptNumber:i.attempts,isLooping:this.isLooping(e,t),shouldEscalate:this.shouldEscalate(e,t)}}isLooping(e,t=""){let n=this._getKey(e,t),s=this._attempts.get(n);if(!s)return!1;if(s.attempts>=2&&!s.success){let o=s.errors.slice(-3);if(o.length>=2){let i=o[0]?.message||"";return o.every(c=>zb(c.message,i))}}return!1}shouldEscalate(e,t=""){let n=this._getKey(e,t),s=this._attempts.get(n);return s?s.attempts>=this.maxAttempts&&!s.success:!1}getEscalationInfo(e,t=""){let n=this._getKey(e,t),s=this._attempts.get(n);if(!s)return null;let o=Jb(s.errors);return{status:"BLOCKED",command:e,context:t,attempts:s.attempts,duration:s.lastAttempt-s.firstAttempt,errorPattern:o,message:Wb(e,o,this.maxAttempts),suggestion:Bb(o),lastError:s.errors[s.errors.length-1]?.message||null}}recordSuccess(e,t=""){let n=this._getKey(e,t),s=this._attempts.get(n);s&&(s.success=!0,s.attempts=0,s.errors=[],this._attempts.set(n,s))}clearTracking(e,t=""){let n=this._getKey(e,t);this._attempts.delete(n)}clearAll(){this._attempts.clear(),this._errorPatterns.clear()}getStats(){let e={activeTracking:this._attempts.size,commands:{}};for(let[t,n]of this._attempts)e.commands[t]={attempts:n.attempts,success:n.success,errorCount:n.errors.length};return e}detectHallucination(e){return Gb(e)}analyzeOutput(e,t){let n=this.detectHallucination(t);return n.detected?(this.recordAttempt(e,"hallucination",{success:!1,error:`HALLUCINATION: ${n.description}`}),{...n,shouldBlock:!0,action:"VERIFY_STATE"}):{detected:!1,shouldBlock:!1}}},Vb=new _c,Js=Vb});import Nc from"node:fs/promises";import Ws from"node:path";function Uc(r){if(Ad.includes(r))return[r];let e=r.toLowerCase().replace(/[-_\s]/g,""),t=[];for(let[n,s]of Object.entries(di))if(n!=="general"){for(let o of s)if(e.includes(o)||o.includes(e)){t.push(n);break}}return t.length>0?t:["general"]}var Lc,di,Qn,_r,Nr,Lr=y(()=>{"use strict";ee();M();Ls();ne();me();Ar();Lc={frontend:[R.CODE_STYLE,R.FILE_STRUCTURE,R.ARCHITECTURE,R.TECH_STACK],backend:[R.CODE_STYLE,R.ARCHITECTURE,R.DEPENDENCIES,R.TECH_STACK],devops:[R.SHIP_WORKFLOW,R.TEST_BEHAVIOR,R.DEPENDENCIES,R.ARCHITECTURE],docs:[R.CODE_STYLE,R.NAMING_CONVENTION,R.FILE_STRUCTURE],testing:[R.TEST_BEHAVIOR,R.CODE_STYLE,R.DEPENDENCIES],database:[R.ARCHITECTURE,R.NAMING_CONVENTION,R.TECH_STACK,R.DEPENDENCIES],general:Object.values(R)},di={frontend:["ui","ux","uxui","css","styling","component","layout","design","responsive","react","vue","svelte","angular","html","tailwind","sass","web","accessibility","a11y"],backend:["api","server","route","endpoint","rest","graphql","middleware","worker","queue","auth","hono","express","service","microservice"],devops:["ci","cd","docker","kubernetes","deploy","infra","infrastructure","monitoring","cloud","aws","gcp","azure","pipeline","helm","terraform"],docs:["documentation","readme","guide","tutorial","wiki","changelog","jsdoc","typedoc"],testing:["test","spec","e2e","unit","integration","coverage","mock","vitest","jest","playwright","cypress"],database:["db","sql","schema","migration","query","orm","prisma","mongo","postgres","redis","drizzle","sqlite"],general:[]};l(Uc,"resolveCanonicalDomains");Qn=class{static{l(this,"CachedStore")}_data=null;_loaded=!1;_projectId=null;getSubdirectory(){return null}getPath(e){let t=Ws.join(P.getGlobalProjectPath(e),"memory"),n=this.getSubdirectory();return n?Ws.join(t,n,this.getFilename()):Ws.join(t,this.getFilename())}async load(e){if(this._loaded&&this._data&&this._projectId===e)return this._data;let t=this.getPath(e);try{let n=await Nc.readFile(t,"utf-8");this._data=JSON.parse(n),this.afterLoad(this._data)}catch(n){if(k(n))this._data=this.getDefault();else throw n}return this._loaded=!0,this._projectId=e,this._data}afterLoad(e){}async save(e){if(!this._data)return;let t=this.getPath(e);await Nc.mkdir(Ws.dirname(t),{recursive:!0}),await Nc.writeFile(t,JSON.stringify(this._data,null,2),"utf-8")}getData(){return this._data}setData(e){this._data=e}async update(e,t){let n=await this.load(e),s=t(n);return this._data=s,await this.save(e),s}isLoaded(e){return e?this._loaded&&this._projectId===e:this._loaded}reset(){this._data=null,this._loaded=!1,this._projectId=null}},_r=class{static{l(this,"SessionStore")}_sessionMemory=new Map;setSession(e,t){this._sessionMemory.set(e,{value:t,timestamp:Date.now()})}getSession(e){return this._sessionMemory.get(e)?.value}clearSession(){this._sessionMemory.clear()}},Nr=class{static{l(this,"HistoryStore")}_getSessionPath(e){let t=new Date,n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`,s=Ao();return Ws.join(P.getGlobalProjectPath(e),"memory","sessions",n,`${s}.jsonl`)}async appendHistory(e,t){let n=this._getSessionPath(e);await dt(Ws.dirname(n));let s={ts:b(),...t,type:t.type};await Ds(n,s)}async getRecentHistory(e,t=20){let n=this._getSessionPath(e);return ic(n,t)}}});import Hc from"node:fs/promises";import Gc from"node:path";var Ur,zc=y(()=>{"use strict";ee();M();Ls();ne();Lr();Ur=class r extends Qn{static{l(this,"PatternStore")}static MAX_CONTEXTS=20;static ARCHIVE_AGE_DAYS=90;getFilename(){return"patterns.json"}getDefault(){return{version:1,decisions:{},preferences:{},workflows:{},counters:{}}}afterLoad(e){for(let t of Object.values(e.decisions))t.contexts.length>r.MAX_CONTEXTS&&(t.contexts=t.contexts.slice(-r.MAX_CONTEXTS))}async loadPatterns(e){return this.load(e)}async savePatterns(e){return this.save(e)}async recordDecision(e,t,n,s="",o={}){let i=await this.load(e),a=b();if(!i.decisions[t])i.decisions[t]={value:n,count:1,firstSeen:a,lastSeen:a,confidence:o.userConfirmed?"high":"low",contexts:[s].filter(Boolean),userConfirmed:o.userConfirmed||!1};else{let c=i.decisions[t];c.value===n?(c.count++,c.lastSeen=a,s&&!c.contexts.includes(s)&&(c.contexts.push(s),c.contexts.length>r.MAX_CONTEXTS&&(c.contexts=c.contexts.slice(-r.MAX_CONTEXTS))),o.userConfirmed&&(c.userConfirmed=!0),c.confidence=Ko(c.count,c.userConfirmed)):(c.value=n,c.count=1,c.lastSeen=a,c.userConfirmed=o.userConfirmed||!1,c.confidence=o.userConfirmed?"high":"low")}await this.save(e)}async confirmDecision(e,t){let s=(await this.load(e)).decisions[t];return s?(s.userConfirmed=!0,s.confidence="high",s.lastSeen=b(),await this.save(e),!0):!1}async getDecision(e,t){let s=(await this.load(e)).decisions[t];return!s||s.confidence==="low"?null:{value:s.value,confidence:s.confidence}}async hasPattern(e,t){return await this.getDecision(e,t)!==null}async recordWorkflow(e,t,n){let s=await this.load(e),o=b();if(!s.workflows[t])s.workflows[t]={...n,count:1,firstSeen:o,lastSeen:o,confidence:"low",userConfirmed:!1};else{let i=s.workflows[t];i.count++,i.lastSeen=o,i.confidence=Ko(i.count,i.userConfirmed)}await this.save(e)}async confirmWorkflow(e,t){let s=(await this.load(e)).workflows[t];return s?(s.userConfirmed=!0,s.confidence="high",s.lastSeen=b(),await this.save(e),!0):!1}async getWorkflow(e,t){let s=(await this.load(e)).workflows[t];return!s||s.count<3?null:s}async setPreference(e,t,n,s={}){let o=await this.load(e),i=o.preferences[t],a=i?i.observationCount+1:1,c=s.userConfirmed||i?.userConfirmed||!1;o.preferences[t]={value:n,updatedAt:b(),confidence:Ko(a,c),observationCount:a,userConfirmed:c},await this.save(e)}async confirmPreference(e,t){let s=(await this.load(e)).preferences[t];return s?(s.userConfirmed=!0,s.confidence="high",s.updatedAt=b(),await this.save(e),!0):!1}async getPreference(e,t,n=null){return(await this.load(e)).preferences[t]?.value??n}async getPatternsSummary(e){let t=await this.load(e);return{decisions:Object.keys(t.decisions).length,learnedDecisions:Object.values(t.decisions).filter(n=>n.confidence!=="low").length,workflows:Object.keys(t.workflows).length,preferences:Object.keys(t.preferences).length}}_getArchivePath(e){let t=Gc.join(P.getGlobalProjectPath(e),"memory");return Gc.join(t,"patterns-archive.json")}async archiveStaleDecisions(e){let t=await this.load(e),n=Date.now(),s=r.ARCHIVE_AGE_DAYS*24*60*60*1e3,o=[];for(let[c,u]of Object.entries(t.decisions)){let p=new Date(u.lastSeen).getTime();n-p>s&&o.push(c)}if(o.length===0)return 0;let i=this._getArchivePath(e),a={};try{let c=await Hc.readFile(i,"utf-8");a=JSON.parse(c)}catch(c){if(!k(c))throw c}for(let c of o)a[c]=t.decisions[c],delete t.decisions[c];return await Hc.mkdir(Gc.dirname(i),{recursive:!0}),await Hc.writeFile(i,JSON.stringify(a,null,2),"utf-8"),await this.save(e),o.length}}});var jm=y(()=>{"use strict"});import Hr from"node:fs/promises";import An from"node:path";import{z as ie}from"zod";async function Qb(r,e){let t=Date.now();if(r.frameworks.length===0)return{name:"Framework verification",passed:!0,output:"No frameworks declared (skipped)",durationMs:Date.now()-t};try{let n=An.join(e,"package.json"),s=await Hr.readFile(n,"utf-8"),o=JSON.parse(s),i={...o.dependencies,...o.devDependencies},a=[],c=[];for(let u of r.frameworks){let p=u.toLowerCase();Object.keys(i).some(d=>d.toLowerCase().includes(p))?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(n){return k(n)?{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: ${n instanceof Error?n.message:"unknown error"}`,durationMs:Date.now()-t}}}async function Zb(r,e){let t=Date.now();if(r.languages.length===0)return{name:"Language verification",passed:!0,output:"No languages declared (skipped)",durationMs:Date.now()-t};try{let n=await sP(e),s=new Set(n),o=[],i=[];for(let a of r.languages){let c=Yb[a];if(!c)continue;c.some(p=>s.has(p))?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(n){return{name:"Language verification",passed:!1,error:`Failed to scan project files: ${n instanceof Error?n.message:"unknown error"}`,durationMs:Date.now()-t}}}async function eP(r,e){let t=Date.now(),n=r.patterns.filter(i=>i.location);if(n.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 n){let a=i.location,c=An.join(e,a);try{await Hr.access(c),o.push(a)}catch{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 tP(r,e){let t=Date.now();try{let n=await rP(e),s=r.fileCount,o=.1,i=Math.abs(n-s),a=s*o;return i<=a?{name:"File count verification",passed:!0,output:`File count accurate (declared: ${s}, actual: ${n})`,durationMs:Date.now()-t}:{name:"File count verification",passed:!1,error:`File count mismatch: declared ${s}, actual ${n} (diff: ${i})`,durationMs:Date.now()-t}}catch(n){return{name:"File count verification",passed:!1,error:`Failed to count files: ${n instanceof Error?n.message:"unknown error"}`,durationMs:Date.now()-t}}}async function nP(r,e){let t=Date.now();if(r.antiPatterns.length===0)return{name:"Anti-pattern file verification",passed:!0,output:"No anti-patterns declared (skipped)",durationMs:Date.now()-t};let n=[],s=[];for(let o of r.antiPatterns){let i=An.join(e,o.file);try{await Hr.access(i),s.push(o.file)}catch{n.push(`${o.issue} (${o.file})`)}}return n.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: ${n.join(", ")}`,durationMs:Date.now()-t}}async function Am(r,e){let t=Date.now(),n=await Promise.all([Qb(r,e),Zb(r,e),eP(r,e),tP(r,e),nP(r,e)]),s=n.filter(i=>!i.passed).length,o=n.filter(i=>i.passed).length;return{passed:s===0,checks:n,totalMs:Date.now()-t,failedCount:s,passedCount:o}}async function sP(r){let e=new Set,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function n(s){try{let o=await Hr.readdir(s,{withFileTypes:!0});for(let i of o){let a=An.join(s,i.name),c=An.relative(r,a);if(!t.some(u=>u.test(c))){if(i.isDirectory())await n(a);else if(i.isFile()){let u=An.extname(i.name);u&&e.add(u)}}}}catch{}}return l(n,"scanDir"),await n(r),Array.from(e)}async function rP(r){let e=0,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function n(s){try{let o=await Hr.readdir(s,{withFileTypes:!0});for(let i of o){let a=An.join(s,i.name),c=An.relative(r,a);t.some(u=>u.test(c))||(i.isDirectory()?await n(a):i.isFile()&&e++)}}catch{}}return l(n,"scanDir"),await n(r),e}var qb,Kb,Xb,Jc,D$,Yb,Wc=y(()=>{"use strict";M();wr();qb=ie.enum(["draft","verified","sealed"]),Kb=ie.object({name:ie.string(),description:ie.string(),location:ie.string().optional()}),Xb=ie.object({issue:ie.string(),file:ie.string(),suggestion:ie.string()}),Jc=ie.object({projectId:ie.string(),languages:ie.array(ie.string()),frameworks:ie.array(ie.string()),packageManager:ie.string().optional(),sourceDir:ie.string().optional(),testDir:ie.string().optional(),configFiles:ie.array(ie.string()),fileCount:ie.number(),patterns:ie.array(Kb),antiPatterns:ie.array(Xb),analyzedAt:ie.string(),modelMetadata:yr.optional(),status:qb.default("draft"),commitHash:ie.string().optional(),signature:ie.string().optional(),sealedAt:ie.string().optional(),verifiedAt:ie.string().optional()}),D$={languages:[],frameworks:[],configFiles:[],fileCount:0,patterns:[],antiPatterns:[],analyzedAt:new Date().toISOString(),status:"draft"},Yb={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(Qb,"verifyFrameworks");l(Zb,"verifyLanguages");l(eP,"verifyPatternLocations");l(tP,"verifyFileCount");l(nP,"verifyAntiPatternFiles");l(Am,"semanticVerify");l(sP,"getProjectExtensions");l(rP,"countProjectFiles")});import{z as Ie}from"zod";var mi,In,oP,F$,Bc,Im,Gr=y(()=>{"use strict";mi=Ie.enum(["frontend","backend","database","devops","testing","docs","uxui","general"]),In=Ie.object({primaryDomain:mi,secondaryDomains:Ie.array(mi),confidence:Ie.number().min(0).max(1),filePatterns:Ie.array(Ie.string()),relevantAgents:Ie.array(Ie.string())}),oP=Ie.object({classification:In,classifiedAt:Ie.string(),source:Ie.enum(["cache","history","llm","heuristic"]),descriptionHash:Ie.string(),projectId:Ie.string()}),F$=Ie.object({entries:Ie.record(Ie.string(),oP),confirmedPatterns:Ie.array(Ie.object({descriptionHash:Ie.string(),classification:In,confirmedAt:Ie.string(),taskDescription:Ie.string()}))}),Bc={entries:{},confirmedPatterns:[]},Im={primaryDomain:"general",secondaryDomains:[],confidence:.3,filePatterns:["**/*.ts","**/*.js"],relevantAgents:[]}});import{z as N}from"zod";var iP,aP,Dm,cP,lP,uP,pP,dP,Rm,N$,Vc=y(()=>{"use strict";iP=N.enum(["low","medium","high"]),aP=N.enum(["pending","converted","completed","archived","dormant"]),Dm=N.enum(["high","medium","low"]),cP=N.object({impact:Dm,effort:Dm}),lP=N.object({frontend:N.string().optional(),backend:N.string().optional(),payments:N.string().optional(),ai:N.string().optional(),deploy:N.string().optional(),other:N.array(N.string()).optional()}),uP=N.object({name:N.string(),description:N.string()}),pP=N.object({name:N.string(),description:N.string().optional()}),dP=N.object({id:N.string(),text:N.string(),details:N.string().optional(),priority:iP,status:aP,tags:N.array(N.string()),addedAt:N.string(),completedAt:N.string().optional(),convertedTo:N.string().optional(),source:N.string().optional(),sourceFiles:N.array(N.string()).optional(),painPoints:N.array(N.string()).optional(),solutions:N.array(N.string()).optional(),filesAffected:N.array(N.string()).optional(),impactEffort:cP.optional(),implementationNotes:N.string().optional(),stack:lP.optional(),modules:N.array(uP).optional(),roles:N.array(pP).optional(),risks:N.array(N.string()).optional(),risksCount:N.number().optional()}),Rm=N.object({ideas:N.array(dP),lastUpdated:N.string()}),N$={priority:"medium",status:"pending",tags:[],addedAt:new Date().toISOString()}});import{z as W}from"zod";function Fm(r){return{provider:r,lastSync:"",staleAfter:18e5,issues:{}}}var $m,mP,gP,fP,hP,yP,G$,Mm,qc=y(()=>{"use strict";$m=W.enum(["linear","jira","github","monday","asana","none"]),mP=W.enum(["backlog","todo","in_progress","in_review","done","cancelled"]),gP=W.enum(["none","urgent","high","medium","low"]),fP=W.enum(["feature","bug","improvement","task","chore","epic"]),hP=W.object({id:W.string(),identifier:W.string(),title:W.string(),description:W.string().optional(),status:mP,priority:gP,type:fP.optional(),assignee:W.object({id:W.string(),name:W.string(),email:W.string().optional()}).optional(),labels:W.array(W.string()).default([]),team:W.object({id:W.string(),name:W.string(),key:W.string().optional()}).optional(),project:W.object({id:W.string(),name:W.string()}).optional(),url:W.string(),createdAt:W.string(),updatedAt:W.string(),fetchedAt:W.string()}),yP=W.object({provider:$m,lastSync:W.string(),staleAfter:W.number().default(18e5),issues:W.record(W.string(),hP)}),G$=W.object({provider:$m,fetched:W.number(),updated:W.number(),errors:W.array(W.object({issueId:W.string(),error:W.string()})),timestamp:W.string()}),Mm=l(r=>yP.parse(r),"parseIssues");l(Fm,"createEmptyIssues")});var Um={};Ne(Um,{AgentAssignmentSchema:()=>Om,OUTPUT_SCHEMAS:()=>Nm,SubtaskBreakdownSchema:()=>_m,TaskClassificationSchema:()=>In,renderSchemaForPrompt:()=>Kc});import{z as Ge}from"zod";function Kc(r){let e=Nm[r];return e?`## OUTPUT FORMAT
500
-
501
- Return ONLY valid JSON matching this schema (no markdown, no explanation):
502
-
503
- \`\`\`json
504
- ${e.example}
505
- \`\`\`
506
-
507
- Fields:
508
- ${wP(e.schema)}`:null}function wP(r){if(r instanceof Ge.ZodObject){let e=r.shape;return Object.entries(e).map(([t,n])=>`- \`${t}\`: ${Lm(n)}`).join(`
509
- `)}return"(see example above)"}function Lm(r){return r instanceof Ge.ZodString?"string":r instanceof Ge.ZodNumber?"number":r instanceof Ge.ZodEnum?`one of: ${r.options.join(", ")}`:r instanceof Ge.ZodArray?`array of ${Lm(r.element)}`:r instanceof Ge.ZodObject?"object":"any"}var Om,_m,Nm,gi=y(()=>{"use strict";Gr();Gr();Om=Ge.object({agentName:Ge.string(),reasoning:Ge.string(),confidence:Ge.number().min(0).max(1)}),_m=Ge.object({subtasks:Ge.array(Ge.object({description:Ge.string(),domain:mi,agent:Ge.string(),dependsOn:Ge.array(Ge.number())})),effort:Ge.enum(["low","medium","high"])}),Nm={classification:{schema:In,example:JSON.stringify({primaryDomain:"backend",secondaryDomains:["database"],confidence:.9,filePatterns:["src/api/**"],relevantAgents:["backend.md"]},null,2)},agentAssignment:{schema:Om,example:JSON.stringify({agentName:"backend.md",reasoning:"Task involves API endpoint creation",confidence:.85},null,2)},subtaskBreakdown:{schema:_m,example:JSON.stringify({subtasks:[{description:"Add schema validation",domain:"backend",agent:"backend.md",dependsOn:[]},{description:"Add unit tests",domain:"testing",agent:"testing.md",dependsOn:[0]}],effort:"medium"},null,2)}};l(Kc,"renderSchemaForPrompt");l(wP,"describeSchema");l(Lm,"describeField")});import{z as j}from"zod";var Hm,kP,SP,Gm,bP,PP,CP,vP,xP,TP,EP,zm,jP,AP,X$,Jm,Wm,Bm,Vm,IP,fi,Xc=y(()=>{"use strict";Hm=j.number().min(1).max(5),kP=j.enum(["exceeded","met","partial","failed"]),SP=j.enum(["definitely","probably","maybe","no"]),Gm=j.enum(["scope_creep","underestimated_complexity","technical_debt","external_blockers","learning_curve","requirements_changed","optimistic_estimate","team_changes","other"]),bP=j.object({estimated:j.object({hours:j.number(),confidence:j.enum(["low","medium","high"]).optional(),source:j.enum(["prd","manual","historical"]).optional()}),actual:j.object({hours:j.number(),commits:j.number().optional(),linesAdded:j.number().optional(),linesRemoved:j.number().optional(),sessions:j.number().optional()}),variance:j.object({hours:j.number(),percentage:j.number(),reason:Gm.optional(),explanation:j.string().optional()})}),PP=j.object({name:j.string(),baseline:j.number().nullable(),target:j.number(),actual:j.number(),unit:j.string(),achieved:j.boolean(),percentOfTarget:j.number()}),CP=j.object({criteria:j.string(),met:j.boolean(),notes:j.string().optional()}),vP=j.object({metrics:j.array(PP),acceptanceCriteria:j.array(CP),overallSuccess:kP,successScore:j.number().min(0).max(100)}),xP=j.object({category:j.enum(["estimation","technical","process","communication","tooling","architecture","testing","other"]),insight:j.string(),actionable:j.boolean(),action:j.string().optional()}),TP=j.object({whatWorked:j.array(j.string()),whatDidnt:j.array(j.string()),surprises:j.array(j.string()),recommendations:j.array(xP)}),EP=j.object({valueDelivered:j.number().min(1).max(10),userImpact:j.enum(["none","low","medium","high","critical"]),businessImpact:j.enum(["none","low","medium","high","critical"]),roiScore:j.number(),worthIt:SP,worthItReason:j.string().optional(),alternativeConsidered:j.string().optional(),betterAlternativeExists:j.boolean().optional()}),zm=j.object({id:j.string(),taskId:j.string(),description:j.string(),estimatedMinutes:j.number().optional(),actualMinutes:j.number(),completedAsPlanned:j.boolean(),qualityScore:Hm,blockers:j.array(j.string()),agentUsed:j.string().optional(),skillsUsed:j.array(j.string()).optional(),startedAt:j.string(),completedAt:j.string()}),jP=j.object({id:j.string(),featureId:j.string(),featureName:j.string(),prdId:j.string().nullable(),version:j.string().optional(),branch:j.string().optional(),prUrl:j.string().optional(),effort:bP,success:vP.optional(),learnings:TP,roi:EP,rating:Hm,taskOutcomes:j.array(zm).optional(),startedAt:j.string(),shippedAt:j.string(),reviewedAt:j.string().optional(),reviewedBy:j.string().optional(),legacy:j.boolean().optional()}),AP=j.object({totalFeatures:j.number(),averageEstimationAccuracy:j.number(),averageSuccessRate:j.number(),averageROI:j.number(),bySuccessLevel:j.object({exceeded:j.number(),met:j.number(),partial:j.number(),failed:j.number()}),variancePatterns:j.array(j.object({reason:Gm,count:j.number(),averageVariance:j.number()})),topLearnings:j.array(j.object({insight:j.string(),frequency:j.number()}))}),X$=j.object({outcomes:j.array(jP),taskOutcomes:j.array(zm).optional(),aggregates:AP.optional(),lastUpdated:j.string(),lastAggregated:j.string().optional()}),Jm={outcomes:[],taskOutcomes:[],lastUpdated:""},Wm=l((r,e)=>{let t=e-r,n=r>0?(e-r)/r*100:0;return{hours:t,percentage:Math.round(n*10)/10}},"calculateVariance"),Bm=l((r,e)=>e<=0?r*10:Math.round(r*10/e*100)/100,"calculateROIScore"),Vm=l(r=>r>=100?"exceeded":r>=80?"met":r>=50?"partial":"failed","determineSuccessLevel"),IP=l(r=>Math.max(0,100-Math.abs(r)),"calculateEstimationAccuracy"),fi=l(r=>{if(r.length===0)return{totalFeatures:0,averageEstimationAccuracy:0,averageSuccessRate:0,averageROI:0,bySuccessLevel:{exceeded:0,met:0,partial:0,failed:0},variancePatterns:[],topLearnings:[]};let e=r.map(p=>IP(p.effort.variance.percentage)),t=r.filter(p=>p.success).map(p=>p.success.successScore),n=r.map(p=>p.roi.roiScore),s={exceeded:r.filter(p=>p.success?.overallSuccess==="exceeded").length,met:r.filter(p=>p.success?.overallSuccess==="met").length,partial:r.filter(p=>p.success?.overallSuccess==="partial").length,failed:r.filter(p=>p.success?.overallSuccess==="failed").length},o=r.filter(p=>p.effort.variance.reason).reduce((p,m)=>{let d=m.effort.variance.reason;return p[d]||(p[d]={count:0,totalVariance:0}),p[d].count++,p[d].totalVariance+=m.effort.variance.percentage,p},{}),i=Object.entries(o).map(([p,m])=>({reason:p,count:m.count,averageVariance:Math.round(m.totalVariance/m.count)})),c=r.flatMap(p=>[...p.learnings.whatWorked,...p.learnings.whatDidnt]).reduce((p,m)=>(p[m]=(p[m]||0)+1,p),{}),u=Object.entries(c).sort((p,m)=>m[1]-p[1]).slice(0,10).map(([p,m])=>({insight:p,frequency:m}));return{totalFeatures:r.length,averageEstimationAccuracy:Math.round(e.reduce((p,m)=>p+m,0)/e.length),averageSuccessRate:t.length>0?Math.round(t.reduce((p,m)=>p+m,0)/t.length):0,averageROI:Math.round(n.reduce((p,m)=>p+m,0)/n.length*100)/100,bySuccessLevel:s,variancePatterns:i,topLearnings:u}},"aggregateOutcomes")});import{z as Ue}from"zod";function OP(){let r={};for(let e of $P)r[e]="allow";for(let e of MP)r[e]="ask";for(let e of FP)r[e]="deny";return{bash:r,files:{read:{"**/*":"allow"},write:{"**/*":"allow"},delete:{"**/*":"ask"}},web:{enabled:!0},doomLoop:{enabled:!0,maxRetries:3},externalDirectories:"ask"}}var hi,eM,DP,Yc,RP,tM,$P,MP,FP,nM,qm=y(()=>{"use strict";hi=Ue.enum(["allow","deny","ask"]),eM=Ue.enum(["read","write","delete","create"]),DP=Ue.record(Ue.string(),hi),Yc=Ue.record(Ue.string(),hi),RP=Ue.object({enabled:Ue.boolean().default(!0),allowedDomains:Ue.array(Ue.string()).optional(),blockedDomains:Ue.array(Ue.string()).optional()}),tM=Ue.object({bash:DP.optional(),files:Ue.object({read:Yc.optional(),write:Yc.optional(),delete:Yc.optional()}).optional(),web:RP.optional(),skills:Ue.record(Ue.string(),hi).optional(),doomLoop:Ue.object({enabled:Ue.boolean().default(!0),maxRetries:Ue.number().default(3)}).optional(),externalDirectories:hi.default("ask")}),$P=["git status*","git log*","git diff*","git branch*","git remote*","ls*","pwd","cat*","head*","tail*","grep*","find*","which*","echo*","node -e*","bun -e*","npm list*","npm view*","npx tsc --noEmit*"],MP=["rm -rf*","rm -r*","git push*","git reset --hard*","git clean*","npm publish*","chmod*","chown*","sudo*","curl*|*sh","wget*|*sh"],FP=["rm -rf /*","rm -rf ~/*",":(){ :|:& };:*","mkfs*","dd if=*of=/dev/*"];l(OP,"buildDefaultPermissions");nM=OP()});import{z as et}from"zod";var iM,aM,Km=y(()=>{"use strict";iM=et.object({projectId:et.string(),name:et.string(),repoPath:et.string(),description:et.string().optional(),version:et.string().optional(),cliVersion:et.string().optional(),techStack:et.array(et.string()),fileCount:et.number(),commitCount:et.number(),createdAt:et.string(),lastSync:et.string(),lastSyncCommit:et.string().optional(),lastSyncBranch:et.string().optional()}),aM={techStack:[],fileCount:0,commitCount:0,createdAt:new Date().toISOString(),lastSync:new Date().toISOString()}});import{z as A}from"zod";var _P,NP,LP,UP,HP,GP,zP,JP,WP,BP,VP,qP,KP,XP,YP,QP,ZP,eC,pM,dM,Xm=y(()=>{"use strict";_P=A.enum(["planned","active","completed","shipped"]),NP=A.enum(["low","medium","high"]),LP=A.enum(["feature","breaking_change","refactor","infrastructure"]),UP=A.enum(["completed","active","planned"]),HP=A.enum(["planned","active","completed"]),GP=A.enum(["git","git-branch","manual","prd"]),zP=A.object({id:A.string(),description:A.string(),completed:A.boolean(),completedAt:A.string().optional()}),JP=A.object({id:A.string(),name:A.string(),status:UP,completedAt:A.string().optional()}),WP=A.object({goal:A.string(),phases:A.array(JP),successMetrics:A.array(A.string()).optional()}),BP=A.object({hours:A.number(),minutes:A.number(),totalMinutes:A.number(),display:A.string().optional()}),VP=A.object({hash:A.string(),message:A.string(),date:A.string(),author:A.string().optional()}),qP=A.object({hours:A.number(),confidence:A.enum(["low","medium","high"]).optional(),breakdown:A.array(A.object({area:A.string(),hours:A.number()})).optional()}),KP=A.object({hours:A.number().optional(),commits:A.number().optional(),linesAdded:A.number().optional(),linesRemoved:A.number().optional()}),XP=A.object({estimated:qP.nullable(),actual:KP.nullable()}),YP=A.object({totalHours:A.number(),allocatedHours:A.number(),bufferPercent:A.number().optional()}),QP=A.object({id:A.string(),name:A.string(),theme:A.string().optional(),goals:A.array(A.string()).optional(),features:A.array(A.string()),capacity:YP.optional(),status:HP,startDate:A.string().optional(),endDate:A.string().optional()}),ZP=A.object({id:A.string(),name:A.string(),description:A.string().optional(),date:A.string(),status:_P,impact:NP,effort:A.string().optional(),progress:A.number(),type:LP.optional(),roi:A.number().optional(),why:A.array(A.string()).optional(),technicalNotes:A.array(A.string()).optional(),compatibility:A.string().optional(),phase:A.string().optional(),tasks:A.array(zP),createdAt:A.string(),shippedAt:A.string().optional(),version:A.string().optional(),duration:BP.optional(),taskCount:A.number().optional(),agent:A.string().optional(),sprintName:A.string().optional(),completedDate:A.string().optional(),prdId:A.string().nullable().optional(),legacy:A.boolean().optional(),inferredFrom:GP.optional(),quarter:A.string().nullable().optional(),dependencies:A.array(A.string()).optional(),blockedBy:A.array(A.string()).optional(),effortTracking:XP.optional(),valueScore:A.number().optional(),commits:A.array(VP).optional(),branch:A.string().optional(),commitsAhead:A.number().optional()}),eC=A.object({id:A.string(),title:A.string(),prdId:A.string().nullable().optional(),valueScore:A.number().optional(),effortEstimate:A.number().optional(),reason:A.string().optional()}),pM=A.object({strategy:WP.nullable().optional(),features:A.array(ZP),backlog:A.array(A.union([A.string(),eC])),lastUpdated:A.string(),quarters:A.array(QP).optional(),generatedFrom:A.enum(["git-history","manual","prd"]).optional(),generatedAt:A.string().optional()}),dM={date:new Date().toISOString().split("T")[0],status:"planned",impact:"medium",progress:0,tasks:[],createdAt:new Date().toISOString(),prdId:null,legacy:!1,quarter:null}});import tC from"node:crypto";import{homedir as nC}from"node:os";import{join as Ym}from"node:path";function ye(){return tC.randomUUID()}function zr(r){return Ym(Qm,r)}var Qm,Qc=y(()=>{"use strict";l(ye,"generateUUID");Qm=Ym(nC(),".prjct-cli","projects");l(zr,"getProjectPath")});import{z as q}from"zod";var sC,Zm,rC,oC,iC,aC,cC,lC,uC,eg,Zc=y(()=>{"use strict";sC=q.enum(["feature","fix","improvement","refactor"]),Zm=q.enum(["pass","warning","fail","skipped"]),rC=q.enum(["added","changed","fixed","removed"]),oC=q.object({hours:q.number(),minutes:q.number(),totalMinutes:q.number()}),iC=q.object({filesChanged:q.number().nullable().optional(),linesAdded:q.number().nullable().optional(),linesRemoved:q.number().nullable().optional(),commits:q.number().nullable().optional()}),aC=q.object({description:q.string(),type:rC.optional()}),cC=q.object({lintStatus:Zm.nullable().optional(),lintDetails:q.string().optional(),testStatus:Zm.nullable().optional(),testDetails:q.string().optional()}),lC=q.object({hash:q.string().optional(),message:q.string().optional(),branch:q.string().optional()}),uC=q.object({id:q.string(),name:q.string(),version:q.string().nullable().optional(),type:sC,agent:q.string().optional(),description:q.string().optional(),changes:q.array(aC).optional(),codeSnippets:q.array(q.string()).optional(),commit:lC.optional(),codeMetrics:iC.optional(),qualityMetrics:cC.optional(),quantitativeImpact:q.string().optional(),duration:oC.optional(),tasksCompleted:q.number().nullable().optional(),shippedAt:q.string(),featureId:q.string().optional()}),eg=q.object({shipped:q.array(uC),lastUpdated:q.string()})});import{z as T}from"zod";var pC,ng,dC,mC,gC,el,sg,fC,hC,rg,tg,yC,wC,og,ig,ag,kC,SC,xM,yi=y(()=>{"use strict";wr();pC=T.enum(["low","medium","high","critical"]),ng=T.enum(["feature","bug","improvement","chore"]),dC=T.enum(["active","backlog","previously_active"]),mC=T.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),gC=T.enum(["task_completed","feature_shipped","idea_captured","session_started"]),el=T.object({title:T.string(),description:T.string(),filesChanged:T.array(T.object({path:T.string(),action:T.enum(["created","modified","deleted"])})),whatWasDone:T.array(T.string()).min(1),outputForNextAgent:T.string().min(1),notes:T.string().optional()}),sg=T.object({output:T.string().min(1,"Subtask output is required"),summary:el}),fC=T.object({id:T.string(),description:T.string(),domain:T.string(),agent:T.string(),status:mC,dependsOn:T.array(T.string()),startedAt:T.string().optional(),completedAt:T.string().optional(),output:T.string().optional(),summary:el.optional(),skipReason:T.string().optional(),blockReason:T.string().optional(),estimatedPoints:T.number().optional(),estimatedMinutes:T.number().optional()}),hC=T.object({completed:T.number(),total:T.number(),percentage:T.number()}),rg=T.object({id:T.string(),description:T.string(),startedAt:T.string(),sessionId:T.string(),featureId:T.string().optional(),subtasks:T.array(fC).optional(),currentSubtaskIndex:T.number().optional(),subtaskProgress:hC.optional(),linearId:T.string().optional(),linearUuid:T.string().optional(),estimatedPoints:T.number().optional(),estimatedMinutes:T.number().optional(),modelMetadata:yr.optional()}),tg=T.object({id:T.string(),description:T.string(),status:T.literal("paused"),startedAt:T.string(),pausedAt:T.string(),pauseReason:T.string().optional()}),yC=T.object({stackConfirmed:T.array(T.string()).optional(),patternsDiscovered:T.array(T.string()).optional(),agentAccuracy:T.array(T.object({agent:T.string(),rating:T.enum(["helpful","neutral","inaccurate"]),note:T.string().optional()})).optional(),issuesEncountered:T.array(T.string()).optional()}),wC=T.object({taskId:T.string(),title:T.string(),classification:ng,startedAt:T.string(),completedAt:T.string(),subtaskCount:T.number(),subtaskSummaries:T.array(el),outcome:T.string(),branchName:T.string(),linearId:T.string().optional(),linearUuid:T.string().optional(),prUrl:T.string().optional(),feedback:yC.optional()}),og=T.object({currentTask:rg.nullable(),previousTask:tg.nullable().optional(),pausedTasks:T.array(tg).optional(),taskHistory:T.array(wC).optional(),lastUpdated:T.string()}),ig=T.object({id:T.string(),description:T.string(),priority:pC,type:ng,featureId:T.string().optional(),originFeature:T.string().optional(),completed:T.boolean(),completedAt:T.string().optional(),createdAt:T.string(),section:dC,agent:T.string().optional(),groupName:T.string().optional(),groupId:T.string().optional()}),ag=T.object({tasks:T.array(ig),lastUpdated:T.string()}),kC=T.object({tasksToday:T.number(),tasksThisWeek:T.number(),streak:T.number(),velocity:T.string(),avgDuration:T.string()}),SC=T.object({type:gC,description:T.string(),timestamp:T.string(),duration:T.string().optional()}),xM=T.object({projectId:T.string(),currentTask:rg.nullable(),queue:T.array(ig),stats:kC,recentActivity:T.array(SC),lastSync:T.string()})});import{z as re}from"zod";var bC,PC,cg,AM,IM,DM,Dn,lg,Bs=y(()=>{"use strict";bC=re.enum(["improving","stable","declining"]),PC=re.object({sprintNumber:re.number(),startDate:re.string(),endDate:re.string(),pointsCompleted:re.number(),tasksCompleted:re.number(),avgVariance:re.number(),estimationAccuracy:re.number()}),cg=re.object({category:re.string(),avgVariance:re.number(),taskCount:re.number()}),AM=re.object({totalPoints:re.number(),sprints:re.number(),estimatedDate:re.string()}),IM=re.object({sprints:re.array(PC),averageVelocity:re.number(),velocityTrend:bC,estimationAccuracy:re.number(),overEstimated:re.array(cg),underEstimated:re.array(cg),lastUpdated:re.string()}),DM=re.object({sprintLengthDays:re.number().min(1).max(90).default(7),startDay:re.enum(["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]).default("monday"),windowSize:re.number().min(1).max(52).default(6),accuracyTolerance:re.number().min(0).max(100).default(20)}),Dn={sprintLengthDays:7,startDay:"monday",windowSize:6,accuracyTolerance:20},lg={sprints:[],averageVelocity:0,velocityTrend:"stable",estimationAccuracy:0,overEstimated:[],underEstimated:[],lastUpdated:""}});var _t=y(()=>{"use strict";jm();Wc();Gr();Vc();qc();gi();wr();Xc();qm();Km();Xm();Qc();Zc();yi();Bs()});var Zn,tl=y(()=>{"use strict";_t();Ls();ne();Lr();Zn=class extends Qn{static{l(this,"SemanticMemories")}getFilename(){return"memories.json"}getDefault(){return{version:1,memories:[],index:this._createEmptyIndex()}}afterLoad(e){this._normalizeIndex(e)}_createEmptyIndex(){let e=Object.values(R),t={};for(let n of e)t[n]=[];return t}_normalizeIndex(e){let t=Object.values(R);for(let n of t)e.index[n]||(e.index[n]=[])}_coerceTags(e){let t=new Set(Object.values(R));return e.filter(n=>t.has(n))}async loadMemories(e){return this.load(e)}async saveMemories(e){return this.save(e)}async createMemory(e,{title:t,content:n,tags:s=[],userTriggered:o=!1}){let i=await this.load(e),a=this._coerceTags(s),c=b(),u={id:ye(),title:t,content:n,tags:a,userTriggered:o,createdAt:c,updatedAt:c};i.memories.push(u);for(let p of a)i.index[p].push(u.id);return await this.save(e),u.id}async updateMemory(e,t,n){let s=await this.load(e),o=s.memories.findIndex(c=>c.id===t);if(o===-1)return!1;let i=s.memories[o],a=i.tags||[];if(n.title&&(i.title=n.title),n.content&&(i.content=n.content),n.tags){let c=this._coerceTags(n.tags);for(let u of a)s.index[u]=s.index[u].filter(p=>p!==t);for(let u of c)s.index[u].push(t);i.tags=c}return i.updatedAt=b(),await this.save(e),!0}async deleteMemory(e,t){let n=await this.load(e),s=n.memories.findIndex(i=>i.id===t);if(s===-1)return!1;let o=n.memories[s];for(let i of o.tags||[])n.index[i]&&(n.index[i]=n.index[i].filter(a=>a!==t));return n.memories.splice(s,1),await this.save(e),!0}async findByTags(e,t,n=!1){let s=await this.load(e),o=this._coerceTags(t);if(n)return s.memories.filter(i=>o.every(a=>(i.tags||[]).includes(a)));{let i=new Set;for(let a of o){let c=s.index[a];for(let u of c)i.add(u)}return s.memories.filter(a=>i.has(a.id))}}async searchMemories(e,t){let n=await this.load(e),s=t.toLowerCase();return n.memories.filter(o=>o.title.toLowerCase().includes(s)||o.content.toLowerCase().includes(s))}async getRelevantMemories(e,t,n=5){return(await this.load(e)).memories.map(i=>{let a=0,c=this._extractContextTags(t);for(let d of i.tags||[])c.includes(d)&&(a+=10);let p=(Date.now()-new Date(i.updatedAt).getTime())/(1e3*60*60*24);a+=Math.max(0,5-p),i.userTriggered&&(a+=5);let m=this._extractKeywords(t);for(let d of m)i.content.toLowerCase().includes(d)&&(a+=2),i.title.toLowerCase().includes(d)&&(a+=3);return{...i,_score:a}}).filter(i=>i._score>0).sort((i,a)=>a._score-i._score).slice(0,n).map(({_score:i,...a})=>a)}async getRelevantMemoriesWithMetrics(e,t){let n=await this.load(e),s=n.memories.length;if(s===0)return{memories:[],metrics:{totalMemories:0,memoriesConsidered:0,memoriesReturned:0,filteringRatio:0,avgRelevanceScore:0}};let o=t.maxResults??10,i=t.minRelevance??10,c=n.memories.map(d=>{let g={domainMatch:0,tagMatch:0,recency:0,confidence:0,keywords:0,userTriggered:0};if(t.taskDomain&&(g.domainMatch=this._getSemanticDomainScore(t.taskDomain,d.tags||[])),t.commandName){let x=this._getCommandTags(t.commandName),$=(d.tags||[]).filter(z=>x.includes(z));g.tagMatch=Math.min(20,$.length*8)}let S=(Date.now()-new Date(d.updatedAt).getTime())/(1e3*60*60*24);if(g.recency=Math.max(0,Math.round(15-S*.5)),d.confidence?g.confidence=d.confidence==="high"?20:d.confidence==="medium"?12:5:d.observationCount&&(g.confidence=Math.min(20,d.observationCount*3)),t.taskDescription){let x=this._extractKeywordsFromText(t.taskDescription),$=0;for(let z of x)d.content.toLowerCase().includes(z)&&($+=2),d.title.toLowerCase().includes(z)&&($+=3);g.keywords=Math.min(15,$)}d.userTriggered&&(g.userTriggered=5);let E=g.domainMatch+g.tagMatch+g.recency+g.confidence+g.keywords+g.userTriggered;return{...d,relevanceScore:E,scoreBreakdown:g}}).filter(d=>d.relevanceScore>=i),p=c.sort((d,g)=>g.relevanceScore-d.relevanceScore).slice(0,o),m=p.length>0?Math.round(p.reduce((d,g)=>d+g.relevanceScore,0)/p.length):0;return{memories:p,metrics:{totalMemories:s,memoriesConsidered:c.length,memoriesReturned:p.length,filteringRatio:s>0?p.length/s:0,avgRelevanceScore:m}}}_getSemanticDomainScore(e,t){let n=this._resolveCanonicalDomains(e);if(n.length===0)return 0;let s=new Set;for(let a of n){let c=Lc[a];if(c)for(let u of c)s.add(u)}let o=new Set;for(let a of n){let c=di[a];if(c)for(let u of c)o.add(u)}let i=0;for(let a of t){if(s.has(a)){i+=10;continue}let c=a.toLowerCase().replace(/[-_\s]/g,"");for(let u of o)if(c.includes(u)||u.includes(c)){i+=5;break}}return Math.min(25,i)}_resolveCanonicalDomains(e){return Uc(e)}_getCommandTags(e){return{ship:[R.COMMIT_STYLE,R.SHIP_WORKFLOW,R.TEST_BEHAVIOR],feature:[R.ARCHITECTURE,R.CODE_STYLE],done:[R.SHIP_WORKFLOW],analyze:[R.TECH_STACK,R.ARCHITECTURE],spec:[R.ARCHITECTURE,R.CODE_STYLE],task:[R.BRANCH_NAMING,R.CODE_STYLE],sync:[R.TECH_STACK,R.ARCHITECTURE,R.DEPENDENCIES],test:[R.TEST_BEHAVIOR],bug:[R.CODE_STYLE,R.TEST_BEHAVIOR]}[e]||[]}_extractKeywordsFromText(e){let t=e.toLowerCase().split(/\s+/),n=new Set(["the","a","an","is","are","to","for","and","or","in","on","at","by","with","from","as","it","this","that","be","have","has"]);return t.filter(s=>s.length>2&&!n.has(s))}_extractContextTags(e){let t=[],n={ship:[R.COMMIT_STYLE,R.SHIP_WORKFLOW,R.TEST_BEHAVIOR],feature:[R.ARCHITECTURE,R.CODE_STYLE],done:[R.SHIP_WORKFLOW],analyze:[R.TECH_STACK,R.ARCHITECTURE],spec:[R.ARCHITECTURE,R.CODE_STYLE]};return e.commandName&&n[e.commandName]&&t.push(...n[e.commandName]),t}_extractKeywords(e){let t=[];e.params?.description&&t.push(...e.params.description.toLowerCase().split(/\s+/)),e.params?.feature&&t.push(...e.params.feature.toLowerCase().split(/\s+/));let n=["the","a","an","is","are","to","for","and","or","in"];return t.filter(s=>s.length>2&&!n.includes(s))}async autoRemember(e,t,n,s=""){let i={commit_footer:[R.COMMIT_STYLE],branch_naming:[R.BRANCH_NAMING],test_before_ship:[R.TEST_BEHAVIOR,R.SHIP_WORKFLOW],preferred_agent:[R.AGENT_PREFERENCE],code_style:[R.CODE_STYLE],verbosity:[R.OUTPUT_VERBOSITY]}[t]||[],a=await this.searchMemories(e,t);a.length>0?await this.updateMemory(e,a[0].id,{content:`${t}: ${n}`,tags:i}):await this.createMemory(e,{title:`Preference: ${t}`,content:`${t}: ${n}${s?`
510
- Context: ${s}`:""}`,tags:i,userTriggered:!0})}async getAllMemories(e){return(await this.load(e)).memories}async getMemoryStats(e){let t=await this.load(e),n={};for(let[s,o]of Object.entries(t.index))n[s]=o.length;return{totalMemories:t.memories.length,userTriggered:t.memories.filter(s=>s.userTriggered).length,tagCounts:n,oldestMemory:t.memories[0]?.createdAt,newestMemory:t.memories[t.memories.length-1]?.createdAt}}}});var nl,CC,Ce,Vs=y(()=>{"use strict";Lr();zc();tl();Lr();zc();tl();nl=class{static{l(this,"MemorySystem")}_semanticMemories;_patternStore;_historyStore;_sessionStore;constructor(){this._semanticMemories=new Zn,this._patternStore=new Ur,this._historyStore=new Nr,this._sessionStore=new _r}loadMemories(e){return this._semanticMemories.loadMemories(e)}saveMemories(e){return this._semanticMemories.saveMemories(e)}createMemory(e,t){return this._semanticMemories.createMemory(e,t)}updateMemory(e,t,n){return this._semanticMemories.updateMemory(e,t,n)}deleteMemory(e,t){return this._semanticMemories.deleteMemory(e,t)}findByTags(e,t,n){return this._semanticMemories.findByTags(e,t,n)}searchMemories(e,t){return this._semanticMemories.searchMemories(e,t)}getRelevantMemories(e,t,n){return this._semanticMemories.getRelevantMemories(e,t,n)}autoRemember(e,t,n,s){return this._semanticMemories.autoRemember(e,t,n,s)}getAllMemories(e){return this._semanticMemories.getAllMemories(e)}getMemoryStats(e){return this._semanticMemories.getMemoryStats(e)}getRelevantMemoriesWithMetrics(e,t){return this._semanticMemories.getRelevantMemoriesWithMetrics(e,t)}setSession(e,t){this._sessionStore.setSession(e,t)}getSession(e){return this._sessionStore.getSession(e)}clearSession(){this._sessionStore.clearSession()}loadPatterns(e){return this._patternStore.loadPatterns(e)}savePatterns(e){return this._patternStore.savePatterns(e)}recordDecision(e,t,n,s){return this._patternStore.recordDecision(e,t,n,s)}getDecision(e,t){return this._patternStore.getDecision(e,t)}hasPattern(e,t){return this._patternStore.hasPattern(e,t)}recordWorkflow(e,t,n){return this._patternStore.recordWorkflow(e,t,n)}getWorkflow(e,t){return this._patternStore.getWorkflow(e,t)}setPreference(e,t,n,s){return this._patternStore.setPreference(e,t,n,s)}getPreference(e,t,n){return this._patternStore.getPreference(e,t,n)}confirmPreference(e,t){return this._patternStore.confirmPreference(e,t)}confirmDecision(e,t){return this._patternStore.confirmDecision(e,t)}confirmWorkflow(e,t){return this._patternStore.confirmWorkflow(e,t)}getPatternsSummary(e){return this._patternStore.getPatternsSummary(e)}archiveStaleDecisions(e){return this._patternStore.archiveStaleDecisions(e)}appendHistory(e,t){return this._historyStore.appendHistory(e,t)}getRecentHistory(e,t){return this._historyStore.getRecentHistory(e,t)}async getSmartDecision(e,t){let n=this.getSession(`decision:${t}`);if(n!==void 0)return n;let s=await this.getDecision(e,t);return s?s.value:null}async learnDecision(e,t,n,s=""){this.setSession(`decision:${t}`,n),await this.recordDecision(e,t,n,s),await this.appendHistory(e,{type:"decision",key:t,value:n,context:s})}resetState(){this._sessionStore.clearSession(),this._semanticMemories.reset(),this._patternStore.reset()}},CC=new nl,Ce=CC});function sl(r,e){let t=Jr(e),n=vC[t.startDay],s=new Date(r);s.setHours(0,0,0,0);let i=(s.getDay()-n+7)%7;return s.setDate(s.getDate()-i),s}function xC(r,e){let t=Jr(e),n=new Date(r);return n.setDate(n.getDate()+t.sprintLengthDays-1),n.setHours(23,59,59,999),n}function TC(r,e,t){let n=Jr(t),s=sl(r,t),o=sl(e,t),i=s.getTime()-o.getTime(),a=Math.round(i/(1e3*60*60*24));return Math.floor(a/n.sprintLengthDays)+1}function wi(r,e=Dn){let t=Jr(e);if(r.length===0)return{sprints:[],averageVelocity:0,velocityTrend:"stable",estimationAccuracy:0,overEstimated:[],underEstimated:[],lastUpdated:new Date().toISOString()};let n=EC(r,e),s=jC(n,t.accuracyTolerance),o=s.slice(-t.windowSize),i=DC(o),a=AC(o),c=IC(r,t.accuracyTolerance),{overEstimated:u,underEstimated:p}=RC(r);return{sprints:s,averageVelocity:i,velocityTrend:a,estimationAccuracy:c,overEstimated:u,underEstimated:p,lastUpdated:new Date().toISOString()}}function pg(r,e,t=Dn){let n=Jr(t);if(e<=0)return{totalPoints:r,sprints:0,estimatedDate:""};let s=Math.ceil(r/e),o=s*n.sprintLengthDays,i=new Date;return i.setDate(i.getDate()+o),{totalPoints:r,sprints:s,estimatedDate:i.toISOString()}}function EC(r,e){let t=new Map,n=r.map(o=>new Date(o.completedAt)),s=new Date(Math.min(...n.map(o=>o.getTime())));for(let o of r){let i=new Date(o.completedAt),a=TC(i,s,e);if(!t.has(a)){let c=sl(i,e),u=xC(c,e);t.set(a,{sprintNumber:a,startDate:c,endDate:u,outcomes:[]})}t.get(a).outcomes.push(o)}return t}function jC(r,e){let t=[];for(let[,n]of r){let s=n.outcomes.reduce((u,p)=>u+$C(p),0),o=n.outcomes.filter(u=>u.variance).map(u=>ol(u)),i=o.length>0?Math.round(o.reduce((u,p)=>u+p,0)/o.length):0,a=o.filter(u=>Math.abs(u)<=e).length,c=o.length>0?Math.round(a/o.length*100):0;t.push({sprintNumber:n.sprintNumber,startDate:n.startDate.toISOString(),endDate:n.endDate.toISOString(),pointsCompleted:s,tasksCompleted:n.outcomes.length,avgVariance:i,estimationAccuracy:c})}return t.sort((n,s)=>n.sprintNumber-s.sprintNumber)}function AC(r){if(r.length<3)return"stable";let e=r.map(p=>p.pointsCompleted),t=e.length,n=0,s=0,o=0,i=0;for(let p=0;p<t;p++)n+=p,s+=e[p],o+=p*e[p],i+=p*p;let a=(t*o-n*s)/(t*i-n*n),c=s/t;if(c===0)return"stable";let u=a/c;return u>.1?"improving":u<-.1?"declining":"stable"}function IC(r,e){let t=r.filter(s=>s.variance);if(t.length===0)return 0;let n=t.filter(s=>{let o=ol(s);return Math.abs(o)<=e});return Math.round(n.length/t.length*100)}function DC(r){if(r.length===0)return 0;let e=r.reduce((t,n)=>t+n.pointsCompleted,0);return Math.round(e/r.length*10)/10}function RC(r){let e=new Map;for(let s of r){if(!s.variance)continue;let o=ol(s),i=s.tags&&s.tags.length>0?s.tags:["uncategorized"];for(let a of i){e.has(a)||e.set(a,{variances:[],count:0});let c=e.get(a);c.variances.push(o),c.count++}}let t=[],n=[];for(let[s,o]of e){if(o.count<2)continue;let i=Math.round(o.variances.reduce((a,c)=>a+c,0)/o.variances.length);i>10?n.push({category:s,avgVariance:i,taskCount:o.count}):i<-10&&t.push({category:s,avgVariance:Math.abs(i),taskCount:o.count})}return t.sort((s,o)=>o.avgVariance-s.avgVariance),n.sort((s,o)=>o.avgVariance-s.avgVariance),{overEstimated:t,underEstimated:n}}function ol(r){if(!r.variance)return 0;let e=rl(r.estimatedDuration),t=rl(r.actualDuration);return e<=0?0:Math.round((t-e)/e*100)}function rl(r){let e=0,t=r.match(/(\d+)h/);t&&(e+=Number.parseInt(t[1],10)*60);let n=r.match(/(\d+)m/);return n&&(e+=Number.parseInt(n[1],10)),r.match(/(\d+)s/)&&e===0&&(e=1),e}function dg(r){if(r.sprints.length===0)return"No velocity data available yet.";let e=[];e.push(`Project velocity: ${r.averageVelocity} pts/sprint (trend: ${r.velocityTrend})`),e.push(`Estimation accuracy: ${r.estimationAccuracy}%`);for(let t of r.underEstimated)e.push(`\u26A0 "${t.category}" tasks historically take ${t.avgVariance}% longer than estimated`);for(let t of r.overEstimated)e.push(`"${t.category}" tasks typically finish ${t.avgVariance}% faster than estimated`);return e.join(`
511
- `)}function $C(r){if(!r.estimatedDuration)return 0;let e=rl(r.estimatedDuration);if(e<=0)return 0;let t=ug[0],n=Number.POSITIVE_INFINITY;for(let s of ug){let o=Math.abs(s.typical-e);o<n&&(n=o,t=s)}return t.points}function Jr(r){return{sprintLengthDays:r.sprintLengthDays??7,startDay:r.startDay??"monday",windowSize:r.windowSize??6,accuracyTolerance:r.accuracyTolerance??20}}var vC,ug,il=y(()=>{"use strict";Bs();vC={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};l(sl,"getSprintStart");l(xC,"getSprintEnd");l(TC,"getSprintNumber");l(wi,"calculateVelocity");l(pg,"projectCompletion");l(EC,"bucketBySprint");l(jC,"buildSprintVelocities");l(AC,"detectTrend");l(IC,"calculateOverallAccuracy");l(DC,"calculateAverageVelocity");l(RC,"detectEstimationPatterns");l(ol,"parseVariancePercent");l(rl,"parseDurationMinutes");l(dg,"formatVelocityContext");ug=[{points:1,typical:10},{points:2,typical:20},{points:3,typical:45},{points:5,typical:90},{points:8,typical:180},{points:13,typical:360},{points:21,typical:720}];l($C,"derivePoints");l(Jr,"resolveConfig")});import{createHash as MC}from"node:crypto";var al,nn,ki=y(()=>{"use strict";Wc();ne();Qt();al=class extends Le{static{l(this,"AnalysisStorage")}constructor(){super("analysis.json")}getDefault(){return{draft:null,sealed:null,lastUpdated:""}}getMdFilename(){return"analysis.md"}getLayer(){return"analysis"}getEventType(e){return`analysis.${e}d`}toMarkdown(e){let t=["# Analysis Status",""];return e.sealed&&(t.push("## Sealed Analysis"),t.push("- **Status**: sealed"),t.push(`- **Commit**: \`${e.sealed.commitHash||"unknown"}\``),t.push(`- **Sealed at**: ${e.sealed.sealedAt||"unknown"}`),t.push(`- **Languages**: ${e.sealed.languages.join(", ")||"none"}`),t.push(`- **Frameworks**: ${e.sealed.frameworks.join(", ")||"none"}`),t.push(`- **Files**: ${e.sealed.fileCount}`),e.sealed.patterns.length>0&&t.push(`- **Patterns**: ${e.sealed.patterns.map(n=>n.name).join(", ")}`),t.push("")),e.draft&&e.draft.status==="draft"&&(t.push("## Draft Analysis"),t.push("- **Status**: draft (not yet sealed)"),t.push(`- **Commit**: \`${e.draft.commitHash||"unknown"}\``),t.push(`- **Analyzed at**: ${e.draft.analyzedAt}`),t.push(`- **Languages**: ${e.draft.languages.join(", ")||"none"}`),t.push(`- **Frameworks**: ${e.draft.frameworks.join(", ")||"none"}`),t.push(`- **Files**: ${e.draft.fileCount}`),t.push("")),!e.sealed&&!e.draft&&(t.push("_No analysis available. Run `p. sync` to generate._"),t.push("")),t.join(`
512
- `)}async saveDraft(e,t){let n={...t,status:"draft"};Jc.parse(n),await this.update(e,s=>({...s,draft:n,lastUpdated:b()})),await this.publishEntityEvent(e,"analysis","drafted",{commitHash:n.commitHash,fileCount:n.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 n=this.computeSignature(t.draft),s=b(),o={...t.draft,status:"sealed",signature:n,sealedAt:s};return Jc.parse(o),await this.write(e,{draft:null,sealed:o,lastUpdated:s}),await this.publishEntityEvent(e,"analysis","sealed",{commitHash:o.commitHash,signature:n}),{success:!0,signature:n}}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,sealedCommit:t.sealed?.commitHash??null,draftCommit:t.draft?.commitHash??null,sealedAt:t.sealed?.sealedAt??null}}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 n=this.computeSignature({...t.sealed,signature:void 0,sealedAt:void 0});return n===t.sealed.signature?{valid:!0,message:"Signature verified. Analysis integrity confirmed."}:{valid:!1,message:`Signature mismatch. Expected ${n}, got ${t.sealed.signature}. Analysis may have been modified.`}}async semanticVerify(e,t){let n=await this.read(e),s=n.sealed??n.draft;return s?await Am(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 MC("sha256").update(JSON.stringify(t)).digest("hex")}},nn=new al});var Nt,cl,yt,Rn=y(()=>{"use strict";_t();ne();Yt();Nt={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},cl=class{static{l(this,"ArchiveStorage")}archive(e,t){let n=ye(),s=b();return V.run(e,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",n,t.entityType,t.entityId,JSON.stringify(t.entityData),t.summary??null,s,t.reason),n}archiveMany(e,t){if(t.length===0)return 0;let n=b();return V.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(ye(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,n,i.reason)}),t.length}getArchived(e,t,n=50){return t?V.query(e,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",t,n):V.query(e,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",n)}getStats(e){let t=V.query(e,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),n={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 n&&(n[o]=s.count),n.total+=s.count}return n}restore(e,t){let n=V.get(e,"SELECT * FROM archives WHERE id = ?",t);return n?(V.run(e,"DELETE FROM archives WHERE id = ?",t),JSON.parse(n.entity_data)):null}pruneOldArchives(e,t){let n=new Date(Date.now()-t*24*60*60*1e3).toISOString(),s=this.getTotalCount(e);V.run(e,"DELETE FROM archives WHERE archived_at < ?",n);let o=this.getTotalCount(e);return s-o}getTotalCount(e){return V.get(e,"SELECT COUNT(*) as count FROM archives")?.count??0}},yt=new cl});var ll,dn,ul=y(()=>{"use strict";_t();Vc();ne();Rn();Qt();ll=class extends Le{static{l(this,"IdeasStorage")}constructor(){super("ideas.json",Rm)}getDefault(){return{ideas:[],lastUpdated:""}}getMdFilename(){return"ideas.md"}getLayer(){return"planning"}getEventType(e){return`ideas.${e}d`}toMarkdown(e){let t=["# IDEAS \u{1F4A1}",""],n=e.ideas.filter(a=>a.status==="pending"),s=e.ideas.filter(a=>a.status==="converted"),o=e.ideas.filter(a=>a.status==="archived"),i=e.ideas.filter(a=>a.status==="dormant");return t.push("## Brain Dump"),n.length>0?n.forEach(a=>{let c=gt(a.addedAt),u=a.tags.length>0?` ${a.tags.map(m=>`#${m}`).join(" ")}`:"",p=a.priority!=="medium"?` [${a.priority.toUpperCase()}]`:"";t.push(`- ${a.text}${p} _(${c})_${u}`)}):t.push("_No pending ideas_"),t.push(""),s.length>0&&(t.push("## Converted"),s.forEach(a=>{let c=gt(a.addedAt),u=a.convertedTo?` \u2192 ${a.convertedTo}`:"";t.push(`- \u2713 ${a.text}${u} _(${c})_`)}),t.push("")),o.length>0&&(t.push("## Archived"),o.forEach(a=>{let c=gt(a.addedAt);t.push(`- ${a.text} _(${c})_`)}),t.push("")),i.length>0&&(t.push(`_${i.length} dormant idea(s) excluded from context_`),t.push("")),t.join(`
513
- `)}async getAll(e){return(await this.read(e)).ideas}async getPending(e){return(await this.read(e)).ideas.filter(n=>n.status==="pending")}async addIdea(e,t,n={}){let s={id:ye(),text:t,status:"pending",priority:n.priority||"medium",tags:n.tags||[],addedAt:b()};return await this.update(e,o=>({ideas:[s,...o.ideas],lastUpdated:b()})),await this.publishEvent(e,"idea.created",{ideaId:s.id,text:s.text,priority:s.priority}),s}async getById(e,t){return(await this.read(e)).ideas.find(s=>s.id===t)}async convertToFeature(e,t,n){await this.update(e,s=>({ideas:s.ideas.map(o=>o.id===t?{...o,status:"converted",convertedTo:n}:o),lastUpdated:b()})),await this.publishEvent(e,"idea.converted",{ideaId:t,featureId:n})}async archive(e,t){await this.update(e,n=>({ideas:n.ideas.map(s=>s.id===t?{...s,status:"archived"}:s),lastUpdated:b()})),await this.publishEvent(e,"idea.archived",{ideaId:t})}async setPriority(e,t,n){await this.update(e,s=>({ideas:s.ideas.map(o=>o.id===t?{...o,priority:n}:o),lastUpdated:b()}))}async addTags(e,t,n){await this.update(e,s=>({ideas:s.ideas.map(o=>o.id===t?{...o,tags:[...new Set([...o.tags,...n])]}:o),lastUpdated:b()}))}async removeIdea(e,t){await this.update(e,n=>({ideas:n.ideas.filter(s=>s.id!==t),lastUpdated:b()}))}async getCounts(e){let t=await this.read(e);return{pending:t.ideas.filter(n=>n.status==="pending").length,converted:t.ideas.filter(n=>n.status==="converted").length,archived:t.ideas.filter(n=>n.status==="archived").length}}async cleanup(e){let n=(await this.read(e)).ideas.filter(a=>a.status==="archived");if(n.length<=50)return{removed:0};let s=n.sort((a,c)=>new Date(c.addedAt).getTime()-new Date(a.addedAt).getTime()),o=new Set(s.slice(50).map(a=>a.id)),i=o.size;return await this.update(e,a=>({ideas:a.ideas.filter(c=>!o.has(c.id)),lastUpdated:b()})),{removed:i}}async markDormantIdeas(e){let t=await this.read(e),n=bn(Nt.IDEA_DORMANT_DAYS),s=t.ideas.filter(i=>i.status==="pending"&&new Date(i.addedAt)<n);if(s.length===0)return 0;yt.archiveMany(e,s.map(i=>({entityType:"idea",entityId:i.id,entityData:i,summary:i.text,reason:"dormant"})));let o=new Set(s.map(i=>i.id));return await this.update(e,i=>({ideas:i.ideas.map(a=>o.has(a.id)?{...a,status:"dormant"}:a),lastUpdated:b()})),await this.publishEvent(e,"ideas.dormant",{count:s.length}),s.length}},dn=new ll});import FC from"node:crypto";import Si from"node:fs/promises";import mg from"node:path";function gg(){return{version:Lt,lastUpdated:"",checksums:{}}}var Lt,pl,Ve,Wr=y(()=>{"use strict";ee();M();ne();Yt();Lt="1.0.0";l(gg,"getDefaultChecksums");pl=class{static{l(this,"IndexStorage")}getIndexPath(e){return mg.join(P.getGlobalProjectPath(e),"index")}async ensureIndexDir(e){let t=this.getIndexPath(e);return await Si.mkdir(t,{recursive:!0}),t}async readIndex(e){try{let t=this.getIndexMeta(e,"project-index");if(t!==null)return t.version!==Lt?null:t}catch{}return null}async writeIndex(e,t){this.setIndexMeta(e,"project-index",t)}async hasValidIndex(e){let t=await this.readIndex(e);return t!==null&&t.lastFullScan!==""}async readChecksums(e){try{let t=this.getIndexMeta(e,"checksums");if(t!==null)return t}catch{}return gg()}async writeChecksums(e,t){this.setIndexMeta(e,"checksums",t)}async calculateChecksum(e){try{let t=await Si.readFile(e);return FC.createHash("md5").update(t).digest("hex")}catch{return""}}async detectChangedFiles(e,t){let s=(await this.readChecksums(e)).checksums,o=[],i=[],a=[];for(let[c,u]of t)c in s?s[c]!==u&&i.push(c):o.push(c);for(let c of Object.keys(s))t.has(c)||a.push(c);return{added:o,modified:i,deleted:a}}async readScores(e){try{let t=this.getIndexMeta(e,"file-scores");if(t!==null)return t.scores||[]}catch{}return[]}async writeScores(e,t){let n={version:Lt,lastUpdated:b(),scores:t};this.setIndexMeta(e,"file-scores",n)}async clearIndex(e){try{V.getDb(e).prepare("DELETE FROM index_meta").run()}catch{}let t=this.getIndexPath(e);try{let n=await Si.readdir(t);await Promise.all(n.map(s=>Si.unlink(mg.join(t,s))))}catch(n){if(!k(n))throw n}}async getIndexAge(e){let t=await this.readIndex(e);if(!t||!t.lastFullScan)return 1/0;let n=new Date(t.lastFullScan);return(new Date().getTime()-n.getTime())/(1e3*60*60)}async readDomains(e){try{let t=this.getIndexMeta(e,"domains");if(t!==null)return t.version!==Lt?null:t}catch{}return null}async writeDomains(e,t){this.setIndexMeta(e,"domains",t)}async readCategories(e){try{let t=this.getIndexMeta(e,"categories-cache");if(t!==null)return t.version!==Lt?null:t}catch{}return null}async writeCategories(e,t){this.setIndexMeta(e,"categories-cache",t)}async getFileCategories(e,t){let n=await this.readCategories(e),s=new Map;if(!n)return s;let o=new Set(t);for(let i of n.fileCategories)o.has(i.path)&&s.set(i.path,i.categories);return s}async getFilesByDomain(e,t){let n=await this.readCategories(e);return n?n.domainIndex[t]||[]:[]}getIndexMeta(e,t){let s=V.getDb(e).prepare("SELECT data FROM index_meta WHERE key = ?").get(t);return s?JSON.parse(s.data):null}setIndexMeta(e,t,n){let s=V.getDb(e),o=JSON.stringify(n),i=new Date().toISOString();s.prepare("INSERT OR REPLACE INTO index_meta (key, data, updated_at) VALUES (?, ?, ?)").run(t,o,i)}},Ve=new pl});import mn from"node:fs/promises";import Me from"node:path";async function ml(r){let e=Date.now(),t={success:!1,migratedFiles:[],skippedFiles:[],errors:[],backupDir:null,duration:0};try{if(V.exists(r)&&V.hasDoc(r,"state"))return t.success=!0,t.duration=Date.now()-e,t;let n=P.getGlobalProjectPath(r),s=Me.join(n,"storage"),o=Me.join(n,"index"),i=Me.join(n,"memory");t.backupDir=await _C(s,o,i),V.getDb(r);for(let{filename:a,key:c}of fg){let u=Me.join(s,a),p=await bi(u);if(p===null){t.skippedFiles.push(a);continue}try{V.setDoc(r,c,p),NC(r,c,p),t.migratedFiles.push(a)}catch(m){t.errors.push({file:a,error:String(m)})}}for(let{filename:a,key:c}of OC){let u=Me.join(o,a),p=await bi(u);if(p===null){t.skippedFiles.push(`index/${a}`);continue}try{V.run(r,"INSERT OR REPLACE INTO index_meta (key, data, updated_at) VALUES (?, ?, ?)",c,JSON.stringify(p),new Date().toISOString()),WC(r,c,p),t.migratedFiles.push(`index/${a}`)}catch(m){t.errors.push({file:`index/${a}`,error:String(m)})}}return await VC(r,o,t),await qC(r,o,t),await KC(r,i,t),await XC(r,i,t),t.errors.length===0&&await YC(s,o,i,t),t.success=t.errors.length===0,t.duration=Date.now()-e,t}catch(n){return t.errors.push({file:"<migration>",error:String(n)}),t.duration=Date.now()-e,t}}async function _C(r,e,t){let n=Me.join(r,"backup");return await mn.mkdir(n,{recursive:!0}),await mn.mkdir(Me.join(n,"index"),{recursive:!0}),await mn.mkdir(Me.join(n,"memory"),{recursive:!0}),await dl(r,n,s=>s.endsWith(".json")||s.endsWith(".jsonl")),await dl(e,Me.join(n,"index")),await dl(t,Me.join(n,"memory")),n}async function dl(r,e,t){try{let n=await mn.readdir(r,{withFileTypes:!0});for(let s of n){if(!s.isFile()||t&&!t(s.name))continue;let o=Me.join(r,s.name),i=Me.join(e,s.name);await mn.copyFile(o,i)}}catch(n){if(!k(n))throw n}}function NC(r,e,t){switch(e){case"state":LC(r,t);break;case"queue":UC(r,t);break;case"ideas":HC(r,t);break;case"shipped":GC(r,t);break;case"metrics":zC(r,t);break;case"analysis":JC(r,t);break}}function LC(r,e){let t=V.getDb(r),n=t.prepare(`
514
- INSERT OR REPLACE INTO tasks
515
- (id, description, type, status, parent_description, branch, linear_id,
516
- linear_uuid, session_id, feature_id, started_at, completed_at,
517
- shipped_at, paused_at, pause_reason, pr_url, expected_value, data)
518
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
519
- `),s=t.prepare(`
520
- INSERT OR REPLACE INTO subtasks
521
- (id, task_id, description, status, domain, agent, sort_order,
522
- depends_on, started_at, completed_at, output, summary)
523
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
524
- `),o=l((a,c)=>{if(!a||!a.id)return;n.run(a.id,a.description??a.parentDescription??"",a.type??null,c??a.status??"unknown",a.parentDescription??null,a.branch??null,a.linearId??null,a.linearUuid??null,a.sessionId??null,a.featureId??null,a.startedAt??new Date().toISOString(),a.completedAt??null,a.shippedAt??null,a.pausedAt??null,a.pauseReason??null,a.prUrl??null,a.expectedValue?JSON.stringify(a.expectedValue):null,JSON.stringify(a));let u=a.subtasks;if(u&&Array.isArray(u))for(let p=0;p<u.length;p++){let m=u[p];s.run(m.id??`subtask-${p}`,a.id,m.description??"",m.status??"pending",m.domain??null,m.agent??null,p,m.dependsOn?JSON.stringify(m.dependsOn):null,m.startedAt??null,m.completedAt??null,m.output??null,m.summary?JSON.stringify(m.summary):null)}},"migrateTask");e.currentTask&&o(e.currentTask),e.previousTask&&o(e.previousTask);let i=e.pausedTasks;if(i&&Array.isArray(i))for(let a of i)o(a,"paused")}function UC(r,e){let t=e.tasks;if(!t||!Array.isArray(t))return;let s=V.getDb(r).prepare(`
525
- INSERT OR REPLACE INTO queue_tasks
526
- (id, description, type, priority, section, created_at, completed, completed_at,
527
- feature_id, feature_name)
528
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
529
- `);for(let o of t)s.run(o.id,o.description??"",o.type??null,o.priority??null,o.section??null,o.createdAt??new Date().toISOString(),o.completed?1:0,o.completedAt??null,o.featureId??null,o.featureName??null)}function HC(r,e){let t=e.ideas;if(!t||!Array.isArray(t))return;let s=V.getDb(r).prepare(`
530
- INSERT OR REPLACE INTO ideas
531
- (id, text, status, priority, tags, added_at, converted_to, details, data)
532
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
533
- `);for(let o of t)s.run(o.id,o.text??"",o.status??"pending",o.priority??"medium",o.tags?JSON.stringify(o.tags):null,o.addedAt??new Date().toISOString(),o.convertedTo??null,o.details??null,JSON.stringify(o))}function GC(r,e){let t=e.shipped;if(!t||!Array.isArray(t))return;let s=V.getDb(r).prepare(`
534
- INSERT OR REPLACE INTO shipped_features
535
- (id, name, shipped_at, version, description, type, duration, data)
536
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
537
- `);for(let o of t)s.run(o.id,o.name??"",o.shippedAt??new Date().toISOString(),o.version??"0.0.0",o.description??null,o.type??null,o.duration??null,JSON.stringify(o))}function zC(r,e){let t=e.dailyStats;if(!t||!Array.isArray(t))return;let s=V.getDb(r).prepare(`
538
- INSERT OR REPLACE INTO metrics_daily
539
- (date, tokens_saved, syncs, avg_compression_rate, total_duration)
540
- VALUES (?, ?, ?, ?, ?)
541
- `);for(let o of t)s.run(o.date,o.tokensSaved??0,o.syncs??0,o.avgCompressionRate??0,o.totalDuration??0)}function JC(r,e){let n=V.getDb(r).prepare(`
542
- INSERT OR REPLACE INTO analysis
543
- (id, status, commit_hash, signature, sealed_at, analyzed_at, data)
544
- VALUES (?, ?, ?, ?, ?, ?, ?)
545
- `),s=l((o,i)=>{o&&n.run(i,o.status??"unknown",o.commitHash??null,o.signature??null,o.sealedAt??null,o.analyzedAt??null,JSON.stringify(o))},"migrate");e.draft&&s(e.draft,"draft"),e.sealed&&s(e.sealed,"sealed")}function WC(r,e,t){e==="categories-cache"&&BC(r,t)}function BC(r,e){let t=e.fileCategories;if(!t||!Array.isArray(t))return;let s=V.getDb(r).prepare(`
546
- INSERT OR REPLACE INTO index_files
547
- (path, categories, domain, score, size, mtime, language)
548
- VALUES (?, ?, ?, COALESCE((SELECT score FROM index_files WHERE path = ?), 0), NULL, NULL, NULL)
549
- `);for(let o of t)s.run(o.path,o.categories?JSON.stringify(o.categories):null,o.primaryDomain??null,o.path)}async function VC(r,e,t){let n=Me.join(e,"checksums.json"),s=await bi(n);if(s===null){t.skippedFiles.push("index/checksums.json");return}try{let o=s.checksums;if(!o)return;let i=V.getDb(r),a=i.prepare("INSERT OR REPLACE INTO index_checksums (path, checksum) VALUES (?, ?)");i.transaction(()=>{for(let[c,u]of Object.entries(o))a.run(c,u)})(),t.migratedFiles.push("index/checksums.json")}catch(o){t.errors.push({file:"index/checksums.json",error:String(o)})}}async function qC(r,e,t){let n=Me.join(e,"file-scores.json"),s=await bi(n);if(s===null){t.skippedFiles.push("index/file-scores.json");return}try{let o=s.scores;if(!o||!Array.isArray(o))return;let i=V.getDb(r),a=i.prepare(`
550
- INSERT OR REPLACE INTO index_files
551
- (path, score, size, mtime, language, categories, domain)
552
- VALUES (?, ?, ?, ?, NULL,
553
- COALESCE((SELECT categories FROM index_files WHERE path = ?), NULL),
554
- COALESCE((SELECT domain FROM index_files WHERE path = ?), NULL))
555
- `);i.transaction(()=>{for(let c of o)a.run(c.path,c.score??0,c.size??null,c.mtime??null,c.path,c.path)})(),t.migratedFiles.push("index/file-scores.json")}catch(o){t.errors.push({file:"index/file-scores.json",error:String(o)})}}async function KC(r,e,t){let n=Me.join(e,"events.jsonl");try{let o=(await mn.readFile(n,"utf-8")).split(`
556
- `).filter(c=>c.trim());if(o.length===0){t.skippedFiles.push("memory/events.jsonl");return}let i=V.getDb(r),a=i.prepare("INSERT INTO events (type, task_id, data, timestamp) VALUES (?, ?, ?, ?)");i.transaction(()=>{for(let c of o)try{let u=JSON.parse(c),p=u.type??u.action??"unknown",m=u.taskId??u.task_id??null,d=u.timestamp??u.ts??new Date().toISOString();a.run(p,m,c,d)}catch{}})(),t.migratedFiles.push("memory/events.jsonl")}catch(s){k(s)?t.skippedFiles.push("memory/events.jsonl"):t.errors.push({file:"memory/events.jsonl",error:String(s)})}}async function XC(r,e,t){let n=Me.join(e,"learnings.jsonl");try{let o=(await mn.readFile(n,"utf-8")).split(`
557
- `).filter(c=>c.trim());if(o.length===0){t.skippedFiles.push("memory/learnings.jsonl");return}let i=V.getDb(r),a=i.prepare("INSERT OR REPLACE INTO memory (key, domain, value, confidence, updated_at) VALUES (?, ?, ?, ?, ?)");i.transaction(()=>{for(let c of o)try{let u=JSON.parse(c),p=`learning:${u.taskId??u.timestamp??Date.now()}`,m=u.tags,d=m&&m.length>0?m[0]:null;a.run(p,d,c,1,u.timestamp??new Date().toISOString())}catch{}})(),t.migratedFiles.push("memory/learnings.jsonl")}catch(s){k(s)?t.skippedFiles.push("memory/learnings.jsonl"):t.errors.push({file:"memory/learnings.jsonl",error:String(s)})}}async function YC(r,e,t,n){let s=l(async(i,a)=>{try{await mn.unlink(i)}catch(c){k(c)||n.errors.push({file:a,error:`cleanup: ${String(c)}`})}},"deleteFile");for(let{filename:i}of fg)await s(Me.join(r,i),`cleanup:${i}`);let o=["project-index.json","domains.json","categories-cache.json","checksums.json","file-scores.json"];for(let i of o)await s(Me.join(e,i),`cleanup:index/${i}`);await s(Me.join(t,"events.jsonl"),"cleanup:memory/events.jsonl"),await s(Me.join(t,"learnings.jsonl"),"cleanup:memory/learnings.jsonl")}async function bi(r){try{let e=await mn.readFile(r,"utf-8");return JSON.parse(e)}catch(e){if(k(e)||e instanceof SyntaxError)return null;throw e}}var fg,OC,gl=y(()=>{"use strict";ee();M();Yt();fg=[{filename:"state.json",key:"state"},{filename:"queue.json",key:"queue"},{filename:"ideas.json",key:"ideas"},{filename:"shipped.json",key:"shipped"},{filename:"metrics.json",key:"metrics"},{filename:"velocity.json",key:"velocity"},{filename:"analysis.json",key:"analysis"},{filename:"roadmap.json",key:"roadmap"},{filename:"session.json",key:"session"},{filename:"issues.json",key:"issues"}],OC=[{filename:"project-index.json",key:"project-index"},{filename:"domains.json",key:"domains"},{filename:"categories-cache.json",key:"categories-cache"}];l(ml,"migrateJsonToSqlite");l(_C,"createBackup");l(dl,"copyFiles");l(NC,"populateNormalized");l(LC,"populateTasksFromState");l(UC,"populateQueueTasks");l(HC,"populateIdeas");l(GC,"populateShippedFeatures");l(zC,"populateMetricsDaily");l(JC,"populateAnalysis");l(WC,"populateIndexTables");l(BC,"populateCategoriesIndex");l(VC,"migrateChecksums");l(qC,"migrateFileScores");l(KC,"migrateEventsJsonl");l(XC,"migrateLearningsJsonl");l(YC,"cleanupJsonFiles");l(bi,"readJsonSafe")});var fl,ot,hl=y(()=>{"use strict";_t();yi();ne();Rn();Qt();fl=class extends Le{static{l(this,"QueueStorage")}constructor(){super("queue.json",ag)}getDefault(){return{tasks:[],lastUpdated:""}}getMdFilename(){return"next.md"}getLayer(){return"core"}getEventType(e){return`queue.${e}d`}toMarkdown(e){let t=["# Priority Queue",""],n=e.tasks.filter(i=>i.section==="active"&&!i.completed),s=e.tasks.filter(i=>i.section==="backlog"&&!i.completed),o=e.tasks.filter(i=>i.section==="previously_active"&&!i.completed);return t.push("## Active Tasks"),n.length>0?n.forEach((i,a)=>{let c=i.completed?"[x]":"[ ]",u=i.priority!=="medium"?` [${i.priority.toUpperCase()}]`:"",p=i.agent?` @${i.agent}`:"",m=i.originFeature?` (from: ${i.originFeature})`:"",d=i.type==="bug"?" \u{1F41B}":"";t.push(`${a+1}. ${c}${d}${u} ${i.description}${p}${m}`)}):t.push("_No active tasks_"),t.push(""),o.length>0&&(t.push("## Previously Active"),o.forEach(i=>{t.push(`- [ ] ${i.description}`)}),t.push("")),t.push("## Backlog"),s.length>0?s.forEach(i=>{let a=i.priority!=="medium"?` [${i.priority.toUpperCase()}]`:"",c=i.type==="bug"?" \u{1F41B}":"";t.push(`- [ ]${c}${a} ${i.description}`)}):t.push("_No backlog items_"),t.push(""),t.join(`
558
- `)}async getTasks(e){return(await this.read(e)).tasks}async getActiveTasks(e){return(await this.read(e)).tasks.filter(n=>n.section==="active"&&!n.completed)}async getBacklog(e){return(await this.read(e)).tasks.filter(n=>n.section==="backlog"&&!n.completed)}async getNextTask(e){let t=await this.getActiveTasks(e);return this.sortTasks(t)[0]||null}async addTask(e,t){let n={...t,id:ye(),createdAt:b(),completed:!1};return await this.update(e,s=>({tasks:[...s.tasks,n],lastUpdated:b()})),await this.publishEvent(e,"queue.task_added",{taskId:n.id,description:n.description,priority:n.priority,section:n.section}),n}async addTasks(e,t){let n=b(),s=t.map(o=>({...o,id:ye(),createdAt:n,completed:!1}));return await this.update(e,o=>({tasks:[...o.tasks,...s],lastUpdated:n})),await this.publishEvent(e,"queue.tasks_added",{count:s.length,tasks:s.map(o=>({id:o.id,description:o.description}))}),s}async removeTask(e,t){await this.update(e,n=>({tasks:n.tasks.filter(s=>s.id!==t),lastUpdated:b()})),await this.publishEvent(e,"queue.task_removed",{taskId:t})}async completeTask(e,t){let n=null;if(await this.update(e,s=>({tasks:s.tasks.map(i=>i.id===t?(n={...i,completed:!0,completedAt:b()},n):i),lastUpdated:b()})),n){let s=n;await this.publishEvent(e,"queue.task_completed",{taskId:t,description:s.description,completedAt:s.completedAt})}return n}async moveToSection(e,t,n){await this.update(e,s=>({tasks:s.tasks.map(o=>o.id===t?{...o,section:n}:o),lastUpdated:b()}))}async setPriority(e,t,n){await this.update(e,s=>({tasks:s.tasks.map(o=>o.id===t?{...o,priority:n}:o),lastUpdated:b()}))}async clearCompleted(e){let n=(await this.read(e)).tasks.filter(s=>s.completed).length;return await this.update(e,s=>({tasks:s.tasks.filter(o=>!o.completed),lastUpdated:b()})),n}async removeStaleCompleted(e){let t=await this.read(e),n=bn(Nt.QUEUE_COMPLETED_DAYS),s=t.tasks.filter(i=>i.completed&&i.completedAt&&new Date(i.completedAt)<n);if(s.length===0)return 0;yt.archiveMany(e,s.map(i=>({entityType:"queue_task",entityId:i.id,entityData:i,summary:i.description,reason:"age"})));let o=new Set(s.map(i=>i.id));return await this.update(e,i=>({tasks:i.tasks.filter(a=>!o.has(a.id)),lastUpdated:b()})),await this.publishEvent(e,"queue.stale_removed",{count:s.length}),s.length}sortTasks(e){let t={critical:0,high:1,medium:2,low:3},n={active:0,previously_active:1,backlog:2};return[...e].sort((s,o)=>{let i=n[s.section]-n[o.section];if(i!==0)return i;let a=t[s.priority]-t[o.priority];return a!==0?a:new Date(s.createdAt).getTime()-new Date(o.createdAt).getTime()})}},ot=new fl});var yl,es,wl=y(()=>{"use strict";_t();Zc();ne();Rn();Qt();yl=class extends Le{static{l(this,"ShippedStorage")}constructor(){super("shipped.json",eg)}getDefault(){return{shipped:[],lastUpdated:""}}getMdFilename(){return"shipped.md"}getLayer(){return"progress"}getEventType(e){return`shipped.${e}d`}toMarkdown(e){let t=["# SHIPPED \u{1F680}",""];if(e.shipped.length===0)return t.push("_No features shipped yet. Use /p:ship to celebrate!_"),t.push(""),t.join(`
559
- `);let n=new Map;return e.shipped.forEach(o=>{let a=new Date(o.shippedAt).toLocaleDateString("en-US",{year:"numeric",month:"long"});n.has(a)||n.set(a,[]),n.get(a).push(o)}),Array.from(n.keys()).sort((o,i)=>{let a=new Date(n.get(o)[0].shippedAt);return new Date(n.get(i)[0].shippedAt).getTime()-a.getTime()}).forEach(o=>{t.push(`## ${o}`),t.push(""),n.get(o).sort((a,c)=>new Date(c.shippedAt).getTime()-new Date(a.shippedAt).getTime()).forEach(a=>{let c=gt(a.shippedAt),u=a.version?` v${a.version}`:"",p=a.duration?` (${a.duration})`:"";t.push(`- **${a.name}**${u}${p} - ${c}`),a.description&&t.push(` _${a.description}_`)}),t.push("")}),t.push("---"),t.push(""),t.push(`**Total shipped:** ${e.shipped.length}`),t.push(""),t.join(`
560
- `)}async getAll(e){return(await this.read(e)).shipped}async getRecent(e,t=5){return(await this.read(e)).shipped.sort((s,o)=>new Date(o.shippedAt).getTime()-new Date(s.shippedAt).getTime()).slice(0,t)}async addShipped(e,t){let n={...t,id:ye(),shippedAt:b()};return await this.update(e,s=>({shipped:[n,...s.shipped],lastUpdated:b()})),await this.publishEvent(e,"feature.shipped",{shipId:n.id,name:n.name,version:n.version,shippedAt:n.shippedAt}),n}async getByVersion(e,t){return(await this.read(e)).shipped.find(s=>s.version===t)}async getCount(e){return(await this.read(e)).shipped.length}async getByDateRange(e,t,n){return(await this.read(e)).shipped.filter(o=>{let i=new Date(o.shippedAt);return i>=t&&i<=n})}async getStats(e,t="month"){let n=new Date,s;switch(t){case"week":s=new Date(n.getTime()-10080*60*1e3);break;case"month":s=new Date(n.getFullYear(),n.getMonth(),1);break;case"year":s=new Date(n.getFullYear(),0,1);break}return{count:(await this.getByDateRange(e,s,n)).length,period:t}}async archiveOldShipped(e){let t=await this.read(e),n=bn(Nt.SHIPPED_RETENTION_DAYS),s=t.shipped.filter(i=>new Date(i.shippedAt)<n);if(s.length===0)return 0;yt.archiveMany(e,s.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)>=n).map(i=>i.id));return await this.update(e,i=>({shipped:i.shipped.filter(a=>o.has(a.id)),lastUpdated:b()})),await this.publishEvent(e,"shipped.archived",{count:s.length,oldestShippedAt:s[s.length-1]?.shippedAt}),s.length}},es=new yl});function hg(){return new kl}var kl,yg=y(()=>{"use strict";kl=class{static{l(this,"MarkdownBuilder")}lines=[];h1(e){return this.lines.push(`# ${e}`,""),this}h2(e){return this.lines.push(`## ${e}`,""),this}h3(e){return this.lines.push(`### ${e}`),this}h4(e){return this.lines.push(`#### ${e}`),this}p(e){return this.lines.push(e,""),this}bold(e){return this.lines.push(`**${e}**`),this}italic(e){return this.lines.push(`*${e}*`),this}code(e){return this.lines.push(`\`${e}\``),this}codeBlock(e,t=""){return this.lines.push(`\`\`\`${t}`,e,"```",""),this}li(e,t){let n=" ".repeat(t?.indent??0);return t?.checked!==void 0?this.lines.push(`${n}- [${t.checked?"x":" "}] ${e}`):this.lines.push(`${n}- ${e}`),this}oli(e,t){return this.lines.push(`${t}. ${e}`),this}list(e,t){for(let n of e)this.li(n,t);return this}orderedList(e){for(let t=0;t<e.length;t++)this.oli(e[t],t+1);return this}hr(){return this.lines.push("","---",""),this}blank(){return this.lines.push(""),this}raw(e){return this.lines.push(e),this}rawLines(e){return this.lines.push(...e),this}quote(e){return this.lines.push(`> ${e}`),this}link(e,t){return this.lines.push(`[${e}](${t})`),this}kv(e,t){return this.lines.push(`**${e}:** ${t}`),this}table(e,t){return this.lines.push(`| ${e.join(" | ")} |`),this.lines.push(`| ${e.map(()=>"---").join(" | ")} |`),t.forEach(n=>{this.lines.push(`| ${n.join(" | ")} |`)}),this.blank(),this}when(e,t){return e&&t(this),this}maybe(e,t){return e!=null&&t(this,e),this}each(e,t){for(let n=0;n<e.length;n++)t(this,e[n],n);return this}section(e,t,n){switch(t){case 1:this.h1(e);break;case 2:this.h2(e);break;case 3:this.h3(e);break;case 4:this.h4(e);break}return n(this),this}build(){return this.lines.join(`
561
- `)}get length(){return this.lines.length}};l(hg,"md")});var Br,Sl,qs,bl=y(()=>{"use strict";Br={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"}},Sl=class{static{l(this,"WorkflowStateMachine")}getCurrentState(e){let t=e?.currentTask;if(!t)return(e?.pausedTasks?.length||0)>0||e?.previousTask?.status==="paused"?"paused":"idle";switch((typeof t.status=="string"?t.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 t?"working":"idle"}}canTransition(e,t){let n=Br[e];if(n.transitions.includes(t))return{valid:!0};let s=n.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 Br[e]}getPrompt(e){return Br[e].prompt}getValidCommands(e){return Br[e].transitions}formatNextSteps(e){return Br[e].transitions.map(n=>{switch(n){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. ${n}`}})}},qs=new Sl});var Pl,le,Cl=y(()=>{"use strict";_t();yi();ne();yg();bl();Rn();Qt();Pl=class extends Le{static{l(this,"StateStorage")}constructor(){super("state.json",og)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],lastUpdated:""}}getMdFilename(){return"now.md"}getLayer(){return"core"}getEventType(e){return`state.${e}d`}toMarkdown(e){return hg().h1("NOW").when(!!e.currentTask,t=>{let n=e.currentTask;if(t.bold(n.description).blank().raw(`Started: ${gt(n.startedAt)}`).raw(`Session: ${n.sessionId}`).maybe(n.featureId,(s,o)=>s.raw(`Feature: ${o}`)),n.subtasks&&n.subtasks.length>0){t.blank().h2("Subtasks Progress").raw(`**Progress**: ${n.subtaskProgress?.completed||0}/${n.subtaskProgress?.total||0} (${n.subtaskProgress?.percentage||0}%)`).blank().raw("| # | Domain | Description | Status | Agent |").raw("|---|--------|-------------|--------|-------|"),n.subtasks.forEach((i,a)=>{let c=i.status==="completed"?"\u2705":i.status==="in_progress"?"\u25B6\uFE0F":i.status==="failed"?"\u274C":i.status==="skipped"?"\u23ED\uFE0F":i.status==="blocked"?"\u{1F6AB}":"\u23F3",u=a===n.currentSubtaskIndex?" **\u2190 Active**":"";t.raw(`| ${a+1} | ${i.domain} | ${i.description} | ${c} ${i.status}${u} | ${i.agent} |`)});let s=n.subtasks[n.currentSubtaskIndex||0];s&&s.status==="in_progress"&&(t.blank().h3("Current Subtask").raw(`**#${(n.currentSubtaskIndex||0)+1}**: ${s.description}`).raw(`**Agent**: ${s.agent}`).raw(`**Domain**: ${s.domain}`),s.dependsOn.length>0&&t.raw(`**Depends on**: ${s.dependsOn.join(", ")}`));let o=n.subtasks.filter(i=>i.status==="completed"&&i.summary);if(o.length>0){let i=o[o.length-1];i.summary&&t.blank().h3("Previous Subtask Output").raw(`**${i.summary.title}**`).raw(i.summary.description).maybe(i.summary.outputForNextAgent,(a,c)=>a.blank().raw(`**Available for next agent**: ${c}`))}}}).when(!e.currentTask,t=>{t.italic("No active task. Use /p:work to start.")}).when((e.pausedTasks?.length||0)>0||!!e.previousTask,t=>{let n=e.pausedTasks?.length?e.pausedTasks:e.previousTask?[e.previousTask]:[];n.length!==0&&(t.hr().h2(`Paused (${n.length})`),n.forEach((s,o)=>{t.raw(`${o+1}. **${s.description}**`).raw(` Paused: ${gt(s.pausedAt)}`),s.pauseReason&&t.raw(` Reason: ${s.pauseReason}`)}),t.blank().italic("Use /p:resume to continue"))}).when((e.taskHistory?.length||0)>0,t=>{let n=this.getTaskHistoryFromState(e);if(n.length===0)return;let s=e.currentTask?.type,o=s?n.filter(i=>i.classification===s).slice(0,3):n.slice(0,5);o.length!==0&&(t.hr().h2(s?`Recent ${s} tasks (${o.length})`:`Recent tasks (${o.length})`),o.forEach((i,a)=>{t.raw(`${a+1}. **${i.title}** (${i.classification})`).raw(` Completed: ${gt(i.completedAt)} | ${i.subtaskCount} subtask${i.subtaskCount>1?"s":""}`).raw(` Outcome: ${i.outcome}`),i.linearId&&t.raw(` Linear: ${i.linearId}`),i.feedback?.patternsDiscovered?.length&&t.raw(` Patterns: ${i.feedback.patternsDiscovered.join(", ")}`),i.feedback?.issuesEncountered?.length&&t.raw(` Gotchas: ${i.feedback.issuesEncountered.join(", ")}`)}),t.blank().italic("Task history helps identify patterns and improve decisions"))}).blank().build()}validateTransition(e,t){let n=qs.getCurrentState(e),s=qs.canTransition(n,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 n=await this.read(e);this.validateTransition(n,"task");let s={...t,startedAt:b()};return await this.update(e,o=>({...o,currentTask:s,lastUpdated:b()})),await this.publishEvent(e,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId}),s}async updateCurrentTask(e,t){let n=await this.read(e);if(!n.currentTask)return null;let s={...n.currentTask,...t};return await this.update(e,o=>({...o,currentTask:s,lastUpdated:b()})),s}async completeTask(e,t){let n=await this.read(e),s=n.currentTask;if(!s)return null;this.validateTransition(n,"done");let o=b(),i=this.createTaskHistoryEntry(s,o,t),a=this.getTaskHistoryFromState(n),c=[i,...a].slice(0,this.maxTaskHistory);return await this.update(e,()=>({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,n){let s=e,o=(e.subtasks||[]).filter(c=>c.status==="completed"&&c.summary).map(c=>c.summary),i=o.length>0?o.map(c=>c.title).join(", "):"Task completed",a={taskId:e.id,title:s.parentDescription||e.description,classification:s.type||"improvement",startedAt:e.startedAt,completedAt:t,subtaskCount:e.subtasks?.length||0,subtaskSummaries:o,outcome:i,branchName:s.branch||"unknown",linearId:e.linearId,linearUuid:e.linearUuid,prUrl:s.prUrl};return n&&(a.feedback=n),a}maxPausedTasks=5;maxTaskHistory=20;stalenessThresholdDays=30;async pauseTask(e,t){let n=await this.read(e);if(!n.currentTask)return null;this.validateTransition(n,"pause");let s={id:n.currentTask.id,description:n.currentTask.description,status:"paused",startedAt:n.currentTask.startedAt,pausedAt:b(),pauseReason:t},o=this.getPausedTasksFromState(n),i=[s,...o].slice(0,this.maxPausedTasks);return await this.update(e,()=>({currentTask:null,previousTask:null,pausedTasks:i,lastUpdated:b()})),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 n=await this.read(e),s=this.getPausedTasksFromState(n);if(s.length===0)return null;this.validateTransition(n,"resume");let o=0;if(t&&(o=s.findIndex(u=>u.id===t),o===-1))return null;let i=s[o],a=s.filter((u,p)=>p!==o),c={id:i.id,description:i.description,startedAt:b(),sessionId:ye()};return await this.update(e,()=>({currentTask:c,previousTask:null,pausedTasks:a,lastUpdated:b()})),await this.publishEvent(e,"task.resumed",{taskId:c.id,description:c.description,resumedAt:c.startedAt,remainingPaused:a.length}),c}getPausedTasksFromState(e){let t=e.pausedTasks||[];return e.previousTask&&e.previousTask.status==="paused"&&!t.some(s=>s.id===e.previousTask.id)?[e.previousTask,...t]:t}getTaskHistoryFromState(e){return e.taskHistory||[]}async getStalePausedTasks(e){let t=await this.read(e),n=this.getPausedTasksFromState(t),s=Date.now()-this.stalenessThresholdDays*24*60*60*1e3;return n.filter(o=>new Date(o.pausedAt).getTime()<s)}async archiveStalePausedTasks(e){let t=await this.read(e),n=this.getPausedTasksFromState(t),s=Date.now()-this.stalenessThresholdDays*24*60*60*1e3,o=n.filter(a=>new Date(a.pausedAt).getTime()<s),i=n.filter(a=>new Date(a.pausedAt).getTime()>=s);if(o.length===0)return[];yt.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:b()}));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:[],lastUpdated:b()}))}async hasTask(e){let t=await this.read(e),n=this.getPausedTasksFromState(t);return t.currentTask!==null||n.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 n=await this.read(e);return this.getTaskHistoryFromState(n).filter(o=>o.classification===t)}async getAggregatedFeedback(e){let n=(await this.getTaskHistory(e)).filter(d=>d.feedback),s=[],o=[],i=[],a=[];for(let d of n){let g=d.feedback;g.stackConfirmed&&s.push(...g.stackConfirmed),g.patternsDiscovered&&o.push(...g.patternsDiscovered),g.agentAccuracy&&i.push(...g.agentAccuracy),g.issuesEncountered&&a.push(...g.issuesEncountered)}let c=[...new Set(s)],u=[...new Set(o)],p=new Map;for(let d of a)p.set(d,(p.get(d)||0)+1);let m=[...p.entries()].filter(([d,g])=>g>=2).map(([d])=>d);return{stackConfirmed:c,patternsDiscovered:u,agentAccuracy:i,issuesEncountered:[...new Set(a)],knownGotchas:m}}async createSubtasks(e,t){let n=await this.read(e);if(!n.currentTask)return;let s=t.map((o,i)=>({...o,status:i===0?"in_progress":"pending",startedAt:i===0?b():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:b()})),await this.publishEvent(e,"subtasks.created",{taskId:n.currentTask.id,subtaskCount:s.length,subtasks:s.map(o=>({id:o.id,description:o.description,domain:o.domain}))})}async completeSubtask(e,t){let n=sg.safeParse(t);if(!n.success){let f=n.error.issues.map(S=>`${S.path.join(".")}: ${S.message}`);throw new Error(`Subtask completion requires handoff data:
562
- ${f.join(`
563
- `)}`)}let{output:s,summary:o}=n.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:b(),output:s,summary:o};let p=u.filter(f=>f.status==="completed").length,m=u.length,d=Math.round(p/m*100),g=a+1;return g<u.length&&(u[g]={...u[g],status:"in_progress",startedAt:b()}),await this.update(e,f=>({...f,currentTask:{...f.currentTask,subtasks:u,currentSubtaskIndex:g<m?g:a,subtaskProgress:{completed:p,total:m,percentage:d}},lastUpdated:b()})),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:p,total:m,percentage:d}}),g<m?u[g]:null}async getCurrentSubtask(e){let t=await this.read(e);if(!t.currentTask?.subtasks)return null;let n=t.currentTask.currentSubtaskIndex||0;return t.currentTask.subtasks[n]||null}async getNextSubtask(e){let t=await this.read(e);if(!t.currentTask?.subtasks)return null;let n=(t.currentTask.currentSubtaskIndex||0)+1;return t.currentTask.subtasks[n]||null}async getPreviousSubtask(e){let t=await this.read(e);if(!t.currentTask?.subtasks)return null;let n=(t.currentTask.currentSubtaskIndex||0)-1;return n<0?null:t.currentTask.subtasks[n]||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(n=>n.status==="completed"||n.status==="failed"||n.status==="skipped"):!0}async failSubtask(e,t){let n=await this.read(e);if(!n.currentTask?.subtasks)return null;let s=n.currentTask.currentSubtaskIndex||0,o=n.currentTask.subtasks[s];if(!o)return null;let i=[...n.currentTask.subtasks];i[s]={...o,status:"failed",completedAt:b(),output:`Failed: ${t}`};let a=s+1,c=i.length;a<c&&(i[a]={...i[a],status:"in_progress",startedAt:b()});let u=i.filter(m=>m.status==="completed"||m.status==="failed"||m.status==="skipped").length,p=Math.round(u/c*100);return await this.update(e,m=>({...m,currentTask:{...m.currentTask,subtasks:i,currentSubtaskIndex:a<c?a:s,subtaskProgress:{completed:u,total:c,percentage:p}},lastUpdated:b()})),await this.publishEvent(e,"subtask.failed",{taskId:n.currentTask.id,subtaskId:o.id,description:o.description,error:t}),a<c?i[a]:null}async skipSubtask(e,t){let n=await this.read(e);if(!n.currentTask?.subtasks)return null;let s=n.currentTask.currentSubtaskIndex||0,o=n.currentTask.subtasks[s];if(!o)return null;let i=[...n.currentTask.subtasks];i[s]={...o,status:"skipped",completedAt:b(),output:`Skipped: ${t}`,skipReason:t};let a=s+1,c=i.length;a<c&&(i[a]={...i[a],status:"in_progress",startedAt:b()});let u=i.filter(m=>m.status==="completed"||m.status==="failed"||m.status==="skipped").length,p=Math.round(u/c*100);return await this.update(e,m=>({...m,currentTask:{...m.currentTask,subtasks:i,currentSubtaskIndex:a<c?a:s,subtaskProgress:{completed:u,total:c,percentage:p}},lastUpdated:b()})),await this.publishEvent(e,"subtask.skipped",{taskId:n.currentTask.id,subtaskId:o.id,description:o.description,reason:t}),a<c?i[a]:null}async blockSubtask(e,t){let n=await this.read(e);if(!n.currentTask?.subtasks)return null;let s=n.currentTask.currentSubtaskIndex||0,o=n.currentTask.subtasks[s];if(!o)return null;let i=[...n.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:b()}),await this.update(e,u=>({...u,currentTask:{...u.currentTask,subtasks:i,currentSubtaskIndex:a<c?a:s},lastUpdated:b()})),await this.publishEvent(e,"subtask.blocked",{taskId:n.currentTask.id,subtaskId:o.id,description:o.description,blocker:t}),a<c?i[a]:null}},le=new Pl});import gn from"node:fs/promises";import QC from"node:os";import ts from"node:path";function xl(r){return new vl(r)}var vl,wg=y(()=>{"use strict";dc();M();vl=class{static{l(this,"FileStorage")}projectId;basePath;constructor(e){this.projectId=e,this.basePath=ts.join(QC.homedir(),".prjct-cli/projects",e,"data")}pathToFile(e){if(e.length===1)return ts.join(this.basePath,`${e[0]}.json`);let t=`${e[0]}s`,s=`${e.slice(1).join("/")}.json`;return ts.join(this.basePath,t,s)}async write(e,t){let n=this.pathToFile(e);await gn.mkdir(ts.dirname(n),{recursive:!0}),await gn.writeFile(n,JSON.stringify(t,null,2),"utf-8"),Us.publish({type:Qo(e,"write"),path:e,data:t,timestamp:new Date().toISOString(),projectId:this.projectId}),e.length===2&&await this.updateIndex(e[0],e[1],"add")}async read(e){let t=this.pathToFile(e);try{let n=await gn.readFile(t,"utf-8");return JSON.parse(n)}catch(n){if(k(n)||n instanceof SyntaxError)return null;throw n}}async list(e){let t=ts.join(this.basePath,`${e[0]}s`);try{return(await gn.readdir(t)).filter(s=>s.endsWith(".json")&&s!=="index.json").map(s=>[...e,s.replace(".json","")])}catch(n){if(k(n))return[];throw n}}async delete(e){let t=this.pathToFile(e);try{await gn.unlink(t),Us.publish({type:Qo(e,"delete"),path:e,data:null,timestamp:new Date().toISOString(),projectId:this.projectId}),e.length===2&&await this.updateIndex(e[0],e[1],"remove")}catch(n){if(!k(n))throw n}}async exists(e){let t=this.pathToFile(e);try{return await gn.access(t),!0}catch(n){if(k(n))return!1;throw n}}async updateIndex(e,t,n){let s=ts.join(this.basePath,`${e}s`,"index.json"),o={ids:[],updatedAt:""};try{let i=await gn.readFile(s,"utf-8");o=JSON.parse(i)}catch(i){if(!k(i)&&!(i instanceof SyntaxError))throw i}n==="add"&&!o.ids.includes(t)?o.ids.push(t):n==="remove"&&(o.ids=o.ids.filter(i=>i!==t)),o.updatedAt=new Date().toISOString(),await gn.mkdir(ts.dirname(s),{recursive:!0}),await gn.writeFile(s,JSON.stringify(o,null,2),"utf-8")}};l(xl,"getStorage")});function ZC(r){switch(r){case"improving":return"\u2191";case"declining":return"\u2193";default:return"\u2192"}}var Tl,El,jl=y(()=>{"use strict";Bs();Qt();Tl=class extends Le{static{l(this,"VelocityStorage")}constructor(){super("velocity.json")}getDefault(){return{metrics:lg,lastUpdated:""}}getMdFilename(){return"velocity.md"}getLayer(){return"progress"}getEventType(e){return`velocity.${e}d`}toMarkdown(e){let{metrics:t}=e,n=["# Velocity",""];if(t.sprints.length===0)return n.push("_No velocity data yet. Complete tasks with estimates to build velocity history._"),n.push(""),n.join(`
564
- `);n.push(`**Average**: ${t.averageVelocity} pts/sprint`),n.push(`**Trend**: ${ZC(t.velocityTrend)} ${t.velocityTrend}`),n.push(`**Estimation Accuracy**: ${t.estimationAccuracy}%`),n.push(""),n.push("## Sprint History"),n.push(""),n.push("| Sprint | Points | Tasks | Accuracy | Variance |"),n.push("|--------|--------|-------|----------|----------|");let s=t.sprints.slice(-6);for(let o of s)n.push(`| ${o.sprintNumber} | ${o.pointsCompleted} | ${o.tasksCompleted} | ${o.estimationAccuracy}% | ${o.avgVariance>0?"+":""}${o.avgVariance}% |`);if(n.push(""),t.underEstimated.length>0||t.overEstimated.length>0){n.push("## Estimation Patterns"),n.push("");for(let o of t.underEstimated)n.push(`- \u26A0 **${o.category}**: underestimated by avg ${o.avgVariance}% (${o.taskCount} tasks)`);for(let o of t.overEstimated)n.push(`- \u2713 **${o.category}**: overestimated by avg ${o.avgVariance}% (${o.taskCount} tasks)`);n.push("")}return n.join(`
565
- `)}async saveMetrics(e,t){await this.write(e,{metrics:t,lastUpdated:t.lastUpdated}),await this.publishEntityEvent(e,"velocity","updated",{averageVelocity:t.averageVelocity,trend:t.velocityTrend,sprintCount:t.sprints.length})}async getMetrics(e){return(await this.read(e)).metrics}};l(ZC,"formatTrendIcon");El=new Tl});var sn=y(()=>{"use strict";ki();Rn();Yt();ul();Wr();Ir();gl();hl();wl();Cl();wg();Qt();jl()});import Al from"node:path";var tv,nv,Pi,sv,it,ns=y(()=>{"use strict";ee();_t();me();tv="outcomes",nv="outcomes.jsonl",Pi=class{static{l(this,"OutcomeRecorder")}getOutcomesDir(e){let t=P.getGlobalProjectPath(e);return Al.join(t,tv)}getOutcomesPath(e){return Al.join(this.getOutcomesDir(e),nv)}async record(e,t){let n={...t,id:ye()},s=this.getOutcomesPath(e);return await dt(Al.dirname(s)),await Da(s,JSON.stringify(n)),n}async getAll(e){let t=this.getOutcomesPath(e);if(!await C(t))return[];let n=await ws(t);return n.trim()?n.trim().split(`
566
- `).filter(s=>s.trim()).map(s=>JSON.parse(s)):[]}async filter(e,t){return(await this.getAll(e)).filter(s=>{if(t.sessionId&&s.sessionId!==t.sessionId||t.command&&s.command!==t.command||t.agent&&s.agentUsed!==t.agent||t.fromDate&&s.startedAt<t.fromDate||t.toDate&&s.completedAt>t.toDate||t.minQuality&&s.qualityScore<t.minQuality)return!1;if(t.tags&&t.tags.length>0){let o=s.tags||[];if(!t.tags.some(i=>o.includes(i)))return!1}return!0})}async getRecent(e,t=10){return(await this.getAll(e)).slice(-t)}async getByCommand(e,t){return this.filter(e,{command:t})}async getByAgent(e,t){return this.filter(e,{agent:t})}async getEstimateAccuracy(e){let t=await this.getAll(e);if(t.length===0)return 0;let n=t.filter(s=>{if(!s.variance)return!1;let o=this.parseVariance(s.variance),i=this.parseDuration(s.estimatedDuration);return i===0?!1:Math.abs(o)/i<=.2});return Math.round(n.length/t.length*100)}parseVariance(e){let t=e.match(/^([+-])(\d+)([mh])$/);if(!t)return 0;let n=t[1]==="-"?-1:1,s=parseInt(t[2],10),o=t[3];return n*(o==="h"?s*60:s)}parseDuration(e){let t=0,n=e.match(/(\d+)h/);n&&(t+=parseInt(n[1],10)*60);let s=e.match(/(\d+)m/);return s&&(t+=parseInt(s[1],10)),t}},sv=new Pi,it=sv});import{createHash as rv}from"node:crypto";import bg from"node:fs/promises";import Pg from"node:path";function kg(r){return rv("sha256").update(r.toLowerCase().trim()).digest("hex").slice(0,16)}async function Sg(r){try{let e=Pg.join(r,"storage","classification-cache.json"),t=await bg.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return k(e)?Bc:(console.warn("[classifier] Failed to load cache:",w(e)),Bc)}}async function Il(r,e){try{let t=Pg.join(r,"storage","classification-cache.json");await bg.writeFile(t,JSON.stringify(e,null,2))}catch(t){console.warn("[classifier] Failed to save cache:",w(t))}}function iv(r,e,t){let n=r.entries[e];return!n||n.projectId!==t||Date.now()-new Date(n.classifiedAt).getTime()>ov?null:n.classification}function av(r,e){return r.confirmedPatterns.find(n=>n.descriptionHash===e)?.classification??null}async function cv(r,e){let t=process.env.ANTHROPIC_API_KEY;if(!t)return null;let n=Cg(e),s=Kc("classification")||"",o=`Classify this software engineering task into a domain.
567
-
568
- Task: "${r}"
569
-
570
- Available domains in this project: ${n.join(", ")}
571
- Available agents: ${e.agents.join(", ")||"none"}
572
- Stack: ${e.stack?.language||"unknown"} / ${e.stack?.framework||"unknown"}
573
-
574
- ${s}`;try{let i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:"claude-haiku-4-5-20251001",max_tokens:200,messages:[{role:"user",content:o}]})});if(!i.ok)return null;let c=(await i.json()).content?.[0]?.text;if(!c)return null;let u=JSON.parse(c),p=In.safeParse(u);return p.success?p.data:{primaryDomain:n.includes(u.primaryDomain)?u.primaryDomain:"general",secondaryDomains:(u.secondaryDomains||[]).filter(m=>n.includes(m)),confidence:Math.min(1,Math.max(0,u.confidence||.5)),filePatterns:Array.isArray(u.filePatterns)?u.filePatterns:[],relevantAgents:Array.isArray(u.relevantAgents)?u.relevantAgents:[]}}catch{return null}}function uv(r,e){let t=Cg(e),n=new Map;for(let[d,g]of Object.entries(lv)){if(d==="general"||!t.includes(d))continue;let f=0;for(let S of g)r.match(new RegExp(S,"gi"))&&(f+=S.source.includes("\\s")?3:1);f>0&&n.set(d,f)}if(n.size===0)return Im;let s=Array.from(n.entries()).sort((d,g)=>g[1]-d[1]),o=s[0][0],i=s[0][1],a=s.slice(1,3).map(([d])=>d),c=s.reduce((d,[,g])=>d+g,0),u=Math.min(.85,i/c+.2),p=pv(o),m=e.agents.filter(d=>d===o||d.includes(o)||o.includes(d.replace(".md","")));return{primaryDomain:o,secondaryDomains:a,confidence:u,filePatterns:p,relevantAgents:m}}function Cg(r){let e=[];return r.domains.hasFrontend&&e.push("frontend"),r.domains.hasBackend&&e.push("backend"),r.domains.hasDatabase&&e.push("database"),r.domains.hasTesting&&e.push("testing"),r.domains.hasDocker&&e.push("devops"),e.push("docs","uxui","general"),e}function pv(r){let e={frontend:["src/components/**","src/pages/**","src/hooks/**","**/*.tsx","**/*.jsx"],backend:["src/api/**","src/routes/**","src/services/**","src/handlers/**"],database:["src/models/**","src/schemas/**","**/*.sql","prisma/**"],devops:[".github/**","docker/**","deploy/**","infra/**","**/*.yml","**/*.yaml"],testing:["**/*.test.*","**/*.spec.*","tests/**","__tests__/**","e2e/**"],docs:["docs/**","**/*.md","**/*.mdx"],uxui:["src/components/**","src/styles/**","**/*.css"],general:["**/*.ts","**/*.js"]};return e[r]||e.general}var ov,lv,Dl,dv,vg,xg=y(()=>{"use strict";Gr();gi();M();ov=3600*1e3;l(kg,"hashDescription");l(Sg,"loadCache");l(Il,"saveCache");l(iv,"lookupCache");l(av,"lookupPatterns");l(cv,"classifyWithLLM");lv={frontend:[/\bui\b/i,/\bcomponents?\b/i,/\breact\b/i,/\bvue\b/i,/\bangular\b/i,/\bsvelte\b/i,/\bnext\.?js\b/i,/\bnuxt\b/i,/\bcss\b/i,/\bscss\b/i,/\bstyles?\b/i,/\bbuttons?\b/i,/\bforms?\b/i,/\bmodals?\b/i,/\blayout\b/i,/\bresponsive\b/i,/\banimation\b/i,/\bdom\b/i,/\bhtml\b/i,/\bfrontend\b/i,/\bclient[- ]side\b/i,/\bbrowser\b/i,/\bjsx\b/i,/\btsx\b/i,/\bhooks?\b/i,/\bredux\b/i,/\bzustand\b/i,/\btailwind\b/i,/\bdashboard\b/i,/\bpage\b/i,/\bnavigation\b/i,/\bsidebar\b/i,/\bheader\b/i,/\bfooter\b/i,/\bwidget\b/i,/\btooltip\b/i,/\bdropdown\b/i,/\bcarousel\b/i,/\bprofile\s+page\b/i,/\bdisplay\b/i],backend:[/\bapi\b/i,/\bendpoints?\b/i,/\bserver\b/i,/\broutes?\b/i,/\bhandlers?\b/i,/\bcontrollers?\b/i,/\bservices?\b/i,/\bmiddleware\b/i,/\bauth\b/i,/\bauthentication\b/i,/\bauthorization\b/i,/\bjwt\b/i,/\boauth\b/i,/\brest\b/i,/\bgraphql\b/i,/\btrpc\b/i,/\bexpress\b/i,/\bfastify\b/i,/\bhono\b/i,/\bnest\.?js\b/i,/\bvalidation\b/i,/\bbusiness\s+logic\b/i,/\bcron\b/i,/\bwebhook\b/i,/\bworker\b/i,/\bqueue\b/i,/\bcache\b/i],database:[/\bdatabase\b/i,/\bdb\b/i,/\bsql\b/i,/\bquery\b/i,/\btables?\b/i,/\bschema\b/i,/\bmigrations?\b/i,/\bpostgres\b/i,/\bmysql\b/i,/\bsqlite\b/i,/\bmongo\b/i,/\bredis\b/i,/\bprisma\b/i,/\bdrizzle\b/i,/\borm\b/i,/\bentity\b/i,/\brepository\b/i,/\bdata\s+layer\b/i,/\bpersist\b/i,/\bindex(?:es|ing)?\b/i,/\bconnection\s+pool\b/i],devops:[/\bdocker\b/i,/\bkubernetes\b/i,/\bk8s\b/i,/\bci\b/i,/\bcd\b/i,/\bpipeline\b/i,/\bdeploy\b/i,/\bgithub\s+actions\b/i,/\bvercel\b/i,/\baws\b/i,/\bgcp\b/i,/\bazure\b/i,/\bterraform\b/i,/\bnginx\b/i,/\bcaddy\b/i,/\binfrastructure\b/i,/\bmonitoring\b/i,/\blogging\b/i,/\bcontainer\b/i,/\bhelm\b/i],testing:[/\btests?\b/i,/\bspec\b/i,/\bunit\s+tests?\b/i,/\bintegration\s+tests?\b/i,/\be2e\b/i,/\bjest\b/i,/\bvitest\b/i,/\bplaywright\b/i,/\bcypress\b/i,/\bmocha\b/i,/\bmocks?\b/i,/\bstubs?\b/i,/\bfixtures?\b/i,/\bcoverage\b/i,/\bassertions?\b/i],docs:[/\bdocument(?:ation)?\b/i,/\bdocs\b/i,/\breadme\b/i,/\bchangelog\b/i,/\bjsdoc\b/i,/\btutorial\b/i,/\bguide\b/i,/\bmarkdown\b/i],uxui:[/\bdesign\b/i,/\bux\b/i,/\buser\s+experience\b/i,/\baccessibility\b/i,/\ba11y\b/i,/\bwcag\b/i,/\bfigma\b/i,/\bprototype\b/i,/\bwireframe\b/i,/\busability\b/i],general:[]};l(uv,"classifyWithHeuristic");l(Cg,"buildAvailableDomains");l(pv,"getFilePatterns");Dl=class{static{l(this,"DomainClassifier")}async classify(e,t,n,s){let o=kg(e),i=await Sg(n),a=iv(i,o,t);if(a)return{classification:a,source:"cache"};let c=av(i,o);if(c)return{classification:c,source:"history"};let u=await cv(e,s);if(u)return i.entries[o]={classification:u,classifiedAt:new Date().toISOString(),source:"llm",descriptionHash:o,projectId:t},await Il(n,i),{classification:u,source:"llm"};let p=uv(e,s);return i.entries[o]={classification:p,classifiedAt:new Date().toISOString(),source:"heuristic",descriptionHash:o,projectId:t},await Il(n,i),{classification:p,source:"heuristic"}}async confirmClassification(e,t,n){let s=kg(e),o=await Sg(n);o.confirmedPatterns.some(i=>i.descriptionHash===s)||(o.confirmedPatterns.push({descriptionHash:s,classification:t,confirmedAt:new Date().toISOString(),taskDescription:e}),await Il(n,o))}},dv=new Dl,vg=dv});import{exec as mv}from"node:child_process";import Ks from"node:fs/promises";import gv from"node:os";import $n from"node:path";import{promisify as fv}from"node:util";var Tg,Eg,Rl,hv,Ci,$l=y(()=>{"use strict";il();Ye();ee();Bs();sn();fc();yc();ri();M();ns();xg();Yn();Tg=fv(mv),Eg=["database","backend","frontend","testing","devops"],Rl=class{static{l(this,"OrchestratorExecutor")}async execute(e,t,n){let s=await I.getProjectId(n),o=P.getGlobalProjectPath(s),i=await this.loadRepoAnalysis(o),{domains:a,primary:c}=await this.detectDomains(t,s,i),u=await this.loadAgents(a,s),p=await this.loadSkills(u),[m,d,g]=await Promise.all([this.gatherRealContext(t,n),this.loadSealedAnalysis(s),this.loadVelocityContext(s)]),f=this.shouldFragment(a,t),S=null;return f&&e==="task"&&(S=await this.createSubtasks(t,a,u,s)),{detectedDomains:a,primaryDomain:c,agents:u,skills:p,requiresFragmentation:f,subtasks:S,project:{id:s,ecosystem:i?.ecosystem||"unknown",conventions:i?.conventions||[]},realContext:m,sealedAnalysis:d,velocityContext:g}}async gatherRealContext(e,t){try{let[n,s,o]=await Promise.all([this.getGitState(t),Dr(e,t,{maxFiles:10,minScore:.15}),$r(t,{commits:10,maxFiles:10})]),i=s.files.slice(0,3),a=await Promise.all(i.map(async c=>{try{let u=await xn(c.path,t);if(u.signatures.length===0)return null;let p=u.signatures.map(m=>`${m.exported?"export ":""}${m.type} ${m.name}: ${m.signature}`).join(`
575
- `);return{path:c.path,content:p}}catch{return null}}));return{gitBranch:n.branch,gitStatus:n.status,relevantFiles:s.files.map(c=>({path:c.path,score:Math.round(c.score*100),reason:c.reasons.join(", ")})),recentFiles:o.hotFiles.slice(0,5).map(c=>({path:c.path,lastChanged:c.lastChanged,changes:c.changes})),signatures:a.filter(c=>c!==null)}}catch{return}}async getGitState(e){try{let[t,n]=await Promise.all([Tg("git branch --show-current",{cwd:e}),Tg("git status --porcelain",{cwd:e})]),s=t.stdout.trim()||"main",o=n.stdout.trim().split(`
576
- `).filter(Boolean),i=0,a=0,c=0;for(let m of o){let d=m.substring(0,2);d.startsWith("??")?a++:d[0]!==" "&&d[0]!=="?"?c++:i++}let u=[];c>0&&u.push(`${c} staged`),i>0&&u.push(`${i} modified`),a>0&&u.push(`${a} untracked`);let p=u.length>0?u.join(", "):"clean";return{branch:s,status:p}}catch{return{branch:"unknown",status:"git unavailable"}}}async loadSealedAnalysis(e){try{let t=await nn.getActive(e);return t?{languages:t.languages,frameworks:t.frameworks,packageManager:t.packageManager,sourceDir:t.sourceDir,testDir:t.testDir,fileCount:t.fileCount,patterns:t.patterns,antiPatterns:t.antiPatterns,status:t.status??"draft",commitHash:t.commitHash}:null}catch{return null}}async loadVelocityContext(e){try{let t=await it.getAll(e);if(t.length===0)return null;let n=wi(t,Dn);return n.sprints.length===0?null:dg(n)}catch{return null}}async loadRepoAnalysis(e){try{let t=$n.join(e,"analysis","repo-analysis.json"),n=await Ks.readFile(t,"utf-8");return JSON.parse(n)}catch(t){return k(t)||console.warn("Failed to load repo-analysis.json:",w(t)),null}}async detectDomains(e,t,n){let s=P.getGlobalProjectPath(t),o=await this.getAvailableAgentNames(s),i={hasFrontend:!1,hasBackend:!0,hasDatabase:!1,hasTesting:!1,hasDocker:!1};try{let m=$n.join(s,"storage","state.json"),d=await Ks.readFile(m,"utf-8"),g=JSON.parse(d);g.domains&&(i=g.domains)}catch{}let a={domains:i,agents:o,stack:n?{language:n.ecosystem}:void 0},{classification:c}=await vg.classify(e,t,s,a),p=[c.primaryDomain,...c.secondaryDomains].filter(m=>o.some(d=>d===m||d.includes(m)||m.includes(d.replace(".md",""))));return p.length===0?{domains:["general"],primary:"general"}:{domains:p,primary:p[0]}}async getAvailableAgentNames(e){try{let t=$n.join(e,"agents");return(await Ks.readdir(t)).filter(s=>s.endsWith(".md")).map(s=>s.replace(".md",""))}catch{return[]}}async loadAgents(e,t){let n=P.getGlobalProjectPath(t),s=$n.join(n,"agents"),o=e.map(async a=>{let c=[`${a}.md`,`${a}-agent.md`,`prjct-${a}.md`];for(let u of c){let p=$n.join(s,u);try{let m=await Ks.readFile(p,"utf-8"),{frontmatter:d,body:g}=this.parseAgentFile(m);return{name:u.replace(".md",""),domain:a,content:g,skills:d.skills||[],filePath:p,effort:d.effort,model:d.model}}catch{}}return null});return(await Promise.all(o)).filter(a=>a!==null)}parseAgentFile(e){let t=ci(e),n={...t.frontmatter};return typeof n.skills=="string"&&(n.skills=n.skills.split(",").map(s=>s.trim())),{frontmatter:n,body:t.content}}async loadSkills(e){let t=$n.join(gv.homedir(),".claude","skills"),n=new Map;for(let i of e)for(let a of i.skills){let c=n.get(a)||[];c.push(i.name),n.set(a,c)}let s=Array.from(n.keys()).map(async i=>{let a=$n.join(t,`${i}.md`),c=$n.join(t,i,"SKILL.md");try{let u=await Ks.readFile(c,"utf-8");return{name:i,content:u,filePath:c}}catch{try{let u=await Ks.readFile(a,"utf-8");return{name:i,content:u,filePath:a}}catch{let u=n.get(i)||[];return console.warn(`\u26A0 Skill "${i}" not installed (needed by: ${u.join(", ")}). Run \`prjct sync\` to auto-install.`),null}}});return(await Promise.all(s)).filter(i=>i!==null)}shouldFragment(e,t){if(e.length>=3)return!0;let n=["full stack","fullstack","end to end","e2e","complete feature","from database to ui","across layers"],s=t.toLowerCase();for(let i of n)if(s.includes(i))return!0;return t.split(/\s+/).length>30&&e.length>=2}async createSubtasks(e,t,n,s){let o=[...t].sort((a,c)=>{let u=Eg.indexOf(a),p=Eg.indexOf(c);return(u===-1?99:u)-(p===-1?99:p)}),i=o.map((a,c)=>{let u=n.find(d=>d.domain===a),p=u?`${u.name}.md`:`${a}.md`,m=o.slice(0,c).map((d,g)=>`subtask-${g+1}`);return{id:`subtask-${c+1}`,description:this.generateSubtaskDescription(e,a),domain:a,agent:p,status:c===0?"in_progress":"pending",dependsOn:m,order:c+1}});return await le.createSubtasks(s,i.map(a=>({id:a.id,description:a.description,domain:a.domain,agent:a.agent,dependsOn:a.dependsOn}))),i}generateSubtaskDescription(e,t){let s={database:"Set up data layer: schema, models, migrations",backend:"Implement API: routes, controllers, services, validation",frontend:"Build UI: components, forms, state management",testing:"Write tests: unit, integration, e2e",devops:"Configure deployment: CI/CD, environment, containers",uxui:"Design user experience: flows, accessibility, styling"}[t]||`Handle ${t} aspects`;return`[${t.toUpperCase()}] ${s} for: ${e.substring(0,80)}${e.length>80?"...":""}`}},hv=new Rl,Ci=hv});function yv(r,e){return{ship:{title:"Ship Confirmation",message:"Ready to commit and push changes?",details:[`Branch: ${e.branch||"current"}`,`Files: ${e.changedFiles?.length||0} changed`,`Commit: "${e.commitMessage||"No message"}"`],options:[{key:"y",label:"Yes, ship it",action:"approve"},{key:"n",label:"No, cancel",action:"reject"},{key:"e",label:"Edit message",action:"edit"}]},cleanup:{title:"Cleanup Confirmation",message:"This will delete files/code. Continue?",details:[`Files to delete: ${e.filesToDelete?.length||0}`,`Code to remove: ${e.linesOfCode||0} lines`],options:[{key:"y",label:"Yes, cleanup",action:"approve"},{key:"n",label:"No, cancel",action:"reject"},{key:"l",label:"List files first",action:"list"}]},git:{title:"Git Operation Confirmation",message:`Execute: ${e.operation||"git operation"}?`,details:e.warnings||[],options:[{key:"y",label:"Yes, execute",action:"approve"},{key:"n",label:"No, cancel",action:"reject"}]}}[r]||{title:"Confirmation Required",message:`Execute ${r}?`,options:[{key:"y",label:"Yes",action:"approve"},{key:"n",label:"No",action:"reject"}]}}var Ml,wv,Fe,jg=y(()=>{"use strict";_t();ne();Kt();Kt();l(yv,"generateApprovalPrompt");Ml=class{static{l(this,"PlanMode")}activePlans;constructor(){this.activePlans=new Map}requiresPlanning(e){return Qa.includes(e)}isDestructive(e){return Za.includes(e)}isToolAllowedInPlanning(e){return Lo.includes(e)}getAllowedTools(e,t){return e?t.filter(n=>Lo.includes(n)):t}startPlanning(e,t,n){let s={id:ye(),projectId:e,command:t,params:n,status:te.GATHERING,startedAt:b(),gatheredInfo:[],analysis:null,proposedPlan:null,userFeedback:null,approvedAt:null,executionStartedAt:null,completedAt:null,steps:[],currentStep:0};return this.activePlans.set(e,s),s}getActivePlan(e){return this.activePlans.get(e)||null}isInPlanningMode(e){let t=this.getActivePlan(e);return t?[te.GATHERING,te.ANALYZING,te.PROPOSING,te.PENDING_APPROVAL].includes(t.status):!1}recordGatheredInfo(e,t){let n=this.getActivePlan(e);n&&n.gatheredInfo.push({...t,gatheredAt:b()})}updateStatus(e,t){let n=this.getActivePlan(e);n&&(n.status=t,t===te.APPROVED?n.approvedAt=b():t===te.EXECUTING?n.executionStartedAt=b():(t===te.COMPLETED||t===te.ABORTED)&&(n.completedAt=b()))}setAnalysis(e,t){let n=this.getActivePlan(e);n&&(n.analysis=t,n.status=te.ANALYZING)}proposePlan(e,t){let n=this.getActivePlan(e);return n?(n.proposedPlan=t,n.status=te.PENDING_APPROVAL,this.formatPlanForApproval(n)):null}formatPlanForApproval(e){let t=e.proposedPlan;return{summary:t?.summary||`Plan for: ${e.command}`,approach:t?.approach,steps:t?.steps||[],risks:t?.risks||[],alternatives:t?.alternatives||[],estimatedTime:t?.estimatedTime,affectedFiles:t?.affectedFiles||[],requiresConfirmation:!0,planId:e.id}}approvePlan(e,t=null){let n=this.getActivePlan(e);return!n||n.status!==te.PENDING_APPROVAL?null:(n.userFeedback=t,n.status=te.APPROVED,n.approvedAt=b(),n.steps=(n.proposedPlan?.steps||[]).map((s,o)=>({index:o,description:typeof s=="string"?s:s.description||"",status:"pending",tool:typeof s=="string"?void 0:s.tool,args:typeof s=="string"?void 0:s.args})),{approved:!0,planId:n.id,steps:n.steps,message:`Plan approved. ${n.steps.length} steps to execute.`})}rejectPlan(e,t=null){let n=this.getActivePlan(e);return n?(n.status=te.REJECTED,n.userFeedback=t,n.completedAt=b(),this.activePlans.delete(e),{rejected:!0,planId:n.id,reason:t,message:"Plan rejected. No changes made."}):null}startExecution(e){let t=this.getActivePlan(e);return!t||t.status!==te.APPROVED?null:(t.status=te.EXECUTING,t.executionStartedAt=b(),t.currentStep=0,this.getNextStep(e))}getNextStep(e){let t=this.getActivePlan(e);if(!t||t.status!==te.EXECUTING)return null;let n=t.steps[t.currentStep];return n?{stepNumber:t.currentStep+1,totalSteps:t.steps.length,step:n,progress:Math.round(t.currentStep/t.steps.length*100)}:(this.completePlan(e),null)}completeStep(e,t={success:!0}){let n=this.getActivePlan(e);return!n||n.status!==te.EXECUTING?null:(n.steps[n.currentStep].status="completed",n.steps[n.currentStep].result=t,n.steps[n.currentStep].completedAt=b(),n.currentStep++,this.getNextStep(e))}failStep(e,t){let n=this.getActivePlan(e);return n?(n.steps[n.currentStep].status="failed",n.steps[n.currentStep].error=t,{failed:!0,step:n.currentStep+1,error:t,options:["retry","skip","abort"]}):null}completePlan(e){let t=this.getActivePlan(e);if(!t)return null;t.status=te.COMPLETED,t.completedAt=b();let n={planId:t.id,command:t.command,totalSteps:t.steps.length,completedSteps:t.steps.filter(s=>s.status==="completed").length,failedSteps:t.steps.filter(s=>s.status==="failed").length,duration:this._calculateDuration(t.executionStartedAt,t.completedAt)};return this.activePlans.delete(e),n}abortPlan(e,t="User requested"){let n=this.getActivePlan(e);if(!n)return null;n.status=te.ABORTED,n.completedAt=b(),n.abortReason=t;let s={aborted:!0,planId:n.id,reason:t,completedSteps:n.steps.filter(o=>o.status==="completed").length,totalSteps:n.steps.length};return this.activePlans.delete(e),s}generateApprovalPrompt(e,t){return yv(e,t)}formatStatus(e){let t=this.getActivePlan(e);if(!t)return"No active plan";let s=[`${{[te.GATHERING]:"\u{1F50D}",[te.ANALYZING]:"\u{1F9E0}",[te.PROPOSING]:"\u{1F4DD}",[te.PENDING_APPROVAL]:"\u23F3",[te.APPROVED]:"\u2705",[te.EXECUTING]:"\u26A1",[te.COMPLETED]:"\u{1F389}",[te.REJECTED]:"\u274C",[te.ABORTED]:"\u{1F6D1}"}[t.status]||"\u{1F4CB}"} Plan: ${t.command}`,`Status: ${t.status}`];if(t.status===te.EXECUTING){let o=Math.round(t.currentStep/t.steps.length*100);s.push(`Progress: ${t.currentStep}/${t.steps.length} (${o}%)`)}return s.join(`
577
- `)}_calculateDuration(e,t){if(!e||!t)return null;let n=new Date(t).getTime()-new Date(e).getTime(),s=Math.floor(n/1e3),o=Math.floor(s/60),i=Math.floor(o/60);return i>0?`${i}h ${o%60}m`:o>0?`${o}m ${s%60}s`:`${s}s`}},wv=new Ml,Fe=wv});import Tt from"chalk";import ss from"prompts";var Fl,Ag,Xs,Ig=y(()=>{"use strict";Xt();Fl=[{value:"web-app",title:"Web Application",description:"React, Vue, Angular, Next.js, etc."},{value:"api-backend",title:"API / Backend Service",description:"Express, Hono, FastAPI, etc."},{value:"fullstack",title:"Full-Stack (Monorepo)",description:"Frontend + Backend in one repo"},{value:"cli-tool",title:"CLI Tool",description:"Command-line application"},{value:"library",title:"Library / Package",description:"Reusable npm/pip/cargo package"},{value:"monorepo",title:"Monorepo (Multiple Projects)",description:"Turborepo, Nx, Lerna, etc."}],Ag=[{value:"claude",title:"Claude Code",description:"Anthropic's Claude in VS Code/CLI"},{value:"cursor",title:"Cursor",description:"AI-first code editor"},{value:"windsurf",title:"Windsurf",description:"Codeium's AI IDE"},{value:"copilot",title:"GitHub Copilot",description:"GitHub's AI pair programmer"},{value:"gemini",title:"Gemini CLI",description:"Google's Gemini in terminal"}],Xs=class{static{l(this,"OnboardingWizard")}projectPath;currentStep=0;totalSteps=5;aborted=!1;detectedType="unknown";confirmedType="unknown";selectedAgents=[];detectedStack={language:"Unknown",technologies:[]};confirmedStack={language:"Unknown",technologies:[]};preferences={verbosity:"normal",autoSync:!0,telemetry:!1};constructor(e=process.cwd()){this.projectPath=e,ss.override({})}async run(){this.printWelcome();let e=[{id:"project-type",title:"Project Type",run:l(()=>this.stepProjectType(),"run")},{id:"ai-agents",title:"AI Agents",run:l(()=>this.stepAIAgents(),"run")},{id:"stack",title:"Stack Confirmation",run:l(()=>this.stepStack(),"run")},{id:"preferences",title:"Preferences",run:l(()=>this.stepPreferences(),"run")},{id:"summary",title:"Summary",run:l(()=>this.stepSummary(),"run")}];for(let t of e)if(this.currentStep++,this.printStepHeader(t.title),!await t.run()||this.aborted)return this.buildResult(!0);return this.buildResult(!1)}async runNonInteractive(){return h.spin("Auto-detecting project configuration..."),this.detectedType=await this.detectProjectType(),this.confirmedType=this.detectedType,this.selectedAgents=["claude"],this.detectedStack=await this.detectStack(),this.confirmedStack=this.detectedStack,h.done("Configuration detected"),this.buildResult(!1)}async stepProjectType(){this.detectedType=await this.detectProjectType();let e=await ss({type:"select",name:"projectType",message:this.detectedType!=="unknown"?`Detected: ${this.getProjectTypeLabel(this.detectedType)}. Is this correct?`:"What type of project is this?",choices:Fl.map(t=>({title:t.title,description:t.description,value:t.value,selected:t.value===this.detectedType})),initial:Fl.findIndex(t=>t.value===this.detectedType)},{onCancel:l(()=>this.handleCancel(),"onCancel")});return this.aborted?!1:(this.confirmedType=e.projectType||this.detectedType,!0)}async stepAIAgents(){let e=await this.detectInstalledAgents(),t=await ss({type:"multiselect",name:"agents",message:"Which AI agents do you use?",choices:Ag.map(n=>({title:n.title,description:n.description,value:n.value,selected:e.includes(n.value)})),hint:"- Space to select, Enter to confirm",instructions:!1,min:1},{onCancel:l(()=>this.handleCancel(),"onCancel")});return this.aborted?!1:(this.selectedAgents=t.agents||["claude"],!0)}async stepStack(){this.detectedStack=await this.detectStack();let e=this.formatStackDisplay(this.detectedStack);console.log(Tt.dim(`
578
- Detected: ${e}
579
- `));let t=await ss({type:"confirm",name:"confirmed",message:"Is this stack correct?",initial:!0},{onCancel:l(()=>this.handleCancel(),"onCancel")});if(this.aborted)return!1;if(t.confirmed)this.confirmedStack=this.detectedStack;else{let n=await ss([{type:"text",name:"language",message:"Primary language:",initial:this.detectedStack.language},{type:"text",name:"framework",message:"Framework (optional):",initial:this.detectedStack.framework||""}],{onCancel:l(()=>this.handleCancel(),"onCancel")});if(this.aborted)return!1;this.confirmedStack={...this.detectedStack,language:n.language||this.detectedStack.language,framework:n.framework||void 0}}return!0}async stepPreferences(){let e=await ss([{type:"select",name:"verbosity",message:"Output verbosity:",choices:[{title:"Minimal",description:"Essential output only",value:"minimal"},{title:"Normal (Recommended)",description:"Balanced information",value:"normal"},{title:"Verbose",description:"Detailed logging",value:"verbose"}],initial:1},{type:"confirm",name:"autoSync",message:"Auto-sync context on file changes?",initial:!0}],{onCancel:l(()=>this.handleCancel(),"onCancel")});return this.aborted?!1:(this.preferences={verbosity:e.verbosity||"normal",autoSync:e.autoSync??!0,telemetry:!1},!0)}async stepSummary(){console.log(""),console.log(Tt.bold(" Configuration Summary")),console.log(Tt.dim(` ${"\u2500".repeat(40)}`)),console.log(` ${Tt.cyan("Project Type:")} ${this.getProjectTypeLabel(this.confirmedType)}`),console.log(` ${Tt.cyan("AI Agents:")} ${this.selectedAgents.map(t=>this.getAgentLabel(t)).join(", ")}`),console.log(` ${Tt.cyan("Stack:")} ${this.formatStackDisplay(this.confirmedStack)}`),console.log(` ${Tt.cyan("Verbosity:")} ${this.preferences.verbosity}`),console.log(` ${Tt.cyan("Auto-sync:")} ${this.preferences.autoSync?"Yes":"No"}`),console.log("");let e=await ss({type:"confirm",name:"proceed",message:"Generate configuration with these settings?",initial:!0},{onCancel:l(()=>this.handleCancel(),"onCancel")});return!(this.aborted||!e.proceed)}async detectProjectType(){let e=await import("node:fs/promises"),t=await import("node:path");try{let n=await e.readdir(this.projectPath);if(n.includes("turbo.json")||n.includes("lerna.json")||n.includes("nx.json"))return"monorepo";if(n.includes("package.json")){let s=t.join(this.projectPath,"package.json"),o=await e.readFile(s,"utf-8"),i=JSON.parse(o),a={...i.dependencies,...i.devDependencies};if(i.bin)return"cli-tool";if(i.main&&!a.react&&!a.vue&&!a.angular&&!a.express&&!a.hono)return"library";if((a.react||a.vue)&&(a.express||a.hono||a.fastify))return"fullstack";if(a.react||a.vue||a["@angular/core"]||a.next||a.nuxt)return"web-app";if(a.express||a.hono||a.fastify||a.koa||a.nestjs)return"api-backend"}return n.includes("pyproject.toml")||n.includes("setup.py")?n.some(o=>["main.py","app.py","server.py"].includes(o))?"api-backend":"library":n.includes("go.mod")?n.includes("main.go")?"cli-tool":"library":n.includes("Cargo.toml")?"cli-tool":"unknown"}catch{return"unknown"}}async detectInstalledAgents(){let e=await import("node:fs/promises"),t=await import("node:path"),n=await import("node:os"),s=[];try{await e.access(t.join(n.homedir(),".claude")),s.push("claude")}catch{}try{await e.access(t.join(this.projectPath,".cursorrules")),s.push("cursor")}catch{}try{await e.access(t.join(this.projectPath,".windsurfrules")),s.push("windsurf")}catch{}try{await e.access(t.join(this.projectPath,".github","copilot-instructions.md")),s.push("copilot")}catch{}try{await e.access(t.join(n.homedir(),".gemini")),s.push("gemini")}catch{}return s.length>0?s:["claude"]}async detectStack(){let e=await import("node:fs/promises"),t=await import("node:path"),n={language:"Unknown",technologies:[]};try{let s=await e.readdir(this.projectPath);if(s.includes("package.json")){let o=t.join(this.projectPath,"package.json"),i=await e.readFile(o,"utf-8"),a=JSON.parse(i),c={...a.dependencies,...a.devDependencies};n.language=c.typescript?"TypeScript":"JavaScript",c.next?n.framework="Next.js":c.nuxt?n.framework="Nuxt":c.react?n.framework="React":c.vue?n.framework="Vue":c["@angular/core"]?n.framework="Angular":c.express?n.framework="Express":c.hono?n.framework="Hono":c.fastify?n.framework="Fastify":(c.nestjs||c["@nestjs/core"])&&(n.framework="NestJS"),c.bun||c["@types/bun"]||a.engines?.bun?n.runtime="Bun":n.runtime="Node.js",s.includes("bun.lockb")?n.packageManager="Bun":s.includes("pnpm-lock.yaml")?n.packageManager="pnpm":s.includes("yarn.lock")?n.packageManager="Yarn":s.includes("package-lock.json")&&(n.packageManager="npm"),(c.prisma||c["@prisma/client"])&&n.technologies.push("Prisma"),(c.drizzle||c["drizzle-orm"])&&n.technologies.push("Drizzle"),c.tailwindcss&&n.technologies.push("Tailwind CSS"),c.zod&&n.technologies.push("Zod"),(c.trpc||c["@trpc/server"])&&n.technologies.push("tRPC")}else s.includes("pyproject.toml")||s.includes("requirements.txt")?n.language="Python":s.includes("go.mod")?n.language="Go":s.includes("Cargo.toml")?n.language="Rust":(s.includes("pom.xml")||s.includes("build.gradle"))&&(n.language="Java");return n}catch{return n}}printWelcome(){console.log(""),console.log(Tt.bold.cyan(" Welcome to prjct-cli!")),console.log(Tt.dim(" Let's set up your project in 60 seconds.")),console.log("")}printStepHeader(e){console.log(""),console.log(Tt.dim(` Step ${this.currentStep}/${this.totalSteps}: ${e}`)),console.log("")}handleCancel(){this.aborted=!0,console.log(Tt.yellow(`
580
- Setup cancelled. Run again anytime.
581
- `))}getProjectTypeLabel(e){return Fl.find(t=>t.value===e)?.title||"Unknown"}getAgentLabel(e){return Ag.find(t=>t.value===e)?.title||e}formatStackDisplay(e){let t=[e.language];return e.framework&&t.push(e.framework),e.runtime&&e.runtime!=="Node.js"&&t.push(e.runtime),e.technologies.length>0&&t.push(`+ ${e.technologies.slice(0,3).join(", ")}`),t.join(" / ")}buildResult(e){return{projectType:this.confirmedType,agents:this.selectedAgents,stack:this.confirmedStack,preferences:this.preferences,skipped:e}}getSelectedAgents(){return this.selectedAgents}getConfirmedStack(){return this.confirmedStack}getPreferences(){return this.preferences}}});var vi,kv,Ol,Dg=y(()=>{"use strict";ns();vi=class{static{l(this,"OutcomeAnalyzer")}async summarize(e){let t=await it.getAll(e);if(t.length===0)return{totalOutcomes:0,avgQualityScore:0,estimateAccuracy:0,topBlockers:[],topAgents:[],patternsDetected:[]};let n=t.reduce((m,d)=>m+d.qualityScore,0)/t.length,s=await it.getEstimateAccuracy(e),o=new Map;for(let m of t)for(let d of m.blockers||[])o.set(d,(o.get(d)||0)+1);let i=[...o.entries()].sort((m,d)=>d[1]-m[1]).slice(0,5).map(([m])=>m),c=(await this.getAgentMetrics(e)).sort((m,d)=>d.successRate-m.successRate).slice(0,3).map(m=>m.agent),p=(await this.detectPatterns(e)).map(m=>m.description);return{totalOutcomes:t.length,avgQualityScore:Math.round(n*10)/10,estimateAccuracy:s,topBlockers:i,topAgents:c,patternsDetected:p}}async getAgentMetrics(e){let t=await it.getAll(e),n=new Map;for(let o of t){let i=o.agentUsed||"unknown";n.has(i)||n.set(i,[]),n.get(i).push(o)}let s=[];for(let[o,i]of n){let a=i.length,c=i.filter(S=>S.completedAsPlanned),u=Math.round(c.length/a*100),p=i.reduce((S,E)=>S+E.qualityScore,0)/a,m=i.filter(S=>{if(!S.variance)return!1;let E=this.parseVariance(S.variance),x=this.parseDuration(S.estimatedDuration);return x===0?!1:Math.abs(E)/x<=.2}),d=Math.round(m.length/a*100),g=new Map;for(let S of i.filter(E=>E.completedAsPlanned))for(let E of S.tags||[])g.set(E,(g.get(E)||0)+1);let f=[...g.entries()].sort((S,E)=>E[1]-S[1]).slice(0,3).map(([S])=>S);s.push({agent:o,tasksCompleted:a,successRate:u,avgQualityScore:Math.round(p*10)/10,estimateAccuracy:d,bestFor:f})}return s}async detectPatterns(e){let t=await it.getAll(e),n=[];if(t.length<3)return n;let s=t.filter(c=>this.parseVariance(c.variance)>0);s.length/t.length>.6&&n.push({description:"Tasks consistently take longer than estimated",confidence:s.length/t.length,occurrences:s.length,suggestedAction:"Add 30% buffer to estimates"});let o=t.filter(c=>this.parseVariance(c.variance)<0);o.length/t.length>.6&&n.push({description:"Tasks consistently finish faster than estimated",confidence:o.length/t.length,occurrences:o.length,suggestedAction:"Reduce estimates by 20%"});let i=new Map;for(let c of t)for(let u of c.blockers||[])i.set(u,(i.get(u)||0)+1);for(let[c,u]of i)u>=3&&n.push({description:`Recurring blocker: ${c}`,confidence:u/t.length,occurrences:u,suggestedAction:`Address root cause of "${c}"`});let a=await this.getAgentMetrics(e);for(let c of a)c.tasksCompleted>=5&&c.successRate>90&&n.push({description:`${c.agent} has high success rate (${c.successRate}%)`,confidence:.9,occurrences:c.tasksCompleted,suggestedAction:`Prefer ${c.agent} for similar tasks`});return n.sort((c,u)=>u.confidence-c.confidence)}async suggestEstimate(e,t){let s=(await it.getAll(e)).filter(a=>a.tags?.includes(t));if(s.length<2)return null;let o=s.reduce((a,c)=>a+this.parseDuration(c.actualDuration),0),i=Math.round(o/s.length);if(i>=60){let a=Math.floor(i/60),c=i%60;return c>0?`${a}h ${c}m`:`${a}h`}return`${i}m`}async suggestAgent(e,t){let s=(await this.getAgentMetrics(e)).filter(o=>o.bestFor.includes(t));return s.length===0?null:s.sort((o,i)=>i.successRate-o.successRate)[0].agent}parseVariance(e){let t=e.match(/^([+-])(\d+)([mh])$/);if(!t)return 0;let n=t[1]==="-"?-1:1,s=parseInt(t[2],10),o=t[3];return n*(o==="h"?s*60:s)}parseDuration(e){let t=0,n=e.match(/(\d+)h/);n&&(t+=parseInt(n[1],10)*60);let s=e.match(/(\d+)m/);return s&&(t+=parseInt(s[1],10)),t}},kv=new vi,Ol=kv});var Vr,xi,_l,Nl=y(()=>{"use strict";Ls();ne();Vr=3,xi=class{static{l(this,"OutcomeMemoryLearner")}async learnFromTaskHistory(e,t,n){let s={patternsExtracted:0,patternsQualified:0,memoriesInjected:0,patternsSkipped:0,details:[]};if(t.length===0)return s;let o=[...this.extractFileCochangePatterns(t),...this.extractStackPatterns(t),...this.extractArchitecturePatterns(t),...this.extractGotchaPatterns(t)];s.patternsExtracted=o.length;for(let i of o)if(i.occurrences>=Vr){s.patternsQualified++;let a=await this.injectIntoMemory(e,i,n);a&&(s.memoriesInjected++,s.details.push({pattern:i.pattern,action:a.action,confidence:i.confidence}))}else s.patternsSkipped++,s.details.push({pattern:i.pattern,action:"skipped",confidence:i.confidence,reason:`${i.occurrences}/${Vr} occurrences needed`});return s}async learnFromOutcomes(e,t,n){let s={patternsExtracted:0,patternsQualified:0,memoriesInjected:0,patternsSkipped:0,details:[]};if(t.length===0)return s;let o=this.extractOutcomePatterns(t);s.patternsExtracted=o.length;for(let i of o)if(i.occurrences>=Vr){s.patternsQualified++;let a=await this.injectIntoMemory(e,i,n);a&&(s.memoriesInjected++,s.details.push({pattern:i.pattern,action:a.action,confidence:i.confidence}))}else s.patternsSkipped++,s.details.push({pattern:i.pattern,action:"skipped",confidence:i.confidence,reason:`${i.occurrences}/${Vr} occurrences needed`});return s}extractFileCochangePatterns(e){let t=new Map;for(let s of e){if(!s.subtaskSummaries)continue;let o=new Set;for(let a of s.subtaskSummaries)if(a.filesChanged)for(let c of a.filesChanged)o.add(c.path);let i=Array.from(o).sort();for(let a=0;a<i.length;a++)for(let c=a+1;c<i.length;c++){let u=`${i[a]}|${i[c]}`,p=t.get(u)||{count:0,tasks:[]};p.count++,p.tasks.push(s.taskId),t.set(u,p)}}let n=[];for(let[s,{count:o,tasks:i}]of t)if(o>=2){let[a,c]=s.split("|");n.push({pattern:`Files "${a}" and "${c}" frequently change together (${o} tasks)`,occurrences:o,confidence:this.calculateConfidence(o),category:"file_cochange",sourceTasks:i})}return n.sort((s,o)=>o.occurrences-s.occurrences)}extractStackPatterns(e){let t=new Map;for(let n of e)if(n.feedback?.stackConfirmed)for(let s of n.feedback.stackConfirmed){let o=t.get(s)||{count:0,tasks:[]};o.count++,o.tasks.push(n.taskId),t.set(s,o)}return Array.from(t.entries()).map(([n,{count:s,tasks:o}])=>({pattern:`Project uses ${n}`,occurrences:s,confidence:this.calculateConfidence(s),category:"tech_stack",sourceTasks:o}))}extractArchitecturePatterns(e){let t=new Map;for(let n of e)if(n.feedback?.patternsDiscovered)for(let s of n.feedback.patternsDiscovered){let o=t.get(s)||{count:0,tasks:[]};o.count++,o.tasks.push(n.taskId),t.set(s,o)}return Array.from(t.entries()).map(([n,{count:s,tasks:o}])=>({pattern:n,occurrences:s,confidence:this.calculateConfidence(s),category:"architecture",sourceTasks:o}))}extractGotchaPatterns(e){let t=new Map;for(let n of e)if(n.feedback?.issuesEncountered)for(let s of n.feedback.issuesEncountered){let o=t.get(s)||{count:0,tasks:[]};o.count++,o.tasks.push(n.taskId),t.set(s,o)}return Array.from(t.entries()).filter(([n,{count:s}])=>s>=2).map(([n,{count:s,tasks:o}])=>({pattern:`Known gotcha: ${n}`,occurrences:s,confidence:this.calculateConfidence(s),category:"gotcha",sourceTasks:o}))}extractOutcomePatterns(e){let t=[],n=new Map,s=new Map;for(let i of e){for(let a of i.learnings.whatWorked){let c=n.get(a)||{count:0,ids:[]};c.count++,c.ids.push(i.id),n.set(a,c)}for(let a of i.learnings.whatDidnt){let c=s.get(a)||{count:0,ids:[]};c.count++,c.ids.push(i.id),s.set(a,c)}}for(let[i,{count:a,ids:c}]of n)t.push({pattern:`What works: ${i}`,occurrences:a,confidence:this.calculateConfidence(a),category:"workflow",sourceTasks:c});for(let[i,{count:a,ids:c}]of s)t.push({pattern:`Known issue: ${i}`,occurrences:a,confidence:this.calculateConfidence(a),category:"gotcha",sourceTasks:c});let o=e.filter(i=>i.effort.variance.percentage>30);return o.length>=Vr&&t.push({pattern:`Tasks are frequently underestimated (${o.length}/${e.length} over 30% variance)`,occurrences:o.length,confidence:this.calculateConfidence(o.length),category:"estimation",sourceTasks:o.map(i=>i.id)}),t}getAllPatterns(e,t=[]){return[...this.extractFileCochangePatterns(e),...this.extractStackPatterns(e),...this.extractArchitecturePatterns(e),...this.extractGotchaPatterns(e),...this.extractOutcomePatterns(t)].sort((n,s)=>s.occurrences-n.occurrences)}async injectIntoMemory(e,t,n){let s=this.getTagsForCategory(t.category),o=`[auto-learned] ${this.getTitleForPattern(t)}`,i=this.formatPatternContent(t),c=(await n.searchMemories(e,t.pattern)).find(u=>u.title.startsWith("[auto-learned]")&&u.content.includes(t.pattern));return c?(await n.updateMemory(e,c.id,{content:i,tags:s}),{action:"updated"}):(await n.createMemory(e,{title:o,content:i,tags:s,userTriggered:!1}),{action:"created"})}calculateConfidence(e){return e>=5?"high":e>=3?"medium":"low"}getTagsForCategory(e){return{file_cochange:[R.FILE_STRUCTURE,R.ARCHITECTURE],tech_stack:[R.TECH_STACK],architecture:[R.ARCHITECTURE,R.CODE_STYLE],estimation:[R.SHIP_WORKFLOW],workflow:[R.SHIP_WORKFLOW,R.CODE_STYLE],gotcha:[R.TEST_BEHAVIOR,R.ARCHITECTURE]}[e]||[]}getTitleForPattern(e){return`${{file_cochange:"File coupling",tech_stack:"Tech stack",architecture:"Architecture pattern",estimation:"Estimation insight",workflow:"Workflow pattern",gotcha:"Known gotcha"}[e.category]}: ${e.pattern.slice(0,80)}`}formatPatternContent(e){let t=["source: auto-learned",`pattern: ${e.pattern}`,`occurrences: ${e.occurrences}`,`confidence: ${e.confidence}`,`category: ${e.category}`,`last_updated: ${b()}`];return e.sourceTasks.length>0&&t.push(`source_tasks: ${e.sourceTasks.slice(0,5).join(", ")}`),t.join(`
582
- `)}},_l=new xi});var Ti,Rg,Ll=y(()=>{"use strict";Xc();Qt();ne();Ti=class extends Le{static{l(this,"OutcomeStorage")}constructor(){super("outcomes.json")}getDefault(){return{...Jm,lastUpdated:""}}getMdFilename(){return"outcomes.md"}getLayer(){return"progress"}getEventType(e){return`outcomes.${e}d`}toMarkdown(e){let t=["# OUTCOMES",""];if(e.outcomes.length===0&&(!e.taskOutcomes||e.taskOutcomes.length===0))return t.push("_No outcomes recorded yet._"),t.push(""),t.join(`
583
- `);let n=e.outcomes.sort((s,o)=>new Date(o.shippedAt).getTime()-new Date(s.shippedAt).getTime()).slice(0,5);if(n.length>0){t.push("## Recent Outcomes"),t.push("");for(let s of n){let o=s.success?.overallSuccess??"unknown",i=s.roi.roiScore,a=gt(s.shippedAt);t.push(`- **${s.featureName}** (${o}, ROI: ${i}) - ${a}`),s.learnings.whatWorked.length>0&&t.push(` What worked: ${s.learnings.whatWorked.slice(0,2).join(", ")}`),s.learnings.whatDidnt.length>0&&t.push(` Issues: ${s.learnings.whatDidnt.slice(0,2).join(", ")}`)}t.push("")}if(e.aggregates&&(t.push("## Aggregate Metrics"),t.push(""),t.push(`- Features: ${e.aggregates.totalFeatures}`),t.push(`- Estimation Accuracy: ${e.aggregates.averageEstimationAccuracy}%`),t.push(`- Success Rate: ${e.aggregates.averageSuccessRate}%`),t.push(`- Average ROI: ${e.aggregates.averageROI}`),t.push(""),e.aggregates.topLearnings.length>0)){t.push("### Top Learnings"),t.push("");for(let s of e.aggregates.topLearnings.slice(0,5))t.push(`- ${s.insight} (${s.frequency}x)`);t.push("")}return t.join(`
584
- `)}async addFeatureOutcome(e,t){await this.update(e,n=>({...n,outcomes:[t,...n.outcomes],aggregates:fi([t,...n.outcomes]),lastUpdated:b()})),await this.publishEvent(e,"outcome.recorded",{outcomeId:t.id,featureName:t.featureName,success:t.success?.overallSuccess})}async addTaskOutcome(e,t){await this.update(e,n=>({...n,taskOutcomes:[t,...n.taskOutcomes||[]],lastUpdated:b()}))}async getFeatureOutcomes(e){return(await this.read(e)).outcomes}async getRecentOutcomes(e,t=10){return(await this.read(e)).outcomes.sort((s,o)=>new Date(o.shippedAt).getTime()-new Date(s.shippedAt).getTime()).slice(0,t)}async getTaskOutcomes(e,t){let n=await this.read(e),s=n.taskOutcomes||[];return t?n.outcomes.find(i=>i.featureId===t)?.taskOutcomes||[]:s}async getAggregates(e){let t=await this.read(e);return!t.aggregates&&t.outcomes.length>0?fi(t.outcomes):t.aggregates}async reaggregate(e){await this.update(e,t=>({...t,aggregates:fi(t.outcomes),lastAggregated:b(),lastUpdated:b()}))}migrateFromShipped(e){return e.shipped.map(t=>this.convertShippedToOutcome(t))}convertShippedToOutcome(e){let t=e.duration?this.parseDurationString(e.duration):60,n=t/60,s=t/60,o=Wm(n,s),i={whatWorked:[],whatDidnt:[],surprises:[],recommendations:[]},a=100,c=Bm(5,s);return{id:`out_feat_${e.id}`,featureId:e.featureId||e.id,featureName:e.name,prdId:null,version:e.version||void 0,branch:e.commit?.branch||void 0,prUrl:void 0,effort:{estimated:{hours:n,confidence:"low",source:"manual"},actual:{hours:s,commits:e.codeMetrics?.commits||void 0,linesAdded:e.codeMetrics?.linesAdded||void 0,linesRemoved:e.codeMetrics?.linesRemoved||void 0},variance:o},success:{metrics:[],acceptanceCriteria:[],overallSuccess:Vm(a),successScore:a},learnings:i,roi:{valueDelivered:5,userImpact:"medium",businessImpact:"medium",roiScore:c,worthIt:"probably"},rating:3,startedAt:e.shippedAt,shippedAt:e.shippedAt,legacy:!0}}parseDurationString(e){let t=0,n=e.match(/(\d+)h/);n&&(t+=parseInt(n[1],10)*60);let s=e.match(/(\d+)m/);return s&&(t+=parseInt(s[1],10)),t||60}},Rg=new Ti});var Ul=y(()=>{"use strict";Ig();Dg();Nl();ns();Ll()});function Sv(r){let e=r.trim().toLowerCase(),t=e.replace(/[.\s-]/g,"");return Ei[t]?Ei[t]:Ei[e]?Ei[e]:e}function ji(r){let e=new Set,t=[];for(let n of r){let s=Sv(n);e.has(s)||(e.add(s),t.push(n))}return t}var Ei,Hl=y(()=>{"use strict";Ei={nextjs:"next.js",nuxtjs:"nuxt.js",expressjs:"express",fastifyjs:"fastify","react.js":"react","vue.js":"vue","svelte.js":"svelte","angular.js":"angular",angularjs:"angular","node.js":"node",nodejs:"node",ts:"typescript",js:"javascript",pg:"postgres",postgresql:"postgres",mongo:"mongodb"};l(Sv,"normalizeFrameworkName");l(ji,"deduplicateTechStack")});import{z as Oe}from"zod";function $g(r){let e=[];e.push(`## CONSTRAINTS (Read Before Acting)
585
- `);let t=[];r.language&&t.push(r.language),r.framework&&t.push(r.framework);let n=r.techStack??[];t.push(...n);let s=r.analysisLanguages??[],o=r.analysisFrameworks??[];t.push(...s,...o);let i=ji(t);if(i.length>0&&e.push(`AVAILABLE in this project: ${i.join(", ")}`),r.analysisPackageManager&&e.push(`PACKAGE MANAGER: ${r.analysisPackageManager}`),r.domains){let c=Object.entries(r.domains).filter(([,u])=>!u).map(([u])=>bv[u]).filter(Boolean);c.length>0&&e.push(`NOT PRESENT: ${c.join(", ")}`)}let a=r.availableAgents??[];return a.length>0&&e.push(`AGENTS: ${a.join(", ")}`),e.push(""),e.push(`SCOPE: Only files in \`${r.projectPath}\` are accessible.`),e.push("RULE: Use ONLY file paths explicitly shown in context. Do NOT infer or guess paths."),e.push("RULE: NEVER assume a library is available. Check package.json/imports first."),e.push("RULE: If previous context contradicts this section, trust this section."),e.push("RULE: Read files BEFORE modifying. Never assume code structure."),r.fileCount&&e.push(`
586
- Context: ${r.fileCount} files in project.`),e.join(`
587
- `)}var lN,bv,Mg=y(()=>{"use strict";Hl();lN=Oe.object({projectPath:Oe.string(),language:Oe.string().optional(),framework:Oe.string().optional(),techStack:Oe.array(Oe.string()).default([]),domains:Oe.object({hasFrontend:Oe.boolean().default(!1),hasBackend:Oe.boolean().default(!1),hasDatabase:Oe.boolean().default(!1),hasTesting:Oe.boolean().default(!1),hasDocker:Oe.boolean().default(!1)}).optional(),fileCount:Oe.number().optional(),availableAgents:Oe.array(Oe.string()).default([]),analysisLanguages:Oe.array(Oe.string()).default([]),analysisFrameworks:Oe.array(Oe.string()).default([]),analysisPackageManager:Oe.string().optional()}),bv={hasFrontend:"Frontend (UI/components)",hasBackend:"Backend (APIs/servers)",hasDatabase:"Database (SQL/ORM)",hasTesting:"Testing (unit/integration)",hasDocker:"Docker/containers"};l($g,"buildAntiHallucinationBlock")});import{z as Ut}from"zod";var Pv,Fg,Og=y(()=>{"use strict";Pv=Ut.object({agents:Ut.boolean(),patterns:Ut.boolean(),checklist:Ut.boolean(),modules:Ut.array(Ut.string())}),Fg=Ut.object({version:Ut.string(),description:Ut.string().optional(),commands:Ut.record(Ut.string(),Pv).refine(r=>"*"in r,{message:'Config must include a "*" wildcard entry for unknown commands'})})});function Gl(r,e){return e.filter(t=>new RegExp(`\\b${t}\\b`).test(r)).length}function _g(r,e){let t=(e.frontmatter?.description||"").toLowerCase(),n=e.content.toLowerCase(),s=e.frontmatter?.["allowed-tools"]||[],o=`${r} ${t} ${n}`,i=Gl(o,Cv),a=Gl(o,vv),c=Gl(o,xv);return s.some(p=>Tv.includes(p))&&i>0?{agents:!0,patterns:!0,checklist:c>0,modules:[]}:c>0&&c>=a?{agents:!1,patterns:!0,checklist:!0,modules:[]}:a>0&&i===0?{agents:!1,patterns:!1,checklist:!1,modules:[]}:{agents:!0,patterns:!0,checklist:!1,modules:[]}}var Cv,vv,xv,Tv,Ng=y(()=>{"use strict";Cv=["build","create","add","implement","fix","refactor","update","modify","change","write","generate","scaffold","migrate","optimize","improve","enhance","redesign","rewrite"],vv=["list","show","get","status","info","check","view","display","describe","explain","analyze","report","dashboard"],xv=["test","verify","validate","review","audit","check","lint","ship","deploy","release","complete","done","finish"],Tv=["Write","Edit","Bash"];l(Gl,"countMatches");l(_g,"classifyCommand")});import zl from"node:fs/promises";import Ev from"node:path";async function Ug(){if(qr)return qr;let r=await zl.readFile(Jl,"utf-8"),e=JSON.parse(r);return qr=Fg.parse(e),qr}function jv(r){return Hg.get(r)}function Av(r,e){Hg.set(r,e)}function Dv(r,e){let t=r,n=Lg.get(t);return n&&$v(n.entry,e)?(n.count++,n.count>=Iv):(Lg.set(t,{entry:e,count:1}),!1)}async function Rv(r,e){let t=await zl.readFile(Jl,"utf-8"),n=JSON.parse(t);n.commands[r]=e,await zl.writeFile(Jl,`${JSON.stringify(n,null,2)}
588
- `,"utf-8"),qr=null}function $v(r,e){return r.agents===e.agents&&r.patterns===e.patterns&&r.checklist===e.checklist&&r.modules.length===e.modules.length&&r.modules.every((t,n)=>t===e.modules[n])}function Gg(r,e,t){if(e in r.commands&&e!=="*")return{entry:r.commands[e],source:"config"};let n=jv(e);if(n)return{entry:n,source:"cache"};if(t){let s=_g(e,t);return Av(e,s),Dv(e,s)&&Rv(e,s).catch(()=>{}),{entry:s,source:"classified"}}return{entry:r.commands["*"],source:"wildcard"}}var Jl,qr,Hg,Lg,Iv,zg=y(()=>{"use strict";Og();st();Ng();Jl=Ev.join(ce,"core/config/command-context.config.json"),qr=null;l(Ug,"loadCommandContextConfig");Hg=new Map;l(jv,"getCachedClassification");l(Av,"cacheClassification");Lg=new Map,Iv=3;l(Dv,"trackClassification");l(Rv,"persistClassification");l($v,"isSameEntry");l(Gg,"resolveCommandContextFull")});import Mv from"node:os";import{z as rn}from"zod";function Fv(){return typeof globalThis<"u"&&"Bun"in globalThis?"bun":"node"}function Ov(r){return{darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD"}[r]??r}function Jg(r){let e=r.platform??Mv.platform(),t=r.runtime??Fv(),n=r.date??new Date().toISOString().split("T")[0];return`<env>
589
- ${[["project",r.projectName],["path",r.projectPath],["git",r.isGitRepo?"true":"false"],["branch",r.gitBranch],["platform",Ov(e)],["runtime",t],["date",n],["model",r.model],["provider",r.provider]].filter(([,i])=>i!==void 0).map(([i,a])=>`${i}: ${a}`).join(`
590
- `)}
591
- </env>`}var xN,Wg=y(()=>{"use strict";xN=rn.object({projectName:rn.string(),projectPath:rn.string(),isGitRepo:rn.boolean().default(!0),gitBranch:rn.string().optional(),platform:rn.string().optional(),runtime:rn.string().optional(),date:rn.string().optional(),model:rn.string().optional(),provider:rn.string().optional()});l(Fv,"detectRuntime");l(Ov,"normalizePlatform");l(Jg,"buildEnvironmentBlock")});function Vg(r){let e=r.getAllocationFor("injection");return{...Ii,totalPrompt:e}}function rs(r,e){let t=e*qg;return r.length<=t?r:`${r.substring(0,t)}
592
- ... (truncated to ~${e} tokens)`}function Bg(r){return Math.ceil(r.length/qg)}function Kg(r,e){if(e.length===0||r.length===0)return r;let t=new Set;for(let n of e){let s=_v[n.toLowerCase()];if(s)for(let o of s)t.add(o);t.add(n.toLowerCase())}return r.filter(n=>{let s=`${n.name} ${n.content}`.toLowerCase();for(let o of t)if(s.includes(o))return!0;return!1})}var Ii,qg,_v,Ai,Xg=y(()=>{"use strict";Ii={autoContext:500,agentContent:400,skillContent:500,stateData:1e3,memories:600,totalPrompt:8e3};l(Vg,"budgetsFromCoordinator");qg=4;l(rs,"truncateToTokenBudget");l(Bg,"estimateTokens");_v={frontend:["react","vue","svelte","css","html","ui","component","frontend","web","dom"],backend:["api","server","backend","endpoint","route","middleware","database","sql"],testing:["test","spec","jest","vitest","cypress","playwright","coverage","assert"],devops:["docker","ci","cd","deploy","kubernetes","terraform","pipeline","github-actions"],docs:["documentation","readme","guide","tutorial","markdown"],design:["design","ux","ui","figma","wireframe","layout","accessibility"]};l(Kg,"filterSkillsByDomains");Ai=class{static{l(this,"InjectionBudgetTracker")}used=0;budgets;constructor(e={}){this.budgets={...Ii,...e}}addSection(e,t){let n=rs(e,t),s=Bg(n);if(this.used+s>this.budgets.totalPrompt){let o=this.budgets.totalPrompt-this.used;if(o<=0)return"";let i=rs(n,o);return this.used+=Bg(i),i}return this.used+=s,n}get remaining(){return Math.max(0,this.budgets.totalPrompt-this.used)}get totalUsed(){return this.used}get config(){return this.budgets}}});import Yg from"node:fs/promises";import os from"node:path";var Wl,Nv,Qg,Zg=y(()=>{"use strict";sn();M();me();st();Ul();Mg();zg();Wg();Xg();Hl();Yn();Wl=class{static{l(this,"PromptBuilder")}_checklistsCache=null;_checklistsCacheTime=0;_checklistRoutingCache=null;_checklistRoutingCacheTime=0;_currentContext=null;_stateCache=new Map;_stateCacheTTL=5e3;_templateCache=new Map;TEMPLATE_CACHE_TTL_MS=6e4;_coordinator=null;async getTemplate(e){let t=this._templateCache.get(e),n=Date.now();if(t&&n-t.loadedAt<this.TEMPLATE_CACHE_TTL_MS)return t.content;try{if(await C(e)){let s=await Yg.readFile(e,"utf-8");return this._templateCache.set(e,{content:s,loadedAt:n}),s}}catch(s){k(s)||console.error(`Template loading warning: ${w(s)}`)}return null}clearTemplateCache(){this._templateCache.clear(),this._checklistsCache=null,this._checklistsCacheTime=0,this._checklistRoutingCache=null,this._checklistRoutingCacheTime=0}setCoordinator(e){this._coordinator=e}getCoordinator(){return this._coordinator}getEffectiveBudgets(){return this._coordinator?Vg(this._coordinator):Ii}resetContext(){this._currentContext=null}setContext(e){this._currentContext=e}async loadModule(e){let t=Se(`global/modules/${e}`);if(t)return t;let n=os.join(ce,"templates/global/modules",e);return this.getTemplate(n)}getModulesForCommand(e,t){return t?t.modules:[]}async loadChecklists(){let e=Date.now();if(this._checklistsCache&&e-this._checklistsCacheTime<this.TEMPLATE_CACHE_TTL_MS)return this._checklistsCache;let t={};try{let n=zs("checklists/");if(n.length>0){for(let s of n)if(s.endsWith(".md")){let o=Se(s);if(o){let i=os.basename(s,".md");t[i]=o}}}else{let s=os.join(ce,"templates","checklists");if(await C(s)){let o=(await Yg.readdir(s)).filter(i=>i.endsWith(".md"));for(let i of o){let a=i.replace(".md",""),c=os.join(s,i),u=await this.getTemplate(c);u&&(t[a]=u)}}}}catch(n){k(n)||console.error(`Checklist loading warning: ${w(n)}`)}return this._checklistsCache=t,this._checklistsCacheTime=e,t}async getProjectState(e){if(!e)return null;let t=this._stateCache.get(e);if(t&&Date.now()-t.timestamp<this._stateCacheTTL)return t.state;try{let[n,s]=await Promise.all([le.read(e),ot.read(e)]),o={projectId:e,currentTask:n.currentTask,queue:s.tasks};return this._stateCache.set(e,{state:o,timestamp:Date.now()}),o}catch(n){if(k(n)||n instanceof SyntaxError)return null;throw n}}async buildInjectedContext(e){if(!e)return null;let t=await this.getProjectState(e);if(!t)return null;let n=[];if(n.push("## AUTO-INJECTED CONTEXT"),n.push(""),t.currentTask){let o=this.calculateElapsed(t.currentTask.startedAt);n.push(`**Current Task**: ${t.currentTask.description}`),n.push(`- Started: ${o} ago`)}else n.push("**Current Task**: None");if(n.push(""),t.queue.length>0){n.push(`**Queue**: ${t.queue.length} tasks pending`);let o=t.queue.slice(0,3);for(let i of o)n.push(`- [${i.priority}] ${i.description}`);t.queue.length>3&&n.push(`- ... and ${t.queue.length-3} more`)}n.push("");try{let o=await Ol.detectPatterns(e);if(o.length>0){n.push("**Project Conventions**");for(let i of o.slice(0,3))n.push(`- ${i.description}`),i.suggestedAction&&n.push(` \u2192 ${i.suggestedAction}`);n.push("")}}catch(o){!k(o)&&!(o instanceof SyntaxError)&&console.error(`Outcome detection warning: ${w(o)}`)}n.push("---"),n.push("");let s=n.join(`
593
- `);return rs(s,this.getEffectiveBudgets().autoContext)}calculateElapsed(e){let t=new Date(e).getTime(),s=Date.now()-t,o=Math.floor(s/6e4),i=Math.floor(o/60),a=Math.floor(i/24);return a>0?`${a}d ${i%24}h`:i>0?`${i}h ${o%60}m`:`${o}m`}async loadChecklistRouting(){let e=Date.now();if(this._checklistRoutingCache&&e-this._checklistRoutingCacheTime<this.TEMPLATE_CACHE_TTL_MS)return this._checklistRoutingCache;let t=os.join(__dirname,"..","..","templates","agentic","checklist-routing.md"),n=await this.getTemplate(t);return n&&(this._checklistRoutingCache=n,this._checklistRoutingCacheTime=e),this._checklistRoutingCache||null}async buildWithInjection(e,t,n,s=null,o=null,i=null,a=null,c=null){let u=[];if(t.projectId){let m=await this.buildInjectedContext(t.projectId);m&&u.push(m)}let p=await this.build(e,t,n,s,o,i,a,c);return u.push(p),u.join("")}async build(e,t,n,s=null,o=null,i=null,a=null,c=null,u=null){let p=[];this._currentContext=t;let m=e.frontmatter?.name?.replace("p:","")||"",d;try{let v=await Ug();d=Gg(v,m,e).entry}catch{d={agents:!0,patterns:!0,checklist:!1,modules:[]}}let g=d.agents;s&&g&&(p.push(`# AGENT: ${s.name}
594
- `),s.role&&p.push(`Role: ${s.role}
595
- `),s.skills?.length&&p.push(`Skills: ${s.skills.join(", ")}
596
- `),p.push(`
597
- Apply specialized expertise. Read agent file for details if needed.
598
-
599
- `)),p.push(`TASK: ${e.frontmatter.description}
600
- `),e.frontmatter["allowed-tools"]&&p.push(`TOOLS: ${e.frontmatter["allowed-tools"].join(", ")}
601
- `);let f=t;(f.params?.task||f.params?.description)&&p.push(`INPUT: ${f.params.task||f.params.description}
602
- `);let S=t.projectPath;if(S){let v=u?.project?.id?os.basename(S):os.basename(S),D=Jg({projectName:v,projectPath:S,isGitRepo:!0,gitBranch:u?.realContext?.gitBranch});p.push(`
603
- ${D}
604
- `)}if(u){let v=u.sealedAnalysis;if(p.push(`
605
- ## PROJECT ANALYSIS (Sealed)
606
- `),p.push(`**Ecosystem**: ${u.project.ecosystem}
607
- `),p.push(`**Primary Domain**: ${u.primaryDomain}
608
- `),p.push(`**Domains**: ${u.detectedDomains.join(", ")}
609
- `),v){if(v.languages.length>0&&p.push(`**Languages**: ${v.languages.join(", ")}
610
- `),v.frameworks.length>0&&p.push(`**Frameworks**: ${v.frameworks.join(", ")}
611
- `),v.packageManager&&p.push(`**Package Manager**: ${v.packageManager}
612
- `),v.sourceDir&&p.push(`**Source Dir**: ${v.sourceDir}
613
- `),v.testDir&&p.push(`**Test Dir**: ${v.testDir}
614
- `),p.push(`**Files Analyzed**: ${v.fileCount}
615
- `),p.push(`**Analysis Status**: ${v.status}${v.commitHash?` (commit: ${v.commitHash.slice(0,8)})`:""}
616
- `),v.patterns.length>0){p.push(`
617
- ### Code Patterns (Follow These)
618
- `);for(let D of v.patterns)p.push(`- **${D.name}**: ${D.description}${D.location?` (${D.location})`:""}
619
- `)}if(v.antiPatterns.length>0){p.push(`
620
- ### Anti-Patterns (Avoid These)
621
- `);for(let D of v.antiPatterns)p.push(`- **${D.issue}** in \`${D.file}\` \u2014 ${D.suggestion}
622
- `)}}p.push(`
623
- `)}let E=d.patterns,x=n?.codePatterns||"";if(E&&x&&x.trim()){let v=this.extractPatternSummary(x);v&&(p.push(`## CODE PATTERNS
624
- `),p.push(v),p.push(`
625
- Full patterns: Read analysis/patterns.md
626
- `))}let $=n?.analysis||"";if(E&&$&&$.trim()){let v=$.match(/Stack[:\s]+([^\n]+)/i)||$.match(/Technology[:\s]+([^\n]+)/i),D=v?v[1].trim():"detected";p.push(`
627
- ## STACK
628
- Stack: ${D}
629
- `),x||p.push(`Read analysis/repo-summary.md + similar files before coding. Match patterns exactly.
630
- `)}if(u){if(u.agents.length>0){p.push(`
631
- ### LOADED AGENTS (Project-Specific Specialists)
632
-
633
- `);for(let D of u.agents){p.push(`#### Agent: ${D.name} (${D.domain})
634
- `),D.effort&&p.push(`Effort: ${D.effort}
635
- `),D.model&&p.push(`Model: ${D.model}
636
- `),D.skills.length>0&&p.push(`Skills: ${D.skills.join(", ")}
637
- `);let Re=rs(D.content,this.getEffectiveBudgets().agentContent);p.push(`\`\`\`markdown
638
- ${Re}
639
- \`\`\`
640
-
641
- `)}}let v=Kg(u.skills,u.detectedDomains);if(v.length>0){p.push(`### LOADED SKILLS (From Agent Frontmatter)
642
-
643
- `);for(let D of v){p.push(`#### Skill: ${D.name}
644
- `);let Re=rs(D.content,this.getEffectiveBudgets().skillContent);p.push(`\`\`\`markdown
645
- ${Re}
646
- \`\`\`
647
-
648
- `)}}}let z=this.getModulesForCommand(m,d);if(z.length>0)for(let v of z){let D=await this.loadModule(v);D&&(p.push(`
649
- `),p.push(D))}if(c?.isPlanning&&(p.push(`
650
- ## PLAN MODE
651
- Read-only. Gather info \u2192 Analyze \u2192 Propose plan \u2192 Wait for approval.
652
- `),c.allowedTools&&p.push(`Tools: ${c.allowedTools.join(", ")}
653
- `)),c?.requiresApproval&&p.push(`
654
- ## APPROVAL REQUIRED
655
- Show changes, list affected files, ask for confirmation.
656
- `),S){let v=u?.sealedAnalysis,D=[...v?.frameworks||[],...u?.project?.conventions||[]],Re={projectPath:S,language:u?.project?.ecosystem,framework:v?.frameworks?.[0],techStack:ji(D),domains:this.extractDomains(n),fileCount:t.files?.length||t.filteredSize||0,availableAgents:u?.agents?.map(B=>B.name)||[],analysisLanguages:v?.languages||[],analysisFrameworks:v?.frameworks||[],analysisPackageManager:v?.packageManager};p.push(`
657
- ${$g(Re)}
658
- `)}else p.push(this.buildCriticalRules());if(u?.realContext){let v=u.realContext;if(p.push(`
659
- ### CODEBASE CONTEXT
660
-
661
- `),p.push(`**Git State**: Branch \`${v.gitBranch}\` | ${v.gitStatus}
662
-
663
- `),v.relevantFiles.length>0){p.push(`**Relevant Files** (scored by task relevance):
664
- `),p.push(`| Score | File | Why |
665
- `),p.push(`|-------|------|-----|
666
- `);for(let D of v.relevantFiles.slice(0,8))p.push(`| ${D.score} | ${D.path} | ${D.reason} |
667
- `);p.push(`
668
- `)}if(v.signatures.length>0){p.push(`**Code Signatures** (top files):
669
- `);for(let D of v.signatures)p.push(`\`\`\`typescript
670
- // ${D.path}
671
- ${D.content}
672
- \`\`\`
673
- `);p.push(`
674
- `)}if(v.recentFiles.length>0){p.push("**Recently Changed**: ");let D=v.recentFiles.slice(0,5).map(Re=>`${Re.path} (${Re.lastChanged})`).join(", ");p.push(`${D}
675
-
676
- `)}}let _e=t.files||[];if(_e.length>0){let v=_e.slice(0,5).join(", ");p.push(`
677
- ## FILES: ${_e.length} available. Top: ${v}
678
- `),p.push(`Read BEFORE modifying. Use Glob/Grep to find more.
679
-
680
- `)}else S&&p.push(`
681
- ## PROJECT: ${S}
682
- Read files before modifying.
683
-
684
- `);let nt=this.filterRelevantState(n);if(nt&&(p.push(`
685
- ## PRJCT STATE (Project Management Data)
686
- `),p.push(nt),p.push(`
687
- `)),u?.velocityContext&&(p.push(`
688
- ### VELOCITY (Historical Estimation Data)
689
-
690
- `),p.push(u.velocityContext),p.push(`
691
-
692
- `)),o&&Object.keys(o).some(v=>o[v])){p.push(`
693
- ## PROJECT DEFAULTS (apply automatically)
694
- `);for(let[v,D]of Object.entries(o))D&&p.push(`- ${v}: ${D}
695
- `)}if(i?.plan&&i.plan.length>0){if(p.push(`
696
- ## THINK FIRST (reasoning from analysis)
697
- `),i.conclusions&&i.conclusions.length>0){p.push(`Conclusions:
698
- `);for(let v of i.conclusions)p.push(` \u2192 ${v}
699
- `)}p.push(`Plan:
700
- `);for(let v=0;v<i.plan.length;v++)p.push(` ${v+1}. ${i.plan[v]}
701
- `);p.push(`Confidence: ${Math.round((i.confidence||.5)*100)}%
702
- `)}if(a&&a.length>0){p.push(`
703
- ## CONTEXT (apply these)
704
- `);for(let v of a)p.push(`- **${v.title}**: ${v.content}
705
- `),v.tags&&v.tags.length>0&&p.push(` Tags: ${v.tags.join(", ")}
706
- `)}if(p.push(`
707
- ---
708
- `),p.push(e.content),u?.requiresFragmentation&&u.subtasks){p.push(`
709
- ### SUBTASKS (Execute in Order)
710
-
711
- `),p.push("**IMPORTANT**: Focus on the CURRENT subtask. Use `p. done` when complete to advance.\n\n"),p.push(`| # | Domain | Description | Status |
712
- `),p.push(`|---|--------|-------------|--------|
713
- `);for(let D of u.subtasks){let Re=D.status==="in_progress"?"\u25B6\uFE0F **CURRENT**":D.status==="completed"?"\u2705 Done":D.status==="failed"?"\u274C Failed":"\u23F3 Pending";p.push(`| ${D.order} | ${D.domain} | ${D.description} | ${Re} |
714
- `)}let v=u.subtasks.find(D=>D.status==="in_progress");if(v&&(p.push(`
715
- **FOCUS ON SUBTASK #${v.order}**: ${v.description}
716
- `),p.push(`Agent: ${v.agent} | Domain: ${v.domain}
717
- `),v.dependsOn.length>0&&p.push(`Dependencies: ${v.dependsOn.join(", ")}
718
- `),v.handoff)){let D=v.handoff;p.push(`
719
- ### Previous Subtask Handoff
720
-
721
- `),p.push(`**From:** ${D.fromSubtask}
722
-
723
- `),p.push(`**What was done:**
724
- `);for(let Re of D.whatWasDone)p.push(`- ${Re}
725
- `);if(D.filesChanged.length>0){p.push(`
726
- **Files changed:**
727
- `);for(let Re of D.filesChanged)p.push(`- \`${Re.path}\` (${Re.action})
728
- `)}p.push(`
729
- **Context for this subtask:**
730
- ${D.outputForNextAgent}
731
- `)}p.push(`
732
- `)}let Dt=this.getSchemaTypeForCommand(m);if(Dt){let{renderSchemaForPrompt:v}=await Promise.resolve().then(()=>(gi(),Um)),D=v(Dt);D&&p.push(`
733
- ${D}
734
- `)}if(d.checklist){let v=await this.loadChecklistRouting(),D=await this.loadChecklists();v&&Object.keys(D).length>0&&(p.push(`
735
- ## QUALITY CHECKLISTS
736
- `),p.push(`Apply relevant checklists based on task. Read checklist-routing.md for guidance.
737
- `),p.push(`Available: ${Object.keys(D).join(", ")}
738
- `),p.push(`Path: templates/checklists/{name}.md
739
- `),p.push(`Use Read tool to load checklists you determine are relevant.
740
- `))}return p.push(this.buildEfficiencyDirective()),p.join("")}filterRelevantState(e){if(!e||Object.keys(e).length===0)return null;let t=this.getEffectiveBudgets(),n=new Ai({totalPrompt:t.stateData}),s=["now","next","context","analysis","codePatterns"],o=[];for(let[i,a]of Object.entries(e))if(a&&a.trim()){let c=s.includes(i)?500:250,u=n.addSection(`### ${i}
741
- ${a}`,c);u&&o.push(u)}return o.length>0?o.join(`
742
-
743
- `):null}buildAnalysis(e,t){let n=[];return n.push(`# Analyze: ${e}
744
-
745
- `),n.push(`Read the project context and provide your analysis.
746
- `),n.push(`No predetermined patterns - decide based on what you find.
747
-
748
- `),n.push(`## Project Context
749
- `),n.push(`- Path: ${t.projectPath}
750
- `),n.push(`- ID: ${t.projectId}
751
-
752
- `),n.join("")}extractPatternSummary(e){if(!e)return null;let t=[],n=e.match(/## Conventions[\s\S]*?(?=##|$)/i);if(n){let a=n[0].split(`
753
- `).filter(c=>c.includes(":")||c.startsWith("-")).slice(0,6).join(`
754
- `);a&&t.push(a)}let s=e.match(/### High Priority[\s\S]*?(?=###|##|$)/i);if(s){let a=s[0].substring(0,300);t.push(`
755
- Avoid:
756
- ${a}`)}let o=t.join(`
757
- `);return rs(o,200)||null}getSchemaTypeForCommand(e){return{task:"subtaskBreakdown",bug:"classification"}[e]??null}buildCriticalRules(){return`
758
- ## RULES (CRITICAL)
759
- 1. **READ FIRST**: Use Read tool BEFORE modifying any file. Never assume code structure.
760
- 2. **MATCH PATTERNS**: Follow existing style, architecture, naming, imports exactly.
761
- 3. **NO HALLUCINATIONS**: Don't invent files, functions, or paths. If unsure, READ first.
762
- 4. **GIT SAFETY**: Never use checkout/reset --hard/clean. Always check status first.
763
- 5. **VERIFY**: After writing, confirm code matches project patterns.
764
- Context: ${this._currentContext?.files?.length||this._currentContext?.filteredSize||0} files available. Read what you need.
765
- `}buildEfficiencyDirective(){return`
766
- ## OUTPUT RULES
767
- - Be concise. Maximum 4 lines of explanation unless asked for detail.
768
- - No preamble ("Here is...", "I'll help you...", "Based on...").
769
- - No postamble (summaries, next steps suggestions unless asked).
770
- - When executing code: show the code, not the explanation.
771
- - Prefer structured output (JSON) over free text when applicable.
772
-
773
- EXECUTE: Follow flow. Use tools. Decide.
774
- `}extractDomains(e){if(!e)return;let t=e;if(t.domains&&typeof t.domains=="object"){let n=t.domains;return{hasFrontend:n.hasFrontend??!1,hasBackend:n.hasBackend??!1,hasDatabase:n.hasDatabase??!1,hasTesting:n.hasTesting??!1,hasDocker:n.hasDocker??!1}}}},Nv=new Wl,Qg=Nv});import ef from"node:fs/promises";import Et from"node:path";var Lv,Uv,Bl,Vl,Di,ql=y(()=>{"use strict";Ye();ee();M();Lv=["task","done","ship","resume","bug","enrich"],Uv=["init","sync","pause","next","dash","history","undo","redo"],Bl=class{static{l(this,"TemplateExecutor")}async getNpmRoot(){return Et.dirname(Tp.resolve("prjct-cli/package.json"))}async getProjectId(e){return I.getProjectId(e)}async buildContext(e,t,n){let s=await this.getProjectId(n),o=P.getGlobalProjectPath(s),a=await(He(),bt(mt)).getActiveProvider(),c;try{let u=await this.getNpmRoot();c=Et.join(u,"templates")}catch{c=Et.join(__dirname,"..","..","templates")}return{projectPath:n,projectId:s,globalPath:o,command:e,args:t,agentName:a.displayName,agentSettingsPath:await P.getAgentSettingsPath(),paths:{orchestrator:Et.join(c,"agentic","orchestrator.md"),agentRouting:Et.join(c,"agentic","agent-routing.md"),taskFragmentation:Et.join(c,"agentic","task-fragmentation.md"),commandTemplate:Et.join(c,"commands",`${e}.md`),repoAnalysis:Et.join(o,"analysis","repo-analysis.json"),agentsDir:Et.join(o,"agents"),skillsDir:a.skillsDir,stateJson:Et.join(o,"storage","state.json")}}}requiresOrchestration(e){return Lv.includes(e)?!0:!Uv.includes(e)}async hasAgents(e){try{let t=await this.getProjectId(e),n=Et.join(P.getGlobalProjectPath(t),"agents");return(await ef.readdir(n)).some(o=>o.endsWith(".md"))}catch(t){return k(t),!1}}async getAvailableAgents(e){try{let t=await this.getProjectId(e),n=Et.join(P.getGlobalProjectPath(t),"agents");return(await ef.readdir(n)).filter(o=>o.endsWith(".md")).map(o=>o.replace(".md",""))}catch{return[]}}buildAgenticPrompt(e){let t=this.requiresOrchestration(e.command);return{prompt:`
775
- ## Agentic Execution Mode
776
-
777
- You are executing a prjct command as ${e.agentName}. Follow the template-first approach.
778
-
779
- ### Context
780
- - Agent: ${e.agentName}
781
- - Settings: ${e.agentSettingsPath}
782
- - Command: ${e.command}
783
- - Args: ${e.args}
784
- - Project: ${e.projectPath}
785
- - Project ID: ${e.projectId}
786
-
787
- ### Paths (Read as needed)
788
- - Orchestrator: ${e.paths.orchestrator}
789
- - Agent Routing: ${e.paths.agentRouting}
790
- - Task Fragmentation: ${e.paths.taskFragmentation}
791
- - Command Template: ${e.paths.commandTemplate}
792
- - Repo Analysis: ${e.paths.repoAnalysis}
793
- - Agents Directory: ${e.paths.agentsDir}
794
- - Skills Directory: ${e.paths.skillsDir}
795
- - State JSON: ${e.paths.stateJson}
796
-
797
- ### Instructions
798
-
799
- 1. **Read the command template** (${e.paths.commandTemplate})
800
-
801
- 2. **Check if orchestration is needed**
802
- - This command ${t?"REQUIRES":"does NOT require"} orchestration
803
- ${t?`
804
- 3. **Orchestration steps:**
805
- - Read: ${e.paths.orchestrator}
806
- - Read: ${e.paths.repoAnalysis} to understand project technologies
807
- - Analyze the task: "${e.args}"
808
- - Determine which domains are ACTUALLY relevant based on:
809
- a) What the task requires
810
- b) What technologies exist in this project
811
- c) What agents are available in ${e.paths.agentsDir}
812
-
813
- - **IMPORTANT**: The agents in ${e.paths.agentsDir} are already project-specific
814
- (they were generated during p. sync with the actual project technologies)
815
-
816
- - ALWAYS use the specialist if one exists for the domain
817
- - Only use the generalist if there is NO agent for that domain
818
-
819
- - Check if task should be fragmented (read: ${e.paths.taskFragmentation})
820
- - If agents loaded, check their skills and load from ${e.paths.skillsDir}
821
- `:`
822
- 3. **Simple execution:**
823
- - Execute the command template directly
824
- - No agent routing needed
825
- `}
826
-
827
- 4. **Execute the command template** with full context
828
-
829
- 5. **Return results**
830
-
831
- ### Agentic Decision Making
832
-
833
- YOU decide:
834
- - Whether to run orchestration (based on command type)
835
- - Which domains the task involves (frontend, backend, database, etc.)
836
- - Whether to fragment the task into subtasks
837
- - Which specialist agents to delegate to
838
-
839
- ALWAYS:
840
- - Use specialist agents when they exist (they're already project-specific)
841
- - Delegate subtasks to the appropriate specialist via Task tool
842
- - Let specialists handle their domain (they have the project patterns)
843
- - Generate and store summaries when subtasks complete
844
-
845
- ONLY use generalist when:
846
- - No specialist agent exists for that domain
847
- - Task is completely outside project scope
848
- - Extreme edge case
849
-
850
- ### Subtask Management
851
-
852
- When fragmenting tasks:
853
- 1. Store subtasks in state.json under currentTask.subtasks
854
- 2. Track progress: currentSubtaskIndex, subtaskProgress
855
- 3. Each completed subtask generates a summary
856
- 4. Pass summary to next agent for context handoff
857
- `,context:e,requiresOrchestration:t}}},Vl=new Bl,Di=Vl});function Kr(r){if(!r||typeof r!="object")return!1;let e=r;if(e.code&&Hv.has(e.code))return!0;if(e.code&&nf.has(e.code))return!1;if(e.message){let t=e.message.toLowerCase();if(t.includes("timeout")||t.includes("timed out"))return!0}return!1}function $i(r){if(!r||typeof r!="object")return!1;let e=r;return!!(e.code&&nf.has(e.code))}function tf(r,e,t){let n=Mn.get(r);return n&&n.consecutiveFailures>=e&&n.openedAt?Date.now()-n.openedAt>=t?(Mn.delete(r),!1):!0:!1}function Kl(r,e){let t=Mn.get(r)||{consecutiveFailures:0,openedAt:null};t.consecutiveFailures++,t.consecutiveFailures>=e&&!t.openedAt&&(t.openedAt=Date.now()),Mn.set(r,t)}function Gv(r){Mn.delete(r)}var Hv,nf,Mn,Ri,sf,Xr,Mi=y(()=>{"use strict";Hv=new Set(["EBUSY","EAGAIN","ETIMEDOUT","ECONNRESET","ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),nf=new Set(["ENOENT","EACCES","EPERM","EISDIR","ENOTDIR","EINVAL"]);l(Kr,"isTransientError");l($i,"isPermanentError");Mn=new Map;l(tf,"isCircuitOpen");l(Kl,"recordFailure");l(Gv,"recordSuccess");Ri=class{static{l(this,"RetryPolicy")}options;constructor(e={}){this.options={maxAttempts:e.maxAttempts??3,baseDelayMs:e.baseDelayMs??1e3,maxDelayMs:e.maxDelayMs??8e3,circuitBreakerThreshold:e.circuitBreakerThreshold??5,circuitBreakerTimeoutMs:e.circuitBreakerTimeoutMs??6e4}}async execute(e,t="default"){if(tf(t,this.options.circuitBreakerThreshold,this.options.circuitBreakerTimeoutMs))throw new Error(`Circuit breaker is open for operation: ${t}. Too many consecutive failures.`);let n,s=0;for(;s<this.options.maxAttempts;)try{let o=await e();return Gv(t),o}catch(o){if(n=o,s++,$i(o))throw Kl(t,this.options.circuitBreakerThreshold),o;if(!(Kr(o)&&s<this.options.maxAttempts))throw Kl(t,this.options.circuitBreakerThreshold),o;let a=Math.min(this.options.baseDelayMs*2**(s-1),this.options.maxDelayMs);await new Promise(c=>setTimeout(c,a))}throw Kl(t,this.options.circuitBreakerThreshold),n}isTransientError(e){return Kr(e)}isCircuitOpen(e){return tf(e,this.options.circuitBreakerThreshold,this.options.circuitBreakerTimeoutMs)}getCircuitState(e){return Mn.get(e)}resetCircuit(e){Mn.delete(e)}resetAllCircuits(){Mn.clear()}},sf=new Ri({maxAttempts:3,baseDelayMs:1e3,maxDelayMs:8e3}),Xr=new Ri({maxAttempts:2,baseDelayMs:500,maxDelayMs:2e3})});import{exec as zv}from"node:child_process";import rf from"node:fs/promises";import{promisify as Jv}from"node:util";var Wv,is,ze,Xl=y(()=>{"use strict";Mi();Wv=Jv(zv),is={tools:new Map,register(r,e){this.tools.set(r,e)},get(r){return this.tools.get(r)},isAllowed(r,e){return!e||e.length===0?!0:e.some(t=>t.endsWith("*")?r.startsWith(t.slice(0,-1)):r===t)},list(){return Array.from(this.tools.keys())}};is.register("Read",async r=>{try{return await Xr.execute(async()=>await rf.readFile(r,"utf-8"),`read-${r}`)}catch(e){return $i(e)||Kr(e),null}});is.register("Write",async(r,e)=>{try{return await Xr.execute(async()=>await rf.writeFile(r,e,"utf-8"),`write-${r}`),!0}catch(t){return $i(t)||Kr(t),!1}});is.register("Bash",async r=>{try{return await Xr.execute(async()=>await Wv(r),`bash-${r}`)}catch(e){let t=e;return{stdout:t.stdout||"",stderr:t.stderr||t.message||"Command failed"}}});is.register("GetTimestamp",async()=>new Date().toISOString());is.register("GetDate",async()=>new Date().toISOString().split("T")[0]);is.register("GetDateTime",async()=>new Date().toISOString());ze=is});import Yl from"node:fs/promises";import Bv from"node:os";import of from"node:path";async function Vv(r){try{let e=of.dirname(Fi);await C(e)||await Yl.mkdir(e,{recursive:!0}),await Yl.writeFile(Fi,`/p:${r}`)}catch{}}async function qv(){try{await C(Fi)&&await Yl.unlink(Fi)}catch{}}var Fi,Ql,Kv,Oi,Zl=y(()=>{"use strict";M();cm();me();pm();mm();Fc();Tm();Em();Vs();$l();jg();Zg();ql();Yn();Xl();Fi=of.join(Bv.homedir(),".prjct-cli",".running");l(Vv,"signalStart");l(qv,"signalEnd");Ql=class{static{l(this,"CommandExecutor")}async signalStart(e){await Vv(e)}async signalEnd(){await qv()}async execute(e,t,n){await this.signalStart(e);let s=t.task||t.description||"";if(Js.shouldEscalate(e,s)){let o=Js.getEscalationInfo(e,s);return await this.signalEnd(),{success:!1,error:o?.message,escalation:o,isLoopDetected:!0,suggestion:o?.suggestion}}try{let o=await Ic.load(e),i=await rt.build(n,t),a=Fe.requiresPlanning(e),c=Fe.isDestructive(e),u=Fe.isInPlanningMode(i.projectId),p=null;a&&!u&&!t.skipPlanning?p=Fe.startPlanning(i.projectId,e,t):u&&(p=Fe.getActivePlan(i.projectId));let m=null;if(pi.requiresVerification(e)){let v=await rt.loadStateForCommand(i,e);m=await pi.verify(e,i,v),!m.verified&&m.warnings.length>0&&console.log(pi.formatWarnings(m))}let d=null;if(ui.requiresReasoning(e)){let v=await rt.loadStateForCommand(i,e);d=await ui.reason(e,i,v),d.reasoning&&!d.reasoning.allPassed&&(console.log("\u26A0\uFE0F Chain of Thought detected issues:"),console.log(ui.formatPlan(d)))}let g=t.task||t.description||"",f=await Di.buildContext(e,g,n),S=Di.buildAgenticPrompt(f),E=null;if(Di.requiresOrchestration(e)&&g)try{E=await Ci.execute(e,g,n),E.detectedDomains.length>0&&li.orchestrate(E.detectedDomains);for(let v of E.agents){let D=v.domain||v.name.replace(".md","");li.startAgent(v.name,D,`Loading ${D} specialist...`),li.endAgent(!0)}if(E.requiresFragmentation&&E.subtasks){let v=E.subtasks.map(D=>({id:D.id,domain:D.domain,description:D.description,status:D.status}));um(v)}}catch(v){console.warn(`\u26A0\uFE0F Orchestrator warning: ${w(v)}`)}let x={...i,agentsPath:f.paths.agentsDir,agentRoutingPath:f.paths.agentRouting,orchestratorPath:f.paths.orchestrator,taskFragmentationPath:f.paths.taskFragmentation,agenticDelegation:!0,agenticMode:!0},$=await rt.loadState(i),z=null,_e=null;i.projectId&&(z={commit_footer:await Ce.getSmartDecision(i.projectId,"commit_footer"),branch_naming:await Ce.getSmartDecision(i.projectId,"branch_naming"),test_before_ship:await Ce.getSmartDecision(i.projectId,"test_before_ship"),preferred_agent:await Ce.getSmartDecision(i.projectId,`preferred_agent_${e}`)},_e=await Ce.getRelevantMemories(i.projectId,{commandName:e,params:t},5));let nt={isPlanning:a||u,requiresApproval:c&&!t.approved,active:p,allowedTools:Fe.getAllowedTools(u,o.frontmatter["allowed-tools"]||[])},Dt=await Qg.build(o,x,$,null,z,null,_e,nt,E);return console.log("\u{1F916} Template-first execution: Claude reads templates and decides"),S.requiresOrchestration&&console.log(` \u2192 Orchestration: ${f.paths.orchestrator}`),Js.recordSuccess(e,s),await this.signalEnd(),{success:!0,template:o,context:x,state:$,prompt:Dt,agenticDelegation:!0,agenticMode:!0,agenticExecContext:f,agenticPrompt:S.prompt,requiresOrchestration:S.requiresOrchestration,agentsPath:x.agentsPath,agentRoutingPath:x.agentRoutingPath,orchestratorPath:f.paths.orchestrator,taskFragmentationPath:f.paths.taskFragmentation,reasoning:d,groundTruth:m,learnedPatterns:z,relevantMemories:_e,orchestratorContext:E,memory:{create:l(v=>Ce.createMemory(i.projectId,v),"create"),autoRemember:l((v,D,Re)=>Ce.autoRemember(i.projectId,v,D,Re),"autoRemember"),search:l(v=>Ce.searchMemories(i.projectId,v),"search"),findByTags:l(v=>Ce.findByTags(i.projectId,v),"findByTags"),getStats:l(()=>Ce.getMemoryStats(i.projectId),"getStats")},plan:{active:p,isPlanning:a||u,isDestructive:c,requiresApproval:c&&!t.approved,recordInfo:l(v=>Fe.recordGatheredInfo(i.projectId,v),"recordInfo"),setAnalysis:l(v=>Fe.setAnalysis(i.projectId,v),"setAnalysis"),propose:l(v=>Fe.proposePlan(i.projectId,v),"propose"),approve:l(v=>Fe.approvePlan(i.projectId,v),"approve"),reject:l(v=>Fe.rejectPlan(i.projectId,v),"reject"),getApprovalPrompt:l(()=>Fe.generateApprovalPrompt(e,{changedFiles:[],filesToDelete:[],operation:e==="ship"?"git_push":e==="cleanup"?"delete_files":"run_command",warnings:[]}),"getApprovalPrompt"),startExecution:l(()=>Fe.startExecution(i.projectId),"startExecution"),getNextStep:l(()=>Fe.getNextStep(i.projectId),"getNextStep"),completeStep:l(v=>Fe.completeStep(i.projectId,v),"completeStep"),failStep:l(v=>Fe.failStep(i.projectId,v),"failStep"),abort:l(v=>Fe.abortPlan(i.projectId,v),"abort"),getStatus:l(()=>Fe.formatStatus(i.projectId),"getStatus"),getAllowedTools:l(()=>Fe.getAllowedTools(u,o.frontmatter["allowed-tools"]||[]),"getAllowedTools")}}}catch(o){await this.signalEnd();let i=Js.recordAttempt(e,s,{success:!1,error:w(o)});if(i.shouldEscalate){let a=Js.getEscalationInfo(e,s);return{success:!1,error:a?.message,escalation:a,isLoopDetected:!0,suggestion:a?.suggestion}}return{success:!1,error:w(o),attemptNumber:i.attemptNumber,isLooping:i.isLooping}}}async executeTool(e,t,n){if(!ze.isAllowed(e,n))throw new Error(`Tool ${e} not allowed for this command`);let s=ze.get(e);if(!s)throw new Error(`Tool ${e} not found`);return await s(...t)}async executeSimple(e,t,n){try{let o=(await Ic.load(e)).frontmatter["allowed-tools"]||[],i=await rt.build(n);return{success:!0,result:await t({read:l(async u=>this.executeTool("Read",[u],o),"read"),write:l(async(u,p)=>this.executeTool("Write",[u,p],o),"write"),bash:l(async u=>this.executeTool("Bash",[u],o),"bash")},i)}}catch(s){return{success:!1,error:w(s)}}}},Kv=new Ql,Oi=Kv});import _i from"node:fs/promises";import Xv from"node:https";import Yv from"node:os";import eu from"node:path";import Ht from"chalk";var tu,af,cf=y(()=>{"use strict";M();me();tu=class{static{l(this,"UpdateChecker")}packageName;cacheDir;cacheFile;checkInterval;constructor(){this.packageName="prjct-cli",this.cacheDir=eu.join(Yv.homedir(),".prjct-cli","config"),this.cacheFile=eu.join(this.cacheDir,"update-cache.json"),this.checkInterval=1440*60*1e3}async getCurrentVersion(){try{let e=eu.join(__dirname,"..","..","package.json");return JSON.parse(await _i.readFile(e,"utf8")).version}catch(e){return console.error("Error reading package version:",w(e)),null}}async getLatestVersion(){return new Promise((e,t)=>{let n={hostname:"registry.npmjs.org",path:`/${this.packageName}/latest`,method:"GET",headers:{"User-Agent":"prjct-cli-update-checker",Accept:"application/json"}},s=Xv.request(n,o=>{let i="";o.on("data",a=>{i+=a}),o.on("end",()=>{try{if(o.statusCode===200){let a=JSON.parse(i);e(a.version)}else t(new Error(`npm registry returned status ${o.statusCode}`))}catch(a){t(a)}})});s.on("error",o=>{t(o)}),s.setTimeout(5e3,()=>{s.destroy(),t(new Error("Request timeout"))}),s.end()})}compareVersions(e,t){let n=e.split(".").map(Number),s=t.split(".").map(Number);for(let o=0;o<3;o++){let i=n[o]||0,a=s[o]||0;if(i>a)return 1;if(i<a)return-1}return 0}async readCache(){try{if(await C(this.cacheFile))return JSON.parse(await _i.readFile(this.cacheFile,"utf8"))}catch{}return null}async writeCache(e){try{await C(this.cacheDir)||await _i.mkdir(this.cacheDir,{recursive:!0}),await _i.writeFile(this.cacheFile,JSON.stringify(e,null,2),"utf8")}catch{}}async checkForUpdates(){try{let e=await this.getCurrentVersion();if(!e)return null;let t=await this.readCache(),n=Date.now();if(t?.lastCheck&&n-t.lastCheck<this.checkInterval)return t.latestVersion&&this.compareVersions(t.latestVersion,e)>0?{updateAvailable:!0,currentVersion:e,latestVersion:t.latestVersion}:{updateAvailable:!1,currentVersion:e,latestVersion:e};let s=await this.getLatestVersion();return await this.writeCache({lastCheck:n,latestVersion:s}),{updateAvailable:this.compareVersions(s,e)>0,currentVersion:e,latestVersion:s}}catch{return null}}async getUpdateNotification(){let e=await this.checkForUpdates();return!e||!e.updateAvailable?null:`
858
- `+Ht.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")+`
859
- `+Ht.yellow("\u2502")+" "+Ht.bold("Update available!")+" "+Ht.dim(`${e.currentVersion} \u2192 ${e.latestVersion}`)+" "+Ht.yellow("\u2502")+`
860
- `+Ht.yellow("\u2502")+" "+Ht.yellow("\u2502")+`
861
- `+Ht.yellow("\u2502")+" Run: "+Ht.cyan("npm update -g prjct-cli")+" "+Ht.yellow("\u2502")+`
862
- `+Ht.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")+`
863
- `}},af=tu});function Qv(){return/<!-- prjct:preserve(?::([\w-]+))? -->/g}function Zv(r){let e=[],t=Qv(),n,s=0;for(;(n=t.exec(r))!==null;){let o=n.index,i=n[0],a=n[1]||`section-${s++}`,c=r.indexOf(nu,o+i.length);if(c===-1)continue;let u=c+nu.length,p=r.substring(o,u);e.push({id:a,content:p,startIndex:o,endIndex:u})}return e}function Yr(r,e){let t=Zv(e);if(t.length===0)return r;let n=r.trimEnd();n+=`
864
-
865
- ---
866
-
867
- `,n+=`## Your Customizations
868
-
869
- `,n+=`_The sections below are preserved during sync. Edit freely._
870
-
871
- `;for(let s of t)n+=s.content,n+=`
872
-
873
- `;return`${n.trimEnd()}
874
- `}function Qr(r){let e=[],t=r.match(/<!-- prjct:preserve(?::\w+)? -->/g)||[],n=r.match(/<!-- \/prjct:preserve -->/g)||[];t.length!==n.length&&e.push(`Mismatched preserve markers: ${t.length} opening, ${n.length} closing`);let s=0,o=0,i=r.split(`
875
- `);for(let a=0;a<i.length;a++){let c=i[a];/<!-- prjct:preserve(?::\w+)? -->/.test(c)&&(s++,o=Math.max(o,s)),c.includes(nu)&&s--,s>1&&e.push(`Nested preserve blocks detected at line ${a+1} (not supported)`),s<0&&e.push(`Unexpected closing marker at line ${a+1}`)}return{valid:e.length===0,errors:e}}var nu,Ni=y(()=>{"use strict";nu="<!-- /prjct:preserve -->";l(Qv,"createPreserveStartRegex");l(Zv,"extractPreservedSections");l(Yr,"mergePreservedSections");l(Qr,"validatePreserveBlocks")});var lf=y(()=>{"use strict";Ni();Mi()});import Li from"node:fs/promises";import su from"node:path";var ru,uf,pf=y(()=>{"use strict";Ye();ee();M();ru=class{static{l(this,"AgentRouter")}projectId=null;projectPath=null;agentsPath=null;async initialize(e){this.projectId=await I.getProjectId(e),this.projectPath=e,this.agentsPath=P.getFilePath(this.projectId,"agents","")}async loadAvailableAgents(){if(!this.agentsPath)return[];try{let e=await Li.readdir(this.agentsPath),t=[];for(let n of e)if(n.endsWith(".md")){let s=n.replace(".md",""),o=await Li.readFile(su.join(this.agentsPath,n),"utf-8");t.push({name:s,content:o})}return t}catch(e){return k(e)||console.error(`Agent loading error: ${w(e)}`),[]}}async getAgentNames(){return(await this.loadAvailableAgents()).map(t=>t.name)}async loadAgent(e){if(!this.agentsPath)return null;try{let t=su.join(this.agentsPath,`${e}.md`),n=await Li.readFile(t,"utf-8");return{name:e,content:n}}catch(t){return k(t)||console.error(`Agent load error: ${w(t)}`),null}}async buildAssignmentContext(e,t){let n=await this.getAgentNames();return{task:typeof e=="string"?e:e.description||"",availableAgents:n,projectPath:t,projectId:this.projectId,_template:"templates/agent-assignment.md"}}async logUsage(e,t,n){try{let s=su.join(process.env.HOME||"",".prjct-cli","projects",this.projectId||"","agent-usage.jsonl"),o=`${JSON.stringify({timestamp:new Date().toISOString(),task:typeof e=="string"?e:e.description,agent:typeof t=="string"?t:t.name,projectId:this.projectId})}
876
- `;await Li.appendFile(s,o)}catch(s){k(s)||console.error(`Agent usage log error: ${w(s)}`)}}},uf=ru});import df from"node:path";async function nx(){if(process.env.CLAUDE_AGENT||process.env.ANTHROPIC_CLAUDE||global.mcp||process.env.MCP_AVAILABLE)return!0;let r=process.cwd();if(await C(df.join(r,"CLAUDE.md")))return!0;let e=process.env.HOME||process.env.USERPROFILE||"";if(await C(df.join(e,".claude")))return!0;let t=process.cwd();return!!(t.includes("/.claude/")||t.includes("/claude-workspace/"))}function sx(){return{...ex}}function rx(){return{...tx}}async function mf(){return Ui||(Ui=await nx()?sx():rx(),Ui)}var Ui,ex,tx,gf=y(()=>{"use strict";me();Ui=null,ex={type:"claude",name:"Claude (Code + Desktop)",isSupported:!0,capabilities:{mcp:!0,filesystem:"mcp",markdown:!0,emojis:!0,colors:!0,interactive:!0,agents:!0},config:{configFile:"CLAUDE.md",commandPrefix:"/p:",responseStyle:"rich",dataDir:".prjct",agentsDir:"~/.claude/agents",commandsDir:"~/.claude/commands/p"},environment:{hasMCP:!0,sandboxed:!1,persistent:!0,agentSystem:!0}},tx={type:"terminal",name:"Terminal/CLI",isSupported:!0,capabilities:{mcp:!1,filesystem:"native",markdown:!1,emojis:!0,colors:!0,interactive:!0,agents:!1},config:{configFile:null,commandPrefix:"prjct",responseStyle:"cli",dataDir:".prjct",agentsDir:null,commandsDir:null},environment:{hasMCP:!1,sandboxed:!1,persistent:!0,agentSystem:!1}};l(nx,"isClaudeEnvironment");l(sx,"getClaudeAgent");l(rx,"getTerminalAgent");l(mf,"detect")});var ix,ou=y(()=>{ix=Ep({})});var ax,Hi,Ys,ff=y(()=>{"use strict";pf();an();gf();Mi();ou();ax=["claude"],Hi=class{static{l(this,"AgentService")}agent=null;agentInfo=null;agentRouter;constructor(){this.agentRouter=new uf}async initialize(){return this.agent?this.agent:await sf.execute(async()=>{if(this.agentInfo=await mf(),!this.agentInfo?.isSupported)throw Sr.notSupported(this.agentInfo?.type??"unknown");let e=this.agentInfo.type;if(!e||!ax.includes(e))throw Sr.notSupported(this.agentInfo?.type??"unknown");let{default:t}=await ix(`../infrastructure/${e}-agent`);return this.agent=new t,this.agent},"agent-initialization")}getInfo(){return this.agentInfo}getAgent(){return this.agent}isInitialized(){return this.agent!==null}async assignForTask(e,t,n){try{await this.agentRouter.initialize(t);let s=await this.agentRouter.getAgentNames();return s.length===0?{agent:null,routing:{confidence:0,reason:'No specialized agents available. Run "p. sync" to generate agents.',availableAgents:[]},_agenticNote:"AGENTIC: Claude reads orchestrator.md and decides how to proceed"}:{agent:null,routing:{confidence:0,reason:"AGENTIC: Claude will analyze task and select appropriate specialist agents",availableAgents:s},_agenticNote:`
877
- AGENTIC EXECUTION:
878
- - Read: templates/agentic/orchestrator.md
879
- - Analyze task: "${e}"
880
- - Available specialists: ${s.join(", ")}
881
- - Claude decides which agent(s) to use
882
- - Always prefer specialists over generalist
883
- - Fragment complex tasks into subtasks
884
- `}}catch{return{agent:null,routing:{confidence:0,reason:'Agent routing unavailable - run "p. sync" first',availableAgents:[]},_agenticNote:"AGENTIC: Suggest running p. sync to generate agents"}}}async getAvailableAgents(e){try{return await this.agentRouter.initialize(e),await this.agentRouter.getAgentNames()}catch{return[]}}reset(){this.agent=null,this.agentInfo=null}},Ys=new Hi});var Gi,zi,hf=y(()=>{"use strict";Gi=class{static{l(this,"BreakdownService")}breakdownFeature(e){return[`Analyze and plan: ${e}`,"Implement core functionality","Test and validate","Document changes"]}detectBugSeverity(e){let t=e.toLowerCase();return t.includes("crash")||t.includes("data loss")||t.includes("security")||t.includes("production down")?"critical":t.includes("broken")||t.includes("not working")||t.includes("error")||t.includes("blocking")?"high":t.includes("minor")||t.includes("cosmetic")||t.includes("typo")||t.includes("polish")?"low":"medium"}estimateComplexity(e){let t=e.split(/\s+/).length;return["refactor","migrate","redesign","overhaul","rewrite","integration","authentication","authorization"].some(o=>e.toLowerCase().includes(o))||t>30?{level:"high",hours:8}:t>10?{level:"medium",hours:4}:{level:"low",hours:1}}detectTaskType(e){let t=e.toLowerCase();return t.includes("bug")||t.includes("fix")||t.includes("error")?"bug":t.includes("refactor")||t.includes("improve")||t.includes("optimize")||t.includes("cleanup")?"improvement":t.includes("update")||t.includes("deps")||t.includes("config")||t.includes("chore")?"chore":"feature"}},zi=new Gi});var yf,cx,Ji,lx,wf=y(()=>{"use strict";Wr();yf=8e4,cx={payments:["payment","pay","stripe","billing","checkout","invoice","subscription","charge","refund","transaction","pricing","price"],auth:["auth","login","logout","signup","sign up","sign in","register","password","session","token","jwt","oauth","sso","permission","role","access","user"],api:["api","endpoint","route","rest","graphql","webhook","request","response","http","fetch","axios"],database:["database","db","model","schema","migration","query","sql","prisma","drizzle","mongoose","sequelize","typeorm"],frontend:["component","page","view","ui","button","form","modal","layout","style","css","react","vue","svelte","html"],testing:["test","spec","unit","e2e","cypress","jest","vitest","mocha","coverage","mock"],integrations:["integration","integrate","connect","sync","webhook","oauth","linear","jira","github","slack","discord"],config:["config","configuration","setting","env","environment","setup"],utilities:["util","utility","helper","lib","common","shared","tool"],services:["service","handler","processor","worker","job","queue","cron"],types:["type","interface","dto","schema","definition"]},Ji=class{static{l(this,"ContextSelector")}CHARS_PER_TOKEN=4;async selectForTask(e,t,n={}){let s=n.maxFiles||50,o=n.minScore||30,i=n.includeGeneral!==!1,a=n.tokenBudget||yf,[c,u,p]=await Promise.all([Ve.readIndex(t),Ve.readDomains(t),Ve.readCategories(t)]);if(!c||!u||!p)return this.fallbackSelection(c?.relevantFiles||[],n);let m=this.detectTaskDomains(e,u.domains),d=new Set;for(let $ of m){let z=p.domainIndex[$]||[];for(let _e of z)d.add(_e)}if(i&&p.domainIndex.general){let $=p.domainIndex.general.slice(0,10);for(let z of $)d.add(z)}let g=c.relevantFiles.filter($=>d.has($.path)&&$.score>=o);g.sort(($,z)=>z.score-$.score);let f=0,S=[];for(let $ of g){let z=Math.ceil($.size/this.CHARS_PER_TOKEN);if(f+z>a||S.length>=s)break;S.push($),f+=z}let E=Math.ceil(c.relevantFiles.reduce(($,z)=>$+z.size,0)/this.CHARS_PER_TOKEN),x=E>0?(E-f)/E:0;return{files:S,domains:m,metrics:{totalFiles:c.relevantFiles.length,selectedFiles:S.length,compressionRate:x,estimatedTokensSaved:E-f}}}detectTaskDomains(e,t){let n=e.toLowerCase(),s=new Set;for(let[o,i]of Object.entries(cx))for(let a of i)if(n.includes(a)){s.add(o);break}for(let o of t){if(n.includes(o.name.toLowerCase())){s.add(o.name);continue}for(let i of o.keywords)if(n.includes(i.toLowerCase())){s.add(o.name);break}}return s.size===0&&(s.add("services"),s.add("api")),Array.from(s)}async filterByDomains(e,t,n){let s=await Ve.readCategories(e);if(!s)return n||[];let o=new Set;for(let a of t){let c=s.domainIndex[a]||[];for(let u of c)o.add(u)}if(n)return n.filter(a=>o.has(a.path));let i=await Ve.readIndex(e);return i?i.relevantFiles.filter(a=>o.has(a.path)):[]}async getFilesDomains(e,t){return Ve.getFileCategories(e,t)}fallbackSelection(e,t){let n=t.maxFiles||50,s=t.minScore||30,o=t.tokenBudget||yf,i=e.filter(p=>p.score>=s).sort((p,m)=>m.score-p.score),a=0,c=[];for(let p of i){let m=Math.ceil(p.size/this.CHARS_PER_TOKEN);if(a+m>o||c.length>=n)break;c.push(p),a+=m}let u=Math.ceil(e.reduce((p,m)=>p+m.size,0)/this.CHARS_PER_TOKEN);return{files:c,domains:[],metrics:{totalFiles:e.length,selectedFiles:c.length,compressionRate:u>0?(u-a)/u:0,estimatedTokensSaved:u-a}}}suggestRelatedDomains(e){let t=new Set,n={payments:["api","database","services"],auth:["api","database","users"],api:["services","types"],database:["types","services"],frontend:["types","utilities"],testing:["services","api"]};for(let s of e){let o=n[s];if(o)for(let i of o)e.includes(i)||t.add(i)}return Array.from(t)}},lx=new Ji});import kf from"node:path";var iu,Wi,ux,Sf=y(()=>{"use strict";Wr();ne();iu=[{pattern:/\b(payment|stripe|billing|checkout|invoice)/i,domain:"payments"},{pattern:/\b(auth|login|signup|user|session|password|oauth)/i,domain:"auth"},{pattern:/\b(api|endpoint|route|controller)/i,domain:"api"},{pattern:/\b(model|schema|migration|database|db|prisma|drizzle)/i,domain:"database"},{pattern:/\b(component|page|view|layout|ui|button|form|modal)/i,domain:"frontend"},{pattern:/\b(test|spec|__tests__|e2e|cypress)/i,domain:"testing"},{pattern:/\b(config|setting|env)/i,domain:"config"},{pattern:/\b(util|helper|lib|common|shared)/i,domain:"utilities"},{pattern:/\b(service|handler|processor|worker)/i,domain:"services"},{pattern:/\b(type|interface|dto)/i,domain:"types"}],Wi=class{static{l(this,"FileCategorizer")}batchSize;maxDomains;constructor(e={}){this.batchSize=e.batchSize||20,this.maxDomains=e.maxDomains||15}async analyzeProject(e,t,n={}){let s=n.useLLM!==!1,o=s?await this.discoverDomainsWithLLM(e,t):this.discoverDomainsHeuristic(t),i=s?await this.categorizeFilesWithLLM(t,o):this.categorizeFilesHeuristic(t,o);for(let a of o)a.fileCount=i.filter(c=>c.primaryDomain===a.name).length;return n.projectId&&await this.saveToCache(n.projectId,o,i),{domains:o,categories:i,metrics:{totalFiles:t.length,categorizedFiles:i.length,domainsDiscovered:o.length,llmCalls:s?Math.ceil(t.length/this.batchSize)+1:0,usedHeuristics:!s}}}async discoverDomainsWithLLM(e,t){return this.discoverDomainsHeuristic(t)}async categorizeFilesWithLLM(e,t){return this.categorizeFilesHeuristic(e,t)}discoverDomainsHeuristic(e){let t=new Map,n=new Map;for(let i of e){let a=i.path.toLowerCase();for(let{pattern:c,domain:u}of iu)if(c.test(a)){t.set(u,(t.get(u)||0)+1),n.has(u)||n.set(u,new Set);let p=kf.dirname(i.path);n.get(u).add(`**/${kf.basename(p)}/**`)}}let s=this.extractDirectoryDomains(e);for(let[i,a]of s)t.set(i,(t.get(i)||0)+a);let o=[];for(let[i,a]of t)if(a>=2){let c=iu.find(u=>u.domain===i);o.push({name:i,description:`Files related to ${i}`,keywords:c?[i]:[i],filePatterns:Array.from(n.get(i)||[]),fileCount:a})}return o.sort((i,a)=>a.fileCount-i.fileCount).slice(0,this.maxDomains)}extractDirectoryDomains(e){let t=new Map;for(let n of e){let s=n.path.split("/");for(let o of s.slice(0,-1)){let i=o.toLowerCase();["src","lib","app","core","dist","build"].includes(i)||i.length>2&&!i.startsWith(".")&&t.set(i,(t.get(i)||0)+1)}}return t}categorizeFilesHeuristic(e,t){let n=[],s=b();for(let o of e){let i=[],a=o.path.toLowerCase();for(let m of t){let d=0;for(let g of m.keywords)a.includes(g.toLowerCase())&&(d+=1);for(let{pattern:g,domain:f}of iu)f===m.name&&g.test(a)&&(d+=2);for(let g of m.filePatterns){let f=g.replace(/\*\*/g,"").replace(/\//g,"");a.includes(f.toLowerCase())&&(d+=1)}d>0&&i.push({domain:m.name,score:d})}i.sort((m,d)=>d.score-m.score);let c=i.length>0?i.slice(0,3).map(m=>m.domain):["general"],u=c[0],p=i.length>0?Math.min(1,i[0].score/5):.1;n.push({path:o.path,categories:c,primaryDomain:u,confidence:p,categorizedAt:s,method:"heuristic"})}return n}async saveToCache(e,t,n){let s=b(),o={version:Lt,projectId:e,domains:t,discoveredAt:s};await Ve.writeDomains(e,o);let i={};for(let c of n)for(let u of c.categories)i[u]||(i[u]=[]),i[u].push(c.path);let a={version:Lt,lastUpdate:s,fileCategories:n,domainIndex:i};await Ve.writeCategories(e,a)}async loadFromCache(e){let[t,n]=await Promise.all([Ve.readDomains(e),Ve.readCategories(e)]);return!t||!n?null:{domains:t.domains,categories:n.fileCategories,metrics:{totalFiles:n.fileCategories.length,categorizedFiles:n.fileCategories.length,domainsDiscovered:t.domains.length,llmCalls:0,usedHeuristics:n.fileCategories[0]?.method==="heuristic"}}}async updateFilesCategories(e,t,n={}){let s=await Ve.readDomains(e);if(!s)return(await this.analyzeProject("",t,{...n,projectId:e})).categories;let o=n.useLLM!==!1?await this.categorizeFilesWithLLM(t,s.domains):this.categorizeFilesHeuristic(t,s.domains),i=await Ve.readCategories(e);if(i){let a=new Set(t.map(d=>d.path)),u=[...i.fileCategories.filter(d=>!a.has(d.path)),...o],p={};for(let d of u)for(let g of d.categories)p[g]||(p[g]=[]),p[g].push(d.path);let m={version:Lt,lastUpdate:b(),fileCategories:u,domainIndex:p};await Ve.writeCategories(e,m)}return o}},ux=new Wi});import au from"node:path";var cu,px,dx,Bi,bf,lu=y(()=>{"use strict";cu=30,px=[/^package\.json$/,/^tsconfig.*\.json$/,/^\.env(\..*)?$/,/^\.eslintrc.*$/,/^\.prettierrc.*$/,/^vite\.config\.\w+$/,/^next\.config\.\w+$/,/^webpack\.config\.\w+$/,/^rollup\.config\.\w+$/,/^jest\.config\.\w+$/,/^vitest\.config\.\w+$/,/^tailwind\.config\.\w+$/,/^postcss\.config\.\w+$/,/^Cargo\.toml$/,/^go\.mod$/,/^pyproject\.toml$/,/^requirements\.txt$/,/^Dockerfile$/,/^docker-compose\.ya?ml$/,/^\.github\/workflows\/.*\.ya?ml$/],dx=[/^index\.\w+$/,/^main\.\w+$/,/^app\.\w+$/,/^server\.\w+$/,/^router\.\w+$/,/^routes\.\w+$/,/^api\.\w+$/,/^schema\.\w+$/,/^types?\.\w+$/,/^constants?\.\w+$/,/^config\.\w+$/,/^utils?\.\w+$/,/^helpers?\.\w+$/,/README\.md$/i,/CHANGELOG\.md$/i],Bi=class{static{l(this,"FileScorer")}scoreFile(e,t){let n={recency:this.calculateRecency(e,t),centrality:this.calculateCentrality(e,t),configRelevance:this.calculateConfigRelevance(e),nameRelevance:this.calculateNameRelevance(e),sizeOptimal:this.calculateSizeOptimal(e,t),gitActivity:this.calculateGitActivity(e,t)},s=Object.values(n).reduce((o,i)=>o+i,0);return{path:e.path,score:Math.min(100,Math.max(0,s)),factors:n}}scoreAll(e){let t=[];for(let n of e.allFiles.values())t.push(this.scoreFile(n,e));return t.sort((n,s)=>s.score-n.score)}getRelevantFiles(e,t=cu){return this.scoreAll(e).filter(n=>n.score>=t)}calculateRecency(e,t){let n=(t.now.getTime()-e.mtime.getTime())/864e5;return n<1?20:n<7?15:n<30?10:n<90?5:0}calculateCentrality(e,t){let n=e.importedBy?.length||0,s=t.allFiles.size;if(s===0)return 0;let o=n/s;return o>=.2?25:o>=.1?20:o>=.05?15:n>=5?10:n>=2?5:0}calculateConfigRelevance(e){let t=au.basename(e.path);for(let n of px)if(n.test(t)||n.test(e.path))return 20;return 0}calculateNameRelevance(e){let t=au.basename(e.path);for(let s of dx)if(s.test(t))return 15;let n=au.dirname(e.path);return n.includes("/api/")||n.includes("/routes/")||n.includes("/components/")&&t.startsWith("index")?10:n.includes("/pages/")||n.includes("/app/")?8:0}calculateSizeOptimal(e,t){let n=e.size;return n<100?2:n>=500&&n<=5e4?10:n>5e4&&n<=2e5?5:n>2e5?0:5}calculateGitActivity(e,t){let n=e.recentCommits||0;if(t.maxRecentCommits===0)return 0;let s=n/t.maxRecentCommits;return s>=.5?10:s>=.25?7:s>=.1?5:n>0?2:0}},bf=new Bi});import{execSync as uu}from"node:child_process";var Vi,pu,qi,Qs,Ki=y(()=>{"use strict";jr();Vi={git:{name:"git",command:"git --version",versionRegex:/git version ([\d.]+)/,required:!0,installHint:"Install Git: https://git-scm.com/downloads",docs:"https://git-scm.com/doc"},node:{name:"node",command:"node --version",versionRegex:/v([\d.]+)/,required:!0,installHint:"Install Node.js: https://nodejs.org",docs:"https://nodejs.org/docs"},bun:{name:"bun",command:"bun --version",versionRegex:/([\d.]+)/,required:!1,installHint:"Install Bun: curl -fsSL https://bun.sh/install | bash",docs:"https://bun.sh/docs"},gh:{name:"gh",command:"gh --version",versionRegex:/gh version ([\d.]+)/,required:!1,installHint:"Install GitHub CLI: https://cli.github.com",docs:"https://cli.github.com/manual"},npm:{name:"npm",command:"npm --version",versionRegex:/([\d.]+)/,required:!1,installHint:"npm comes with Node.js: https://nodejs.org"},claude:{name:"claude",command:"claude --version",versionRegex:/claude ([\d.]+)/,required:!1,installHint:"Install Claude Code: npm install -g @anthropic-ai/claude-code",docs:"https://docs.anthropic.com/claude-code"},gemini:{name:"gemini",command:"gemini --version",versionRegex:/gemini ([\d.]+)/,required:!1,installHint:"Install Gemini CLI: npm install -g @google/gemini-cli",docs:"https://ai.google.dev/gemini-api/docs"}},pu=class{static{l(this,"DependencyValidator")}cache=new Map;cacheTimeout=6e4;cacheTimestamps=new Map;checkTool(e){let t=this.getCached(e);if(t)return t;let n=Vi[e];if(!n)return this.checkUnknownTool(e);let s=this.executeCheck(n);return this.setCache(e,s),s}ensureTool(e){let t=this.checkTool(e);if(!t.available){let n=Vi[e],s=t.error||{message:`${e} is not available`,hint:n?.installHint||`Install ${e} and try again`,docs:n?.docs};throw new qi(s)}}ensureTools(e){let t=[];for(let n of e)this.checkTool(n).available||t.push(n);if(t.length>0){let n=t.map(s=>{let o=Vi[s];return o?` ${s}: ${o.installHint}`:` ${s}: Install and try again`}).join(`
885
- `);throw new qi({message:`Missing required tools: ${t.join(", ")}`,hint:`Install the following:
886
- ${n}`})}}isAvailable(e){return this.checkTool(e).available}getVersion(e){return this.checkTool(e).version}checkAll(e){let t=e||Object.keys(Vi),n=new Map;for(let s of t)n.set(s,this.checkTool(s));return n}clearCache(){this.cache.clear(),this.cacheTimestamps.clear()}executeCheck(e){try{let t=uu(e.command,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}),n;if(e.versionRegex){let s=t.match(e.versionRegex);n=s?s[1]:void 0}return{available:!0,version:n}}catch{return{available:!1,error:Er(`${e.name} is not installed or not in PATH`,e.installHint,{docs:e.docs})}}}checkUnknownTool(e){try{return uu(`${e} --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}),{available:!0}}catch{try{return uu(`${e} -v`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}),{available:!0}}catch{return{available:!1,error:Er(`${e} is not installed or not in PATH`,`Install ${e} and try again`)}}}}getCached(e){let t=this.cacheTimestamps.get(e);return t?Date.now()-t>this.cacheTimeout?(this.cache.delete(e),this.cacheTimestamps.delete(e),null):this.cache.get(e)||null:null}setCache(e,t){this.cache.set(e,t),this.cacheTimestamps.set(e,Date.now())}},qi=class extends Error{static{l(this,"DependencyError")}hint;docs;constructor(e){super(e.message),this.name="DependencyError",this.hint=e.hint,this.docs=e.docs}},Qs=new pu});import{exec as mx}from"node:child_process";import{promisify as gx}from"node:util";var T1,Pf=y(()=>{"use strict";Kt();Ki();T1=gx(mx)});var Xi,at,du=y(()=>{"use strict";Ye();ee();Rn();M();ne();Ar();Xi=class{static{l(this,"MemoryService")}async log(e,t,n,s){try{let o=await I.getProjectId(e);if(!o)return;let i=P.getFilePath(o,"memory","context.jsonl"),a={timestamp:b(),action:t,data:n,author:s};await Ds(i,a)}catch(o){k(o)||console.error(`Memory log error: ${w(o)}`)}}async getRecent(e,t=100){try{let n=await I.getProjectId(e);if(!n)return[];let s=P.getFilePath(n,"memory","context.jsonl");return(await ln(s)).slice(-t)}catch(n){return!k(n)&&!(n instanceof SyntaxError)&&console.error(`Memory read error: ${w(n)}`),[]}}async search(e,t,n=50){let s=await this.getRecent(e,1e3),o=t.toLowerCase();return s.filter(i=>{let a=i.action.toLowerCase().includes(o),c=JSON.stringify(i.data).toLowerCase().includes(o);return a||c}).slice(-n)}async getByAction(e,t,n=50){return(await this.getRecent(e,1e3)).filter(o=>o.action===t).slice(-n)}async clear(e){try{let t=await I.getProjectId(e);if(!t)return;let n=P.getFilePath(t,"memory","context.jsonl");await Jo(n,[])}catch(t){k(t)||console.error(`Memory clear error: ${w(t)}`)}}async getRecentEvents(e,t=100){try{let n=P.getFilePath(e,"memory","context.jsonl");return(await ln(n)).slice(-t)}catch(n){return!k(n)&&!(n instanceof SyntaxError)&&console.error(`Memory read error: ${w(n)}`),[]}}async capEntries(e){try{let t=P.getFilePath(e,"memory","context.jsonl"),n=await ln(t);if(n.length<=Nt.MEMORY_MAX_ENTRIES)return 0;let s=n.slice(0,n.length-Nt.MEMORY_MAX_ENTRIES),o=n.slice(-Nt.MEMORY_MAX_ENTRIES);return yt.archiveMany(e,s.map((i,a)=>({entityType:"memory_entry",entityId:`memory-${i.timestamp||a}`,entityData:i,summary:i.action,reason:"overflow"}))),await Jo(t,o),s.length}catch(t){return k(t)||console.error(`Memory cap error: ${w(t)}`),0}}},at=new Xi});import Yi from"node:fs/promises";import De from"node:path";var Zr,mu=y(()=>{"use strict";ee();me();Zr=class{static{l(this,"NestedContextResolver")}rootPath;monoInfo=null;constructor(e){this.rootPath=De.resolve(e)}async initialize(){this.monoInfo=await P.detectMonorepo(this.rootPath)}async discoverContextFiles(){let e=[],t=De.join(this.rootPath,"PRJCT.md");if(await C(t)){let s=await this.loadContext(t,null);e.push(s)}if(this.monoInfo?.isMonorepo)for(let s of this.monoInfo.packages){let o=De.join(s.path,"PRJCT.md");if(await C(o)){let i=e.find(c=>c.depth===0)||null,a=await this.loadContext(o,i,s);e.push(a),i&&i.children.push(a)}}let n=await this.scanForNestedContexts(this.rootPath,e);return e.push(...n),e}async loadContext(e,t,n=null){let s=await Yi.readFile(e,"utf-8"),o=De.relative(this.rootPath,e),i=o.split(De.sep).length-1;return{path:e,relativePath:o,depth:i,parent:t,children:[],content:s,sections:this.parseSections(s),package:n}}parseSections(e){let t=[],n=e.split(`
887
- `),s=null,o=[];for(let i of n){let a=i.match(/^##\s+(.+)$/);if(a){s&&(s.content=o.join(`
888
- `).trim(),t.push(s));let c=a[1],u=c.includes("@override")||c.includes("(override)");s={name:c.replace(/@override|\(override\)/gi,"").trim(),content:"",override:u},o=[]}else s&&o.push(i)}return s&&(s.content=o.join(`
889
- `).trim(),t.push(s)),t}async scanForNestedContexts(e,t){let n=[],s=new Set(t.map(i=>i.path)),o=l(async(i,a)=>{if(!(a>5))try{let c=await Yi.readdir(i,{withFileTypes:!0});for(let u of c)if(!(u.name.startsWith(".")||u.name==="node_modules"||u.name==="dist"||u.name==="build"||u.name==="coverage")&&u.isDirectory()){let p=De.join(i,u.name),m=De.join(p,"PRJCT.md");if(await C(m)&&!s.has(m)){let d=this.findParentContext(m,t.concat(n)),g=await this.loadContext(m,d);n.push(g),s.add(m),d&&d.children.push(g)}await o(p,a+1)}}catch{}},"scan");return await o(e,0),n}findParentContext(e,t){let n=De.dirname(e),s=[...t].sort((o,i)=>i.depth-o.depth);for(let o of s){let i=De.dirname(o.path);if(n.startsWith(i)&&n!==i)return o}return null}async resolveContextForPath(e){let t=await this.discoverContextFiles(),n=De.resolve(e),s=null;for(let a of t){let c=De.dirname(a.path);n.startsWith(c)&&(!s||a.depth>s.depth)&&(s=a)}if(!s)return{content:"",sources:[],overrides:[]};let o=[],i=s;for(;i;)o.unshift(i),i=i.parent;return this.mergeContextChain(o)}mergeContextChain(e){let t=new Map,n=[],s=[];for(let i of e){n.push(i.relativePath);for(let a of i.sections)if(a.override||!t.has(a.name))t.set(a.name,a.content),a.override&&s.push(`${i.relativePath}:${a.name}`);else{let c=t.get(a.name)||"";t.set(a.name,`${c}
890
-
891
- ${a.content}`)}}let o=[];for(let[i,a]of t)o.push(`## ${i}
892
-
893
- ${a}`);return{content:o.join(`
894
-
895
- ---
896
-
897
- `),sources:n,overrides:s}}async getPackageContext(e){if(!this.monoInfo?.isMonorepo)return null;let t=this.monoInfo.packages.find(n=>n.name===e);return t?this.resolveContextForPath(t.path):null}async getAllPackageContexts(){let e=new Map;if(!this.monoInfo?.isMonorepo)return e;for(let t of this.monoInfo.packages){let n=await this.resolveContextForPath(t.path);e.set(t.name,n)}return e}async discoverAgentFiles(){let e=[],t=De.join(this.rootPath,"AGENTS.md");if(await C(t)){let s=await this.loadAgents(t,null);e.push(s)}if(this.monoInfo?.isMonorepo)for(let s of this.monoInfo.packages){let o=De.join(s.path,"AGENTS.md");if(await C(o)){let i=e.find(c=>c.depth===0)||null,a=await this.loadAgents(o,i,s);e.push(a),i&&i.children.push(a)}}let n=await this.scanForNestedAgents(this.rootPath,e);return e.push(...n),e}async loadAgents(e,t,n=null){let s=await Yi.readFile(e,"utf-8"),o=De.relative(this.rootPath,e),i=o.split(De.sep).length-1;return{path:e,relativePath:o,depth:i,parent:t,children:[],content:s,agents:this.parseAgents(s),package:n}}parseAgents(e){let t=[],n=e.split(`
898
- `),s=null,o=null,i=[],a=l(()=>{if(s){if(o){let c=i.join(`
899
- `).trim();switch(o.toLowerCase()){case"triggers":s.triggers=this.parseListItems(c);break;case"rules":s.rules=this.parseListItems(c);break;case"patterns":s.patterns=this.parseCodeBlocks(c);break;case"examples":s.examples=this.parseListItems(c);break;case"domain":s.domain=c;break}}else{let c=i.join(`
900
- `).trim();c&&!s.description&&(s.description=c)}i=[]}},"saveCurrentContent");for(let c of n){let u=c.match(/^##\s+([^#].+)$/);if(u){s&&(a(),t.push(s));let m=u[1],d=m.includes("@override")||m.includes("(override)");s={name:m.replace(/@override|\(override\)/gi,"").trim(),description:"",override:d},o=null,i=[];continue}let p=c.match(/^###\s+(.+)$/);if(p&&s){a(),o=p[1].trim(),i=[];continue}s&&i.push(c)}return s&&(a(),t.push(s)),t}parseListItems(e){return e.split(`
901
- `).filter(t=>t.match(/^\s*[-*]\s+/)).map(t=>t.replace(/^\s*[-*]\s+/,"").trim()).filter(t=>t.length>0)}parseCodeBlocks(e){let t=[],n=/```[\w]*\n([\s\S]*?)```/g,s;for(;(s=n.exec(e))!==null;)t.push(s[1].trim());return t.length===0&&e.trim()&&t.push(e.trim()),t}async scanForNestedAgents(e,t){let n=[],s=new Set(t.map(i=>i.path)),o=l(async(i,a)=>{if(!(a>5))try{let c=await Yi.readdir(i,{withFileTypes:!0});for(let u of c)if(!(u.name.startsWith(".")||u.name==="node_modules"||u.name==="dist"||u.name==="build"||u.name==="coverage")&&u.isDirectory()){let p=De.join(i,u.name),m=De.join(p,"AGENTS.md");if(await C(m)&&!s.has(m)){let d=this.findParentAgents(m,t.concat(n)),g=await this.loadAgents(m,d);n.push(g),s.add(m),d&&d.children.push(g)}await o(p,a+1)}}catch{}},"scan");return await o(e,0),n}findParentAgents(e,t){let n=De.dirname(e),s=[...t].sort((o,i)=>i.depth-o.depth);for(let o of s){let i=De.dirname(o.path);if(n.startsWith(i)&&n!==i)return o}return null}async resolveAgentsForPath(e){let t=await this.discoverAgentFiles(),n=De.resolve(e),s=null;for(let a of t){let c=De.dirname(a.path);n.startsWith(c)&&(!s||a.depth>s.depth)&&(s=a)}if(!s)return{agents:[],sources:[],overrides:[]};let o=[],i=s;for(;i;)o.unshift(i),i=i.parent;return this.mergeAgentsChain(o)}mergeAgentsChain(e){let t=new Map,n=[],s=[];for(let o of e){n.push(o.relativePath);for(let i of o.agents){let a=t.get(i.name);if(i.override||!a)t.set(i.name,{...i}),i.override&&a&&s.push(`${o.relativePath}:${i.name}`);else{let c={...a};i.triggers&&(c.triggers=[...a.triggers||[],...i.triggers]),i.rules&&(c.rules=[...a.rules||[],...i.rules]),i.patterns&&(c.patterns=[...a.patterns||[],...i.patterns]),i.examples&&(c.examples=[...a.examples||[],...i.examples]),i.description&&(c.description=`${a.description}
902
-
903
- ${i.description}`),i.domain&&(c.domain=i.domain),t.set(i.name,c)}}}return{agents:Array.from(t.values()),sources:n,overrides:s}}async getPackageAgents(e){if(!this.monoInfo?.isMonorepo)return null;let t=this.monoInfo.packages.find(n=>n.name===e);return t?this.resolveAgentsForPath(t.path):null}async getAllPackageAgents(){let e=new Map;if(!this.monoInfo?.isMonorepo)return e;for(let t of this.monoInfo.packages){let n=await this.resolveAgentsForPath(t.path);e.set(t.name,n)}return e}}});import{exec as fx}from"node:child_process";import{promisify as hx}from"node:util";var B1,Cf=y(()=>{"use strict";Wr();ne();lu();B1=hx(fx)});import eo from"chalk";function wt(r,e={}){if(e.quiet)return;let t=wx[r]||"idle",n=qs.getValidCommands(t);if(n.length===0)return;let s=n.map(o=>({cmd:`p. ${o}`,desc:yx[o]||o}));console.log(eo.dim(`
904
- Next:`));for(let o of s){let i=eo.cyan(o.cmd.padEnd(12));console.log(eo.dim(` ${i} \u2192 ${o.desc}`))}}function to(r){let e=qs.getStateInfo(r);console.log(eo.dim(`\u{1F4CD} State: ${eo.white(r.toUpperCase())} - ${e.description}`))}var yx,wx,no=y(()=>{"use strict";bl();yx={task:"Start new task",done:"Complete current task",pause:"Pause and switch context",resume:"Continue paused task",ship:"Ship the feature",reopen:"Reopen for rework",next:"View task queue",sync:"Analyze project",bug:"Report a bug",idea:"Capture an idea"},wx={task:"working",done:"completed","done-subtask":"working",pause:"paused",resume:"working",ship:"shipped",reopen:"working",next:"idle",sync:"idle",init:"idle",bug:"working",idea:"idle"};l(wt,"showNextSteps");l(to,"showStateInfo")});import{exec as kx}from"node:child_process";import er from"node:fs/promises";import Zs from"node:path";import{promisify as Sx}from"node:util";async function vf(r,e){let t=P.getGlobalProjectPath(r),n=P.getContextPath(r),s=xl(r);await er.mkdir(n,{recursive:!0});let o=await s.read(["project"])||{},i=await s.list(["task"]),a=await s.list(["feature"]),c=await s.list(["idea"]),u=await s.list(["agent"]),p=[];for(let E of i){let x=await s.read(E);x&&p.push({...x,id:E[1]})}let m=[];for(let E of a){let x=await s.read(E);x&&m.push({...x,id:E[1]})}let d=[];for(let E of c){let x=await s.read(E);x&&d.push({...x,id:E[1]})}let g=[];for(let E of u){let x=await s.read(E);x&&g.push({...x,name:E[1]})}let f=await bx(e),S=await Px(e);await Cx(n,r,o,p,m,d,g,f,S,e),await vx(n,p),await xx(n,p),await Tx(n,o,f,S)}async function bx(r){let e={branch:"main",commits:0,contributors:0,hasChanges:!1,recentCommits:[]};try{let{stdout:t}=await so("git branch --show-current",{cwd:r});e.branch=t.trim()||"main";let{stdout:n}=await so("git rev-list --count HEAD",{cwd:r});e.commits=parseInt(n.trim(),10)||0;let{stdout:s}=await so("git shortlog -sn --all | wc -l",{cwd:r});e.contributors=parseInt(s.trim(),10)||0;let{stdout:o}=await so("git status --porcelain",{cwd:r});e.hasChanges=o.trim().length>0;let{stdout:i}=await so('git log --oneline -10 --pretty=format:"%h|%s|%ad" --date=short',{cwd:r});e.recentCommits=i.split(`
905
- `).filter(Boolean).map(a=>{let[c,u,p]=a.split("|");return{hash:c,message:u,date:p}})}catch{}return e}async function Px(r){let e={dependencies:{},devDependencies:{},scripts:{}};try{let t=Zs.join(r,"package.json"),n=JSON.parse(await er.readFile(t,"utf-8"));e.dependencies=n.dependencies||{},e.devDependencies=n.devDependencies||{},e.scripts=n.scripts||{}}catch{}return e}async function Cx(r,e,t,n,s,o,i,a,c,u){let p=t.name||Zs.basename(u),m=n.find(x=>x.status==="in_progress"),d=n.filter(x=>x.status==="pending"),g=s.filter(x=>x.status==="in_progress"||x.status==="active"),f=Object.keys(c.dependencies),S=Object.keys(c.devDependencies),E=`# ${p} - Project Context
906
- <!-- projectId: ${e} -->
907
- <!-- Generated: ${new Date().toISOString()} -->
908
-
909
- ## PROJECT DATA
910
-
911
- ### Dependencies (${f.length+S.length})
912
-
913
- **Production** (${f.length}):
914
- ${f.length>0?f.map(x=>`- ${x}: ${c.dependencies[x]}`).join(`
915
- `):"_None_"}
916
-
917
- **Dev** (${S.length}):
918
- ${S.length>0?S.map(x=>`- ${x}: ${c.devDependencies[x]}`).join(`
919
- `):"_None_"}
920
-
921
- ### Scripts
922
-
923
- ${Object.keys(c.scripts).length>0?Object.entries(c.scripts).map(([x,$])=>`- \`${x}\`: ${$}`).join(`
924
- `):"_None_"}
925
-
926
- ### Git
927
-
928
- - Branch: ${a.branch}
929
- - Commits: ${a.commits}
930
- - Contributors: ${a.contributors}
931
- - Uncommitted: ${a.hasChanges?"Yes":"No"}
932
-
933
- **Recent:**
934
- ${a.recentCommits.length>0?a.recentCommits.slice(0,5).map(x=>`- \`${x.hash}\` ${x.message}`).join(`
935
- `):"_None_"}
936
-
937
- ---
938
-
939
- ## CURRENT STATE
940
-
941
- **Now:** ${m?m.description:"_No active task_"}
942
-
943
- **Queue (${d.length}):**
944
- ${d.length>0?d.slice(0,10).map((x,$)=>`${$+1}. ${x.description}`).join(`
945
- `):"_Empty_"}
946
-
947
- **Active Features (${g.length}):**
948
- ${g.length>0?g.map(x=>`- ${x.name}`).join(`
949
- `):"_None_"}
950
-
951
- **Ideas (${o.length}):**
952
- ${o.length>0?o.slice(0,5).map(x=>`- ${x.title}`).join(`
953
- `):"_None_"}
954
-
955
- ---
956
-
957
- ## AGENTS
958
-
959
- ${i.length>0?i.map(x=>`- **${x.name}**: ${x.role||"Specialist"}`).join(`
960
- `):"_None_"}
961
-
962
- ---
963
-
964
- ## DATA LOCATION
965
-
966
- \`\`\`
967
- ~/.prjct-cli/projects/${e}/
968
- \u251C\u2500\u2500 data/ # JSON (source of truth)
969
- \u2502 \u251C\u2500\u2500 project.json
970
- \u2502 \u251C\u2500\u2500 tasks/
971
- \u2502 \u251C\u2500\u2500 features/
972
- \u2502 \u251C\u2500\u2500 ideas/
973
- \u2502 \u2514\u2500\u2500 agents/
974
- \u251C\u2500\u2500 context/ # MD (for Claude)
975
- \u2502 \u251C\u2500\u2500 CLAUDE.md
976
- \u2502 \u251C\u2500\u2500 now.md
977
- \u2502 \u2514\u2500\u2500 queue.md
978
- \u2514\u2500\u2500 sync/ # Sync state
979
- \u2514\u2500\u2500 pending.json
980
- \`\`\`
981
- `;await er.writeFile(Zs.join(r,"CLAUDE.md"),E,"utf-8")}async function vx(r,e){let t=e.find(s=>s.status==="in_progress"),n=t?`# NOW
982
-
983
- **Task:** ${t.description}
984
-
985
- **Started:** ${t.startedAt||"Unknown"}
986
-
987
- **Priority:** ${t.priority||"medium"}
988
- `:`# NOW
989
-
990
- _No active task. Use /p:now to start._
991
- `;await er.writeFile(Zs.join(r,"now.md"),n,"utf-8")}async function xx(r,e){let t=e.filter(s=>s.status==="pending"),n=`# QUEUE
992
-
993
- ${t.length>0?t.map((s,o)=>`${o+1}. ${s.description}${s.priority?` [${s.priority}]`:""}`).join(`
994
- `):"_Empty queue. Use /p:next to add tasks._"}
995
- `;await er.writeFile(Zs.join(r,"queue.md"),n,"utf-8")}async function Tx(r,e,t,n){let s=`# PROJECT SUMMARY
996
-
997
- **Name:** ${e.name||"Unknown"}
998
- **Version:** ${e.version||"N/A"}
999
- **Stack:** ${e.techStack?.join(", ")||"Not detected"}
1000
-
1001
- ## Git
1002
-
1003
- - Branch: ${t.branch}
1004
- - Commits: ${t.commits}
1005
- - Status: ${t.hasChanges?"Has uncommitted changes":"Clean"}
1006
-
1007
- ## Dependencies
1008
-
1009
- - Production: ${Object.keys(n.dependencies).length}
1010
- - Dev: ${Object.keys(n.devDependencies).length}
1011
- `;await er.writeFile(Zs.join(r,"summary.md"),s,"utf-8")}var so,xf=y(()=>{"use strict";ee();sn();so=Sx(kx);l(vf,"generateContext");l(bx,"getGitData");l(Px,"getPackageData");l(Cx,"generateClaudeMd");l(vx,"generateNowMd");l(xx,"generateQueueMd");l(Tx,"generateSummaryMd")});import{exec as Ex}from"node:child_process";import kt from"node:fs/promises";import Gt from"node:path";import{promisify as jx}from"node:util";var as,gu,Ax,Je,Tf=y(()=>{"use strict";M();as=jx(Ex),gu=class{static{l(this,"CodebaseAnalyzer")}projectPath=null;init(e=process.cwd()){this.projectPath=e}async readPackageJson(){try{let e=Gt.join(this.projectPath,"package.json"),t=await kt.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(k(e)||e instanceof SyntaxError)return null;throw e}}async readCargoToml(){try{let e=Gt.join(this.projectPath,"Cargo.toml");return await kt.readFile(e,"utf-8")}catch(e){if(k(e))return null;throw e}}async readRequirements(){try{let e=Gt.join(this.projectPath,"requirements.txt");return await kt.readFile(e,"utf-8")}catch(e){if(k(e))return null;throw e}}async readGoMod(){try{let e=Gt.join(this.projectPath,"go.mod");return await kt.readFile(e,"utf-8")}catch(e){if(k(e))return null;throw e}}async readGemfile(){try{let e=Gt.join(this.projectPath,"Gemfile");return await kt.readFile(e,"utf-8")}catch(e){if(k(e))return null;throw e}}async readMixExs(){try{let e=Gt.join(this.projectPath,"mix.exs");return await kt.readFile(e,"utf-8")}catch(e){if(k(e))return null;throw e}}async readPomXml(){try{let e=Gt.join(this.projectPath,"pom.xml");return await kt.readFile(e,"utf-8")}catch(e){if(k(e))return null;throw e}}async readComposerJson(){try{let e=Gt.join(this.projectPath,"composer.json"),t=await kt.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(k(e)||e instanceof SyntaxError)return null;throw e}}async readPyprojectToml(){try{let e=Gt.join(this.projectPath,"pyproject.toml");return await kt.readFile(e,"utf-8")}catch(e){if(k(e))return null;throw e}}async getFileExtensions(){try{let{stdout:e}=await as('find . -type f ! -path "*/node_modules/*" ! -path "*/.git/*" ! -path "*/dist/*" ! -path "*/.next/*" | sed "s/.*\\./\\./" | sort | uniq -c | sort -rn',{cwd:this.projectPath}),t={};return e.trim().split(`
1012
- `).filter(Boolean).forEach(n=>{let s=n.trim().match(/^\s*(\d+)\s+(\.\w+)$/);s&&(t[s[2]]=parseInt(s[1],10))}),t}catch{return{}}}async listConfigFiles(){try{let e=await kt.readdir(this.projectPath),t=[/^package\.json$/,/^Cargo\.toml$/,/^go\.mod$/,/^requirements\.txt$/,/^Gemfile$/,/^mix\.exs$/,/^pom\.xml$/,/^composer\.json$/,/^pyproject\.toml$/,/^tsconfig.*\.json$/,/^\..*rc(\.json|\.js|\.cjs)?$/,/^Dockerfile$/,/^docker-compose.*\.ya?ml$/,/^\.env.*$/];return e.filter(n=>t.some(s=>s.test(n)))}catch(e){if(k(e))return[];throw e}}async listDirectories(){try{return(await kt.readdir(this.projectPath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).filter(t=>!t.startsWith(".")&&t!=="node_modules")}catch(e){if(k(e))return[];throw e}}async getGitLog(e=50){try{let{stdout:t}=await as(`git log -n ${e} --pretty=format:"%h|%an|%ar|%s"`,{cwd:this.projectPath});return t}catch{return""}}async getGitStats(){try{let{stdout:e}=await as("git rev-list --count HEAD",{cwd:this.projectPath}),{stdout:t}=await as('git log --format="%an" | sort -u | wc -l',{cwd:this.projectPath}),{stdout:n}=await as('git log --reverse --pretty=format:"%ar" | head -1',{cwd:this.projectPath});return{totalCommits:parseInt(e.trim(),10)||0,contributors:parseInt(t.trim(),10)||0,age:n.trim()||"unknown"}}catch{return{totalCommits:0,contributors:0,age:"unknown"}}}async countFiles(){try{let{stdout:e}=await as('find . -type f ! -path "*/node_modules/*" ! -path "*/.git/*" ! -path "*/dist/*" | wc -l',{cwd:this.projectPath});return parseInt(e.trim(),10)||0}catch{return 0}}async fileExists(e){try{return await kt.access(Gt.join(this.projectPath,e)),!0}catch(t){if(k(t))return!1;throw t}}async readFile(e){try{let t=Gt.join(this.projectPath,e);return await kt.readFile(t,"utf-8")}catch(t){if(k(t))return null;throw t}}async findFiles(e){try{let{stdout:t}=await as(`find . -type f -name "${e}" ! -path "*/node_modules/*" ! -path "*/.git/*"`,{cwd:this.projectPath});return t.trim().split(`
1013
- `).filter(Boolean)}catch{return[]}}},Ax=new gu,Je=Ax});import fn from"chalk";function Ef(r){return Math.ceil(r.length/Ix)}function jf(r){let e=r.split(`
1014
- `),t=[],n=null;for(let s=0;s<e.length;s++){let o=e[s],i=o.match(/^(#{1,3})\s+(.+)$/);i?(n&&(n.endLine=s-1,t.push(n)),n={name:i[2].trim(),content:o,startLine:s,endLine:s}):n&&(n.content+=`
1015
- ${o}`)}return n&&(n.endLine=e.length-1,t.push(n)),t}function fu(r){return r.includes("<!-- prjct:preserve")}function Af(r,e){let t=jf(r),n=jf(e),s={hasChanges:!1,added:[],modified:[],removed:[],preserved:[],tokensBefore:Ef(r),tokensAfter:Ef(e),tokenDelta:0};s.tokenDelta=s.tokensAfter-s.tokensBefore;let o=new Map(t.map(a=>[a.name.toLowerCase(),a])),i=new Map(n.map(a=>[a.name.toLowerCase(),a]));for(let a of t)fu(a.content)&&s.preserved.push({name:a.name,lineCount:a.content.split(`
1016
- `).length});for(let a of n){let c=a.name.toLowerCase(),u=o.get(c);u?u.content.trim()!==a.content.trim()&&(fu(u.content)||(s.modified.push({name:a.name,type:"modified",before:u.content,after:a.content,lineCount:a.content.split(`
1017
- `).length}),s.hasChanges=!0)):(s.added.push({name:a.name,type:"added",after:a.content,lineCount:a.content.split(`
1018
- `).length}),s.hasChanges=!0)}for(let a of t){let c=a.name.toLowerCase();!i.has(c)&&!fu(a.content)&&(s.removed.push({name:a.name,type:"removed",before:a.content,lineCount:a.content.split(`
1019
- `).length}),s.hasChanges=!0)}return s}function If(r,e={}){let{colorize:t=!0}=e,n=[],s=t?fn.green:d=>d,o=t?fn.red:d=>d,i=t?fn.yellow:d=>d,a=t?fn.dim:d=>d,c=t?fn.bold:d=>d;if(!r.hasChanges)return n.push(a("No changes detected (context is up to date)")),n.join(`
1020
- `);if(n.push(""),n.push(c("\u{1F4CB} Changes to context files:")),n.push(""),r.added.length>0)for(let d of r.added)n.push(s(`+ \u2502 + ${d.name} (new)`));if(r.modified.length>0)for(let d of r.modified)n.push(i(`~ \u2502 ${d.name} (modified)`));if(r.removed.length>0)for(let d of r.removed)n.push(o(`- \u2502 - ${d.name} (removed)`));if(r.preserved.length>0){n.push(""),n.push(a(" ## Your Customizations"));for(let d of r.preserved)n.push(a(` \u2502 \u2713 ${d.name} (${d.lineCount} lines preserved)`))}n.push(""),n.push(a("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));let u=[];r.added.length>0&&u.push(s(`+${r.added.length} added`)),r.modified.length>0&&u.push(i(`~${r.modified.length} modified`)),r.removed.length>0&&u.push(o(`-${r.removed.length} removed`)),n.push(`Summary: ${u.join(", ")||"no changes"}`);let p=r.tokenDelta>=0?"+":"",m=r.tokenDelta>=0?s:o;return n.push(`Tokens: ${r.tokensBefore.toLocaleString()} \u2192 ${r.tokensAfter.toLocaleString()} (${m(p+r.tokenDelta.toLocaleString())})`),n.push(""),n.join(`
1021
- `)}function Df(r,e={}){let{colorize:t=!0}=e,n=[],s=t?fn.green:c=>c,o=t?fn.red:c=>c,i=t?fn.cyan:c=>c,a=t?fn.dim:c=>c;for(let c of r.added){if(n.push(i(`@@ +${c.name} @@`)),c.after)for(let u of c.after.split(`
1022
- `))n.push(s(`+ ${u}`));n.push("")}for(let c of r.modified){if(n.push(i(`@@ ${c.name} @@`)),c.before){for(let u of c.before.split(`
1023
- `).slice(0,5))n.push(o(`- ${u}`));c.before.split(`
1024
- `).length>5&&n.push(a(` ... ${c.before.split(`
1025
- `).length-5} more lines`))}if(c.after){for(let u of c.after.split(`
1026
- `).slice(0,5))n.push(s(`+ ${u}`));c.after.split(`
1027
- `).length>5&&n.push(a(` ... ${c.after.split(`
1028
- `).length-5} more lines`))}n.push("")}for(let c of r.removed){if(n.push(i(`@@ -${c.name} @@`)),c.before){for(let u of c.before.split(`
1029
- `).slice(0,5))n.push(o(`- ${u}`));c.before.split(`
1030
- `).length>5&&n.push(a(` ... ${c.before.split(`
1031
- `).length-5} more lines`))}n.push("")}return n.join(`
1032
- `)}var Ix,Rf=y(()=>{"use strict";Ix=4;l(Ef,"estimateTokens");l(jf,"parseMarkdownSections");l(fu,"isPreservedSection");l(Af,"generateSyncDiff");l(If,"formatDiffPreview");l(Df,"formatFullDiff")});import Dx from"node:path";async function hu(r,e){let t=Date.now()-e,n=r.contextFiles.length+(r.aiTools?.filter(d=>d.success).length||0),s=r.agents.length,o=r.agents.filter(d=>d.type==="domain").length;await be.installGlobalConfig(),h.done(`Synced ${r.stats.name||"project"} (${(t/1e3).toFixed(1)}s)`),console.log("");let i=r.syncMetrics?.compressionRate?Math.round(r.syncMetrics.compressionRate*100):0,a=r.stats.frameworks.length>0?` (${r.stats.frameworks[0]})`:"",c=[`${r.stats.fileCount} files \u2192 ${n} context | ${s} agents${i>10?` | ${i}% reduction`:""}`,`Stack: ${r.stats.ecosystem}${a} | Branch: ${r.git.branch}`];h.box("Sync Summary",c.join(`
1033
- `));let u=[];r.contextFiles.length>0&&u.push(`${r.contextFiles.length} context files`);let p=r.aiTools?.filter(d=>d.success)||[];if(p.length>0&&u.push(`AI tools: ${p.map(d=>d.toolId).join(", ")}`),s>0){let d=o>0?`${s} agents (${o} domain)`:`${s} agents`;u.push(d)}if(r.skills.length>0){let d=r.skills.length===1?"skill":"skills";u.push(`${r.skills.length} ${d}`)}let m=r.skillsInstalled?.filter(d=>d.status==="installed")||[];if(m.length>0){let d=m.length===1?"skill":"skills";u.push(`${m.length} ${d} auto-installed`)}if(h.section("Generated"),h.list(u,{bullet:"\u2713"}),console.log(""),r.git.hasChanges&&(h.warn("Uncommitted changes detected"),console.log("")),r.verification){let d=r.verification;if(d.passed){let g=d.checks.map(f=>`${f.name} (${f.durationMs}ms)`);h.section("Verified"),h.list(g,{bullet:"\u2713"})}else{h.section("Verification");let g=d.checks.map(f=>f.passed?`\u2713 ${f.name}`:`\u2717 ${f.name}${f.error?` \u2014 ${f.error}`:""}`);h.list(g),d.skippedCount>0&&h.warn(`${d.skippedCount} check(s) skipped (fail-fast)`)}console.log("")}return wt("sync"),{success:!0,data:r,metrics:{elapsed:t,contextFilesCount:n,agentCount:s,fileCount:r.stats.fileCount}}}async function $f(r){try{let e=await at.getRecentEvents(r,100),t=new Date().toISOString().split("T")[0],n=e.filter(u=>(u.timestamp||u.ts)?.startsWith(t)),s=null;if(n.length>=2){let u=n.map(p=>new Date(p.timestamp||p.ts).getTime()).filter(p=>!Number.isNaN(p)).sort((p,m)=>p-m);if(u.length>=2){let p=u[u.length-1]-u[0];s=U.formatDuration(p)}}let o=n.filter(u=>u.action==="task_completed").length,i=n.filter(u=>u.action==="feature_shipped").length,a=new Map;for(let u of n)if(u.action==="sync"&&Array.isArray(u.subagents))for(let p of u.subagents)a.set(p,(a.get(p)||0)+1);let c=Array.from(a.entries()).map(([u,p])=>({name:u,count:p})).sort((u,p)=>p.count-u.count);return{sessionDuration:s,tasksCompleted:o,featuresShipped:i,agentsUsed:c}}catch{return{sessionDuration:null,tasksCompleted:0,featuresShipped:0,agentsUsed:[]}}}function ro(r){return r>=1e6?`${(r/1e6).toFixed(1)}M`:r>=1e3?`${(r/1e3).toFixed(1)}K`:r.toLocaleString()}function yu(r){return r<1e3?`${Math.round(r)}ms`:`${(r/1e3).toFixed(1)}s`}function Mf(r){if(r.length===0)return"";let e="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",t=r.map(s=>s.tokensSaved),n=Math.max(...t,1);return t.map(s=>{let o=Math.min(Math.floor(s/n*(e.length-1)),e.length-1);return e[o]}).join("")}function Ff(r,e,t,n,s,o){let i=[];if(i.push(`# ${t} - Stats Dashboard`),i.push(""),i.push(`_Generated: ${new Date().toLocaleString()} | Tracking since: ${n}_`),i.push(""),s){if(i.push("## \u{1F3AF} Today's Activity"),i.push(""),i.push("| Metric | Value |"),i.push("|--------|-------|"),s.sessionDuration&&i.push(`| Duration | ${s.sessionDuration} |`),i.push(`| Tasks completed | ${s.tasksCompleted} |`),i.push(`| Features shipped | ${s.featuresShipped} |`),s.agentsUsed.length>0){let a=s.agentsUsed.slice(0,3).map(c=>`${c.name} (${c.count}\xD7)`).join(", ");i.push(`| Agents used | ${a} |`)}i.push("")}if(o&&(o.decisions>0||o.preferences>0)&&(i.push("## \u{1F9E0} Patterns Learned"),i.push(""),i.push("| Type | Count |"),i.push("|------|-------|"),i.push(`| Decisions | ${o.learnedDecisions} confirmed (${o.decisions} total) |`),i.push(`| Preferences | ${o.preferences} |`),i.push(`| Workflows | ${o.workflows} |`),i.push("")),i.push("## \u{1F4B0} Token Savings"),i.push(""),i.push("| Metric | Value |"),i.push("|--------|-------|"),i.push(`| Total saved | ${ro(r.totalTokensSaved)} tokens |`),i.push(`| Compression | ${(r.compressionRate*100).toFixed(0)}% |`),i.push(`| Cost saved | ${Ns(r.estimatedCostSaved)} |`),i.push(""),i.push("## \u26A1 Performance"),i.push(""),i.push("| Metric | Value |"),i.push("|--------|-------|"),i.push(`| Syncs | ${r.syncCount} |`),i.push(`| Avg time | ${yu(r.avgSyncDuration)} |`),i.push(""),r.topAgents.length>0){i.push("## \u{1F916} Agent Usage"),i.push(""),i.push("| Agent | Usage |"),i.push("|-------|-------|");let a=r.topAgents.reduce((c,u)=>c+u.usageCount,0);for(let c of r.topAgents){let u=a>0?(c.usageCount/a*100).toFixed(0):0;i.push(`| ${c.agentName} | ${u}% (${c.usageCount}) |`)}i.push("")}if(i.push("## \u{1F4C8} 30-Day Trend"),i.push(""),i.push(`- Tokens saved: ${ro(r.last30DaysTokens)}`),r.trend!==0){let a=r.trend>0?"+":"";i.push(`- Trend: ${a}${r.trend.toFixed(0)}% vs previous period`)}return i.push(""),i.push("---"),i.push(""),i.push("_Generated with [prjct-cli](https://prjct.app)_"),i.join(`
1034
- `)}function Of(r,e){let t=[];t.push(`# Repository Analysis
1035
- `),t.push(`Generated: ${new Date().toLocaleString()}
1036
- `);let n=Dx.basename(e);if(t.push(`## Project: ${n}
1037
- `),t.push(`## Stack Detected
1038
- `),r.packageJson){let i=r.packageJson;if(t.push(`### JavaScript/TypeScript
1039
- `),t.push("- **Package Manager**: npm/yarn/pnpm"),i.dependencies){let a=Object.keys(i.dependencies);a.length>0&&t.push(`- **Dependencies**: ${a.slice(0,10).join(", ")}${a.length>10?` (+${a.length-10} more)`:""}`)}r.hasNextConfig&&t.push("- **Framework**: Next.js detected"),r.hasViteConfig&&t.push("- **Build Tool**: Vite detected"),r.hasTsconfig&&t.push("- **Language**: TypeScript"),t.push("")}r.cargoToml&&(t.push(`### Rust
1040
- `),t.push("- **Package Manager**: Cargo"),t.push(`- **Language**: Rust
1041
- `)),r.goMod&&(t.push(`### Go
1042
- `),t.push("- **Package Manager**: Go modules"),t.push(`- **Language**: Go
1043
- `)),r.requirements&&(t.push(`### Python
1044
- `),t.push("- **Package Manager**: pip"),t.push(`- **Language**: Python
1045
- `));let s=r.directories;t.push(`## Structure
1046
- `),t.push(`- **Total Files**: ${r.fileCount}`),t.push(`- **Directories**: ${s?.slice(0,15).join(", ")||"none"}${(s?.length||0)>15?` (+${(s?.length||0)-15} more)`:""}`),r.hasDockerfile&&t.push("- **Docker**: Detected"),r.hasDockerCompose&&t.push("- **Docker Compose**: Detected"),r.hasReadme&&t.push("- **Documentation**: README.md found"),t.push("");let o=r.gitStats;return t.push(`## Git Statistics
1047
- `),t.push(`- **Total Commits**: ${o?.totalCommits||0}`),t.push(`- **Contributors**: ${o?.contributors||0}`),t.push(`- **Age**: ${o?.age||"unknown"}`),t.push(""),r.gitLog&&(t.push(`## Recent Activity
1048
- `),r.gitLog.split(`
1049
- `).slice(0,5).forEach(a=>{if(a.trim()){let[c,,u,p]=a.split("|");t.push(`- \`${c}\` ${p} (${u})`)}}),t.push("")),t.push(`## Recommendations
1050
- `),t.push("Based on detected stack, consider generating specialized agents using `/p:sync`.\n"),t.push(`---
1051
- `),t.push("*This analysis was generated automatically. For updated information, run `/p:analyze` again.*\n"),t.join(`
1052
- `)}var _f=y(()=>{"use strict";En();Vo();Fn();no();Xt();tt();l(hu,"showSyncResult");l($f,"getSessionActivity");l(ro,"formatTokens");l(yu,"formatDuration");l(Mf,"generateSparkline");l(Ff,"generateStatsMarkdown");l(Of,"generateAnalysisSummary")});var Lf={};Ne(Lf,{AnalysisCommands:()=>ls});import oo from"node:fs/promises";import wu from"node:path";import Nf from"prompts";var ls,Qi=y(()=>{"use strict";xf();Vs();Tf();En();Vo();Fn();Rf();ki();Ir();M();Xt();_f();tt();ls=class extends ve{static{l(this,"AnalysisCommands")}async analyze(e={},t=process.cwd()){try{await this.initializeAgent(),console.log(`\u{1F50D} Analyzing repository...
1053
- `),Je.init(t);let n=await rt.build(t,e),s={packageJson:await Je.readPackageJson(),cargoToml:await Je.readCargoToml(),goMod:await Je.readGoMod(),requirements:await Je.readRequirements(),directories:await Je.listDirectories(),fileCount:await Je.countFiles(),gitStats:await Je.getGitStats(),gitLog:await Je.getGitLog(20),hasDockerfile:await Je.fileExists("Dockerfile"),hasDockerCompose:await Je.fileExists("docker-compose.yml"),hasReadme:await Je.fileExists("README.md"),hasTsconfig:await Je.fileExists("tsconfig.json"),hasViteConfig:await Je.fileExists("vite.config.ts")||await Je.fileExists("vite.config.js"),hasNextConfig:await Je.fileExists("next.config.js")||await Je.fileExists("next.config.mjs")},o=Of(s,t),i=await I.getProjectId(t),a=n.paths.analysis||P.getFilePath(i,"analysis","repo-summary.md");await ze.get("Write")(a,o),await this.logToMemory(t,"repository_analyzed",{timestamp:U.getTimestamp(),fileCount:s.fileCount,gitCommits:s.gitStats.totalCommits}),await vf(i,t);let u=await(He(),bt(mt)).getActiveProvider(),p=await be.installGlobalConfig();return p.success&&console.log(`\u{1F4DD} Updated ${P.getDisplayPath(p.path)}`),console.log(`\u2705 Analysis complete!
1054
- `),console.log("\u{1F4C4} Full report: analysis/repo-summary.md"),console.log(`\u{1F4DD} Context: ~/.prjct-cli/projects/${i}/${u.contextFile}
1055
- `),console.log("Next steps:"),console.log("\u2022 /p:sync \u2192 Generate agents based on stack"),console.log("\u2022 /p:feature \u2192 Add a new feature"),{success:!0,summaryPath:a,data:s}}catch(n){return console.error("\u274C Error:",w(n)),{success:!1,error:w(n)}}}async sync(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await I.getProjectId(e);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=P.getGlobalProjectPath(s),i=Date.now();if(t.package){let m=await P.detectMonorepo(e);if(!m.isMonorepo)return{success:!1,error:"Not a monorepo. --package flag only works in monorepos."};let d=m.packages.find(f=>f.name===t.package||f.relativePath===t.package);if(!d){let f=m.packages.map(S=>S.name).join(", ");return{success:!1,error:`Package "${t.package}" not found. Available: ${f}`}}let g=await cs.sync(e,{aiTools:t.aiTools,packagePath:d.path,packageName:d.name});return t.json?console.log(JSON.stringify({success:g.success,package:d.name,path:d.relativePath})):h.done(`Synced package: ${d.name}`),{success:g.success}}let a=wu.join(o,"context","CLAUDE.md"),c=null;try{c=await oo.readFile(a,"utf-8")}catch{}let u=!process.stdin.isTTY||t.json;if(c&&!t.yes){u||h.spin("Analyzing changes...");let m=await cs.sync(e,{aiTools:t.aiTools,full:t.full});if(!m.success)return u?(console.log(JSON.stringify({success:!1,error:m.error||"Sync failed"})),{success:!1,error:m.error}):(h.fail(m.error||"Sync failed"),{success:!1,error:m.error});let d;try{d=await oo.readFile(a,"utf-8")}catch{d=""}let g=Af(c,d);if(u||h.stop(),!g.hasChanges)return u?(console.log(JSON.stringify({success:!0,action:"no_changes",message:"No changes detected (context is up to date)"})),{success:!0,message:"No changes"}):(h.done("No changes detected (context is up to date)"),{success:!0,message:"No changes"});let f=l(async()=>{c!=null&&await oo.writeFile(a,c,"utf-8")},"restoreOriginal");if(u){await f();let E={added:g.added.map(x=>({name:x.name,lineCount:x.lineCount})),modified:g.modified.map(x=>({name:x.name,lineCount:x.lineCount})),removed:g.removed.map(x=>({name:x.name,lineCount:x.lineCount})),preserved:g.preserved,tokensBefore:g.tokensBefore,tokensAfter:g.tokensAfter,tokenDelta:g.tokenDelta};return console.log(JSON.stringify({success:!0,action:"confirm_required",message:"Changes detected. Confirmation required to apply.",diff:E,fullDiff:t.preview?{added:g.added,modified:g.modified,removed:g.removed}:void 0,hint:"Run `prjct sync --yes` to apply changes"})),{success:!0,isPreview:!0,diff:g,message:"Preview complete (awaiting confirmation)"}}if(console.log(If(g)),t.preview)return await f(),{success:!0,isPreview:!0,diff:g,message:"Preview complete (no changes applied)"};let S=await Nf({type:"select",name:"action",message:"Apply these changes?",choices:[{title:"Yes, apply changes",value:"apply"},{title:"No, cancel",value:"cancel"},{title:"Show full diff",value:"diff"}]});return S.action==="cancel"||!S.action?(await f(),h.warn("Sync cancelled \u2014 no changes applied"),{success:!1,message:"Cancelled by user"}):S.action==="diff"&&(console.log(`
1056
- ${Df(g)}`),!(await Nf({type:"confirm",name:"apply",message:"Apply these changes?",initial:!0})).apply)?(await f(),h.warn("Sync cancelled \u2014 no changes applied"),{success:!1,message:"Cancelled by user"}):(h.done("Changes applied"),hu(m,i))}h.spin("Syncing project...");let p=await cs.sync(e,{aiTools:t.aiTools,full:t.full});return p.success?(h.stop(),hu(p,i)):(h.fail(p.error||"Sync failed"),{success:!1,error:p.error})}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}async stats(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await I.getProjectId(e);if(!s)return{success:!1,error:"No project ID found"};let o=await pn.getSummary(s),i=await pn.getDailyStats(s,30),a=await $f(s),c=await Ce.getPatternsSummary(s);if(t.json){let g={session:a,patterns:c,totalTokensSaved:o.totalTokensSaved,estimatedCostSaved:o.estimatedCostSaved,compressionRate:o.compressionRate,syncCount:o.syncCount,avgSyncDuration:o.avgSyncDuration,topAgents:o.topAgents,last30DaysTokens:o.last30DaysTokens,trend:o.trend,dailyStats:i};return console.log(JSON.stringify(g,null,2)),{success:!0,data:g}}let u=P.getGlobalProjectPath(s),p="Unknown";try{p=JSON.parse(await oo.readFile(wu.join(u,"project.json"),"utf-8")).name||"Unknown"}catch{}let m=await pn.read(s),d=m.firstSync?new Date(m.firstSync).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"N/A";if(console.log(""),console.log("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"),console.log("\u2502 \u{1F4CA} prjct-cli Stats Dashboard \u2502"),console.log(`\u2502 Project: ${p.padEnd(20).slice(0,20)} | Since: ${d.padEnd(12).slice(0,12)} \u2502`),console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"),console.log(""),console.log("\u{1F3AF} TODAY'S ACTIVITY"),a.sessionDuration&&console.log(` Duration: ${a.sessionDuration}`),console.log(` Tasks completed: ${a.tasksCompleted}`),console.log(` Features shipped: ${a.featuresShipped}`),a.agentsUsed.length>0){let g=a.agentsUsed.slice(0,3).map(f=>`${f.name} (${f.count}\xD7)`).join(", ");console.log(` Agents used: ${g}`)}if(console.log(""),(c.decisions>0||c.preferences>0)&&(console.log("\u{1F9E0} PATTERNS LEARNED"),console.log(` Decisions: ${c.learnedDecisions} confirmed (${c.decisions} total)`),console.log(` Preferences: ${c.preferences} saved`),console.log(` Workflows: ${c.workflows} tracked`),console.log("")),console.log("\u{1F4B0} TOKEN SAVINGS"),console.log(` Total saved: ${ro(o.totalTokensSaved)} tokens`),console.log(` Compression: ${(o.compressionRate*100).toFixed(0)}% average reduction`),console.log(` Estimated cost: ${Ns(o.estimatedCostSaved)} saved`),console.log(""),console.log("\u26A1 PERFORMANCE"),console.log(` Syncs completed: ${o.syncCount.toLocaleString()}`),console.log(` Avg sync time: ${yu(o.avgSyncDuration)}`),console.log(""),o.topAgents.length>0){console.log("\u{1F916} AGENT USAGE (all time)");let g=o.topAgents.reduce((f,S)=>f+S.usageCount,0);for(let f of o.topAgents){let S=g>0?(f.usageCount/g*100).toFixed(0):0;console.log(` ${f.agentName.padEnd(12)}: ${S}% (${f.usageCount} uses)`)}console.log("")}if(i.length>0){console.log("\u{1F4C8} TREND (last 30 days)");let g=Mf(i);if(console.log(` ${g} ${ro(o.last30DaysTokens)} tokens saved`),o.trend!==0){let f=o.trend>0?"\u2191":"\u2193",S=o.trend>0?"+":"";console.log(` ${f} ${S}${o.trend.toFixed(0)}% vs previous 30 days`)}console.log("")}if(console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log("Export: prjct stats --export > stats.md"),console.log(""),t.export){let g=Ff(o,i,p,d,a,c);return console.log(g),{success:!0,data:{markdown:g}}}return{success:!0,data:{...o,session:a,patterns:c}}}catch(n){return console.error("\u274C Error:",w(n)),{success:!1,error:w(n)}}}async status(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await I.getProjectId(e);if(!s)return t.json?console.log(JSON.stringify({success:!1,error:"No project ID found"})):h.fail("No project ID found"),{success:!1,error:"No project ID found"};let o=io(e),i=await o.check(s),a=await o.getSessionInfo(s),c=await nn.getStatus(s);return t.json?(console.log(JSON.stringify({success:!0,...i,session:a,analysis:c})),{success:!0,data:{...i,session:a,analysis:c}}):(console.log(""),console.log(o.formatStatus(i)),console.log(""),console.log(o.formatSessionInfo(a)),(c.hasSealed||c.hasDraft)&&(console.log(""),console.log("Analysis:"),c.hasSealed&&console.log(` Sealed: ${c.sealedCommit} (${c.sealedAt})`),c.hasDraft&&console.log(` Draft: ${c.draftCommit} (pending seal)`)),console.log(""),{success:!0,data:{...i,session:a,analysis:c}})}catch(n){let s=w(n);return t.json?console.log(JSON.stringify({success:!1,error:s})):h.fail(s),{success:!1,error:s}}}async seal(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await I.getProjectId(e);if(!s)return t.json&&console.log(JSON.stringify({success:!1,error:"No project ID found"})),{success:!1,error:"No project ID found"};let o=await nn.seal(s);return t.json?(console.log(JSON.stringify({success:o.success,signature:o.signature,error:o.error})),{success:o.success,error:o.error}):o.success?(h.done("Analysis sealed"),console.log(` Signature: ${o.signature?.substring(0,16)}...`),console.log(""),{success:!0,data:{signature:o.signature}}):(h.fail(o.error||"Seal failed"),{success:!1,error:o.error})}catch(n){let s=w(n);return t.json?console.log(JSON.stringify({success:!1,error:s})):h.fail(s),{success:!1,error:s}}}async verify(e=process.cwd(),t={}){if(t.semantic)return this.semanticVerify(e,t);try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await I.getProjectId(e);if(!s)return{success:!1,error:"No project ID found"};let o=await nn.verify(s);return t.json?(console.log(JSON.stringify(o)),{success:o.valid}):(o.valid?h.done(o.message):h.fail(o.message),console.log(""),{success:o.valid,data:o})}catch(n){let s=w(n);return h.fail(s),{success:!1,error:s}}}async semanticVerify(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await I.getProjectId(e);if(!s)return t.json?console.log(JSON.stringify({success:!1,error:"No project ID found"})):h.fail("No project ID found"),{success:!1,error:"No project ID found"};let o=P.getGlobalProjectPath(s),i=e;try{i=JSON.parse(await oo.readFile(wu.join(o,"project.json"),"utf-8")).repoPath||e}catch{}let a=await nn.semanticVerify(s,i);if(t.json)return console.log(JSON.stringify(a)),{success:a.passed,data:a};console.log(""),a.passed?(h.done("Semantic verification passed"),console.log(` ${a.passedCount}/${a.checks.length} checks passed (${a.totalMs}ms)`)):(h.fail("Semantic verification failed"),console.log(` ${a.failedCount}/${a.checks.length} checks failed`)),console.log(""),console.log("Check Results:");for(let c of a.checks){let u=c.passed?"\u2713":"\u2717",p=c.passed?`${c.output} (${c.durationMs}ms)`:c.error||"Failed";console.log(` ${u} ${c.name}: ${p}`)}return console.log(""),{success:a.passed,data:a}}catch(n){let s=w(n);return t.json?console.log(JSON.stringify({success:!1,error:s})):h.fail(s),{success:!1,error:s}}}}});var Uf={};Ne(Uf,{PlanningCommands:()=>ps});import us from"node:path";async function Rx(){if(!ku){let{AnalysisCommands:r}=await Promise.resolve().then(()=>(Qi(),Lf));ku=new r}return ku}var ku,ps,Zi=y(()=>{"use strict";$o();En();_t();sn();M();no();Ul();tt();ku=null;l(Rx,"getAnalysisCommands");ps=class extends ve{static{l(this,"PlanningCommands")}async init(e={},t=process.cwd()){try{let n={};if(typeof e=="string"||e===null?n={idea:e}:n=e,await this.initializeAgent(),await I.isConfigured(t))return h.warn("already initialized"),{success:!1,message:"Already initialized"};let o=process.stdout.isTTY&&process.stdin.isTTY,i=n.yes||!o||process.env.CI==="true",a=null;if(i)o&&n.yes&&(a=await new Xs(t).runNonInteractive());else if(a=await new Xs(t).run(),a.skipped)return{success:!1,message:"Setup cancelled"};h.step(1,4,"Detecting author...");let c=await vs(),u={name:c.name||void 0,email:c.email||void 0,github:c.github||void 0},m=(await I.createConfig(t,u)).projectId;h.step(2,4,"Creating structure..."),await P.ensureProjectStructure(m);let d=P.getGlobalProjectPath(m),g={"core/now.md":`# NOW
1057
-
1058
- No current task. Use \`/p:now\` to set focus.
1059
- `,"core/next.md":`# NEXT
1060
-
1061
- ## Priority Queue
1062
-
1063
- `,"core/context.md":`# CONTEXT
1064
-
1065
- `,"progress/shipped.md":`# SHIPPED \u{1F680}
1066
-
1067
- `,"progress/metrics.md":`# METRICS
1068
-
1069
- `,"planning/ideas.md":`# IDEAS \u{1F4A1}
1070
-
1071
- ## Brain Dump
1072
-
1073
- `,"planning/roadmap.md":`# ROADMAP
1074
-
1075
- `,"planning/specs/.gitkeep":`# Specs directory - created by /p:spec
1076
- `,"memory/context.jsonl":"","memory/patterns.json":JSON.stringify({version:1,decisions:{},preferences:{},workflows:{},counters:{}},null,2)};a&&(g["config/wizard.json"]=JSON.stringify({projectType:a.projectType,agents:a.agents,stack:a.stack,preferences:a.preferences,createdAt:new Date().toISOString()},null,2));for(let[x,$]of Object.entries(g))await ze.get("Write")(us.join(d,x),$);let f=await this._detectEmptyDirectory(t),S=await this._detectExistingCode(t);if(S||!f){h.step(3,4,"Analyzing project...");let x=await Rx();if((await x.analyze({},t)).success)return h.step(4,4,"Generating agents..."),a?.agents?await x.sync(t,{aiTools:a.agents}):await x.sync(t),h.done("initialized"),this._printNextSteps(a),{success:!0,mode:"existing",projectId:m,wizard:a}}let E=n.idea;if(f&&!S){if(!E)return h.done("blank project - provide idea for architect mode"),{success:!0,mode:"blank_no_idea",projectId:m,wizard:a};h.spin("architect mode...");let x=us.join(d,"planning","architect-session.md"),$=`# Architect Session
1077
-
1078
- ## Idea
1079
- ${E}
1080
-
1081
- ## Status
1082
- Initialized - awaiting stack recommendation
1083
-
1084
- Generated: ${new Date().toLocaleString()}
1085
- `;return await ze.get("Write")(x,$),await be.installGlobalConfig(),h.done("architect mode ready"),{success:!0,mode:"architect",projectId:m,idea:E,wizard:a}}return await be.installGlobalConfig(),h.done("initialized"),this._printNextSteps(a),{success:!0,projectId:m,wizard:a}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}_printNextSteps(e){if(console.log(""),console.log(" Quick start:"),console.log(" prjct sync Update context after changes"),console.log(" prjct task Start working on a task"),console.log(" prjct hooks Auto-sync on commit/checkout"),console.log(""),e){let t=e.agents.map(n=>{switch(n){case"claude":return"CLAUDE.md";case"cursor":return".cursorrules";case"windsurf":return".windsurfrules";case"copilot":return".github/copilot-instructions.md";case"gemini":return"GEMINI.md";default:return null}}).filter(Boolean);t.length>0&&(console.log(` Generated: ${t.join(", ")}`),console.log(""))}console.log(" Docs: https://prjct.app/docs"),console.log("")}async feature(e,t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;if(!e)return h.fail("description required"),{success:!1,error:"Description required"};let s=await I.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};h.spin(`planning ${e}...`);let o=await rt.build(t,{description:e}),i=this._breakdownFeatureTasks(e),a=ye(),c=[];for(let m of i){let g=(await this._assignAgentForTask(m,t,o)).agent?.name||"generalist";c.push({task:m,agent:g})}await ot.addTasks(s,c.map(m=>({description:m.task,priority:"medium",type:"feature",section:"active",featureId:a,originFeature:e,agent:m.agent}))),await this.logToMemory(t,"feature_planned",{feature:e,featureId:a,tasks:c.length,assignments:c.map(m=>({task:m.task,agent:m.agent})),timestamp:U.getTimestamp()});let u=c.reduce((m,d)=>(m[d.agent]=(m[d.agent]||0)+1,m),{}),p=Object.entries(u).map(([m,d])=>`${m}:${d}`).join(" ");return h.done(`${i.length} tasks [${p}]`),{success:!0,feature:e,featureId:a,tasks:c}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}async bug(e,t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;if(!e)return h.fail("bug description required"),{success:!1,error:"Description required"};let s=await I.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};h.spin("tracking bug...");let o=await rt.build(t,{description:e}),i=this._detectBugSeverity(e),c=(await this._assignAgentForTask(`fix bug: ${e}`,t,o)).agent?.name||"generalist",p={critical:"critical",high:"high",medium:"medium",low:"low"}[i]||"medium";return await ot.addTask(s,{description:`\u{1F41B} ${e}`,priority:p,type:"bug",section:"active",agent:c}),await this.logToMemory(t,"bug_reported",{bug:e,severity:i,priority:p,agent:c,timestamp:U.getTimestamp()}),h.done(`bug [${i}] \u2192 ${c}`),wt("bug"),{success:!0,bug:e,severity:i,agent:c}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}async architect(e="execute",t=process.cwd()){if(e!=="execute")return{success:!1,message:"\u274C Invalid action. Use: /p:architect execute"};try{let n=await this.ensureProjectInit(t);if(!n.success)return n;console.log(`\u{1F3D7}\uFE0F Architect Mode - Code Generation
1086
- `);let s=await this.getGlobalProjectPath(t),o=us.join(s,"planning","architect-session.md"),i;try{i=await ae.readFile(o)}catch{return{success:!1,message:`\u274C No architect plan found.
1087
-
1088
- Create a plan first:
1089
- 1. Run /p:init in an empty directory
1090
- 2. Answer the discovery questions
1091
- 3. Plan will be auto-generated
1092
- 4. Then run /p:architect execute`}}if(!i||i.trim()==="")return{success:!1,message:"\u274C Architect plan is empty"};console.log(`\u{1F4CB} Reading architect plan...
1093
- `);let a=i.match(/## Project Idea\n(.+)/s),c=i.match(/\*\*Stack:\*\*\n([\s\S]+?)\n\n/),u=i.match(/\*\*Implementation Steps:\*\*\n([\s\S]+?)\n\n/),p=a?a[1].split(`
1094
- `)[0].trim():"Unknown project",m=c?c[1]:"Not specified",d=u?u[1]:"Not specified";return console.log(`\u{1F4DD} Project: ${p}`),console.log(`
1095
- \u{1F527} Stack:
1096
- ${m}`),console.log(`
1097
- \u{1F4CB} Implementation Steps:
1098
- ${d}`),console.log(`
1099
- ${"=".repeat(60)}`),console.log("\u{1F916} READY TO GENERATE CODE"),console.log("=".repeat(60)),console.log(`
1100
- The architect plan is ready. Claude will now:
1101
- 1. Read the architectural plan
1102
- 2. Use Context7 for official documentation
1103
- 3. Generate project structure
1104
- 4. Create starter files with boilerplate
1105
- `),console.log(`
1106
- \u{1F4A1} This command shows the plan.`),console.log(" For code generation, Claude Code will read this plan"),console.log(` and generate the structure automatically.
1107
- `),await this.logToMemory(t,"architect_executed",{timestamp:U.getTimestamp(),idea:p}),{success:!0,plan:i,idea:p}}catch(n){return console.error("\u274C Error:",w(n)),{success:!1,error:w(n)}}}async idea(e,t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;if(!e)return h.fail("idea description required"),{success:!1,error:"Idea description required"};let s=await I.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(e.split(/\s+/).length>20||e.includes("with")||e.includes("that")){h.spin("analyzing idea...");let a=P.getGlobalProjectPath(s),c=us.join(a,"planning","architect-session.md"),u=`# Architect Session
1108
-
1109
- ## Idea
1110
- ${e}
1111
-
1112
- ## Status
1113
- Initialized - awaiting architecture design
1114
-
1115
- ## Next Steps
1116
- 1. Define tech stack
1117
- 2. Create system design
1118
- 3. Break down into features
1119
- 4. Generate roadmap
1120
-
1121
- Generated: ${new Date().toLocaleString()}
1122
- `;return await ze.get("Write")(c,u),await this.logToMemory(t,"idea_architecture_started",{idea:e,timestamp:U.getTimestamp()}),h.done("architecture session created"),console.log(`
1123
- \u{1F4A1} Use /p:architect execute to continue planning
1124
- `),{success:!0,mode:"architecture",idea:e}}else return h.spin("capturing idea..."),await dn.addIdea(s,e),await this.logToMemory(t,"idea_captured",{idea:e,timestamp:U.getTimestamp()}),h.done(`idea captured: ${e.slice(0,40)}`),wt("idea"),{success:!0,mode:"capture",idea:e}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}async spec(e=null,t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await I.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(!e){h.spin("loading specs...");let p=P.getGlobalProjectPath(s),m=us.join(p,"planning","specs");try{let f=(await(await import("node:fs/promises")).readdir(m)).filter(S=>S.endsWith(".md")&&S!==".gitkeep");return f.length===0?(h.warn("no specs yet"),console.log(`
1125
- \u{1F4A1} Create one with /p:spec "feature name"
1126
- `),{success:!0,specs:[]}):(console.log(`
1127
- \u{1F4CB} SPECIFICATIONS
1128
- `),console.log("\u2550".repeat(50)),f.forEach((S,E)=>{let x=S.replace(".md","").replace(/-/g," ");console.log(` ${E+1}. ${x}`)}),console.log(`${"\u2550".repeat(50)}
1129
- `),{success:!0,specs:f})}catch{return h.warn("no specs directory"),{success:!0,specs:[]}}}h.spin("creating spec...");let o=P.getGlobalProjectPath(s),i=us.join(o,"planning","specs");await ae.ensureDir(i);let a=e.toLowerCase().replace(/\s+/g,"-"),c=us.join(i,`${a}.md`),u=`# Specification: ${e}
1130
-
1131
- ## Overview
1132
- [Brief description of the feature]
1133
-
1134
- ## Requirements
1135
- - [ ] Requirement 1
1136
- - [ ] Requirement 2
1137
- - [ ] Requirement 3
1138
-
1139
- ## Design Decisions
1140
- | Decision | Rationale |
1141
- |----------|-----------|
1142
- | | |
1143
-
1144
- ## Tasks (20-30 min each)
1145
- 1. [ ] Task 1 - [description]
1146
- 2. [ ] Task 2 - [description]
1147
- 3. [ ] Task 3 - [description]
1148
-
1149
- ## Acceptance Criteria
1150
- - [ ] Criterion 1
1151
- - [ ] Criterion 2
1152
-
1153
- ## Notes
1154
- [Additional notes and considerations]
1155
-
1156
- ---
1157
- Created: ${new Date().toLocaleString()}
1158
- Status: Draft
1159
- `;return await ze.get("Write")(c,u),await this.logToMemory(t,"spec_created",{feature:e,timestamp:U.getTimestamp()}),h.done(`spec created: ${a}.md`),console.log(`
1160
- \u{1F4DD} Edit: ~/.prjct-cli/projects/${s}/planning/specs/${a}.md`),console.log(`\u{1F4A1} When ready, use /p:feature to add tasks to queue
1161
- `),{success:!0,feature:e,specPath:c}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}}});var ea,On,Hf=y(()=>{"use strict";an();$o();Ye();ee();M();me();Xt();ea=class{static{l(this,"ProjectService")}currentAuthor=null;async ensureInit(e){if(await I.isConfigured(e))return{success:!0};h.spin("initializing project...");let{PlanningCommands:t}=await Promise.resolve().then(()=>(Zi(),Uf)),s=await new t().init(null,e);return s.success?{success:!0}:s}async getProjectId(e){let t=await I.getProjectId(e);if(!t)throw To.notInitialized();return t}async getGlobalPath(e){let t=await this.getProjectId(e);return await P.ensureProjectStructure(t),P.getGlobalProjectPath(t)}async ensureAuthor(){if(this.currentAuthor)return this.currentAuthor;let e=await vs();return this.currentAuthor={name:e.name??void 0,email:e.email??void 0,github:e.github??void 0},this.currentAuthor}getCurrentAuthor(){return this.currentAuthor}clearAuthorCache(){this.currentAuthor=null}async isEmptyDirectory(e){try{return(await ks(e)).filter(s=>!s.startsWith(".")&&s!=="node_modules"&&s!=="package.json"&&s!=="package-lock.json"&&s!=="README.md").length===0}catch(t){return k(t)||console.error(`Directory check error: ${w(t)}`),!0}}async hasExistingCode(e){try{let t=["src","lib","app","components","pages","api","main.go","main.rs","main.py"];return(await ks(e)).some(s=>t.includes(s))}catch(t){return k(t)||console.error(`Code check error: ${w(t)}`),!1}}async isConfigured(e){return await I.isConfigured(e)}async needsMigration(e){return await I.needsMigration(e)}},On=new ea});import{exec as $x}from"node:child_process";import Mx from"node:fs/promises";import Fx from"node:path";import{promisify as Ox}from"node:util";var Su,_x,ta,io,Gf=y(()=>{"use strict";ee();M();zo();Su=Ox($x),_x={commitThreshold:10,dayThreshold:3,significantFiles:["package.json","tsconfig.json","Cargo.toml","go.mod","requirements.txt","pyproject.toml",".env.example","docker-compose.yml","Dockerfile"]},ta=class{static{l(this,"StalenessChecker")}projectPath;config;constructor(e,t={}){this.projectPath=e,this.config={..._x,...t}}async check(e){let t={isStale:!1,reason:null,lastSyncCommit:null,currentCommit:null,commitsSinceSync:0,daysSinceSync:0,changedFiles:[],significantChanges:[]};try{let n=Fx.join(P.getGlobalProjectPath(e),"project.json"),s={};try{s=JSON.parse(await Mx.readFile(n,"utf-8"))}catch{return t.isStale=!0,t.reason="No sync history found. Run `prjct sync` to initialize.",t}t.lastSyncCommit=s.lastSyncCommit||null;let o=s.lastSync;try{let{stdout:i}=await Su("git rev-parse --short HEAD",{cwd:this.projectPath});t.currentCommit=i.trim()}catch{return t.reason="Not a git repository",t}if(!t.lastSyncCommit)return t.isStale=!0,t.reason="No sync commit recorded. Run `prjct sync` to track.",t;if(t.lastSyncCommit===t.currentCommit)return t.reason="Context is up to date",t;try{let{stdout:i}=await Su(`git rev-list --count ${t.lastSyncCommit}..HEAD`,{cwd:this.projectPath});t.commitsSinceSync=parseInt(i.trim(),10)||0}catch{return t.isStale=!0,t.reason="Sync commit no longer exists (history changed). Run `prjct sync`.",t}if(o){let i=new Date(o),a=new Date;t.daysSinceSync=Math.floor((a.getTime()-i.getTime())/(1e3*60*60*24))}try{let{stdout:i}=await Su(`git diff --name-only ${t.lastSyncCommit}..HEAD`,{cwd:this.projectPath});t.changedFiles=i.trim().split(`
1162
- `).filter(Boolean)}catch{t.changedFiles=[]}return t.significantChanges=t.changedFiles.filter(i=>this.config.significantFiles.some(a=>i.endsWith(a)||i.includes(a))),t.commitsSinceSync>=this.config.commitThreshold?(t.isStale=!0,t.reason=`${t.commitsSinceSync} commits since last sync (threshold: ${this.config.commitThreshold})`):t.daysSinceSync>=this.config.dayThreshold?(t.isStale=!0,t.reason=`${t.daysSinceSync} days since last sync (threshold: ${this.config.dayThreshold})`):t.significantChanges.length>0?(t.isStale=!0,t.reason=`Significant files changed: ${t.significantChanges.join(", ")}`):t.commitsSinceSync>0?t.reason=`${t.commitsSinceSync} commits since sync (threshold: ${this.config.commitThreshold})`:t.reason="Context is up to date",t}catch(n){return t.reason=`Error checking staleness: ${w(n)}`,t}}formatStatus(e){let t=[];e.isStale?t.push("CLAUDE.md status: \u26A0\uFE0F STALE"):t.push("CLAUDE.md status: \u2713 Fresh");let n=[];if(e.lastSyncCommit&&n.push(`Last sync: ${e.lastSyncCommit}`),e.currentCommit&&n.push(`Current: ${e.currentCommit}`),e.commitsSinceSync>0&&n.push(`Commits since: ${e.commitsSinceSync}`),e.daysSinceSync>0&&n.push(`Days since: ${e.daysSinceSync}`),e.changedFiles.length>0&&n.push(`Files changed: ${e.changedFiles.length}`),n.length>0){let s=Math.max(...n.map(i=>i.length)),o="\u2500".repeat(s+2);t.push(`\u250C${o}\u2510`);for(let i of n)t.push(`\u2502 ${i.padEnd(s)} \u2502`);t.push(`\u2514${o}\u2518`)}if(e.significantChanges.length>0){t.push(""),t.push("Significant changes:");for(let s of e.significantChanges.slice(0,5))t.push(` \u2022 ${s}`);e.significantChanges.length>5&&t.push(` ... and ${e.significantChanges.length-5} more`)}return e.reason&&(t.push(""),t.push(e.reason)),e.isStale&&(t.push(""),t.push("Run `prjct sync` to update context")),t.join(`
1163
- `)}async getSessionInfo(e){return Cn.getInfo(e)}formatSessionInfo(e){let t=[];if(!e.active)return t.push("Session: \u25CB No active session"),t.join(`
1164
- `);t.push(`Session: \u25B6 Active (${e.duration})`);let n=[];if(e.commandCount>0){let s=new Set,o=[];for(let i of e.commands)s.has(i)||(s.add(i),o.push(i));n.push(`Commands: ${o.join(" \u2192 ")} (${e.commandCount} total)`)}if((e.filesRead>0||e.filesWritten>0)&&n.push(`Files: ${e.filesRead} read, ${e.filesWritten} written`),n.push(`Idle: ${e.expiresIn} until timeout`),n.length>0){let s=Math.max(...n.map(i=>i.length)),o="\u2500".repeat(s+2);t.push(`\u250C${o}\u2510`);for(let i of n)t.push(`\u2502 ${i.padEnd(s)} \u2502`);t.push(`\u2514${o}\u2518`)}return t.join(`
1165
- `)}getWarning(e){return e.isStale?e.commitsSinceSync>0?`\u26A0\uFE0F Context stale (${e.commitsSinceSync} commits behind). Run \`prjct sync\``:e.daysSinceSync>0?`\u26A0\uFE0F Context stale (${e.daysSinceSync} days old). Run \`prjct sync\``:"\u26A0\uFE0F Context may be stale. Run `prjct sync`":null}},io=l((r,e)=>new ta(r,e),"createStalenessChecker")});import zf from"node:fs/promises";import na from"node:path";function ao(r){return r.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 Hx(r,e){let t=[],n=e.replace(/\.[^.]+$/,"").split(/[/\\]/).filter(Boolean);for(let d of n)t.push(...ao(d));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 d of s){let g;for(;(g=d.exec(r))!==null;)g[1]&&t.push(...ao(g[1]))}let o=[/(?:async\s+)?function\s+(\w+)/g,/class\s+(\w+)/g,/interface\s+(\w+)/g,/type\s+(\w+)\s*=/g];for(let d of o){let g;for(;(g=d.exec(r))!==null;)g[1]&&t.push(...ao(g[1]))}let i=/(?:from|import)\s+['"]([^'"]+)['"]/g,a;for(;(a=i.exec(r))!==null;){let d=a[1];if(d.startsWith(".")||d.startsWith("@/"))t.push(...ao(d));else{let g=d.startsWith("@")?d.split("/").slice(0,2).join("/"):d.split("/")[0];t.push(...ao(g))}}let c=/\/\/\s*(.+)/g,u;for(;(u=c.exec(r))!==null;){let d=u[1].toLowerCase().split(/\s+/).filter(g=>g.length>2);t.push(...d)}let p=/\/\*\*?([\s\S]*?)\*\//g,m;for(;(m=p.exec(r))!==null;){let d=m[1].replace(/@\w+/g,"").replace(/\*/g,"").toLowerCase().split(/\s+/).filter(g=>g.length>2&&/^[a-z]+$/.test(g));t.push(...d)}return t.filter(d=>d.length>1&&!Lx.has(d)&&/^[a-z][a-z0-9]*$/.test(d))}async function Jf(r,e){let t=[],n=await zf.readdir(r,{withFileTypes:!0});for(let s of n){if(Ux.has(s.name))continue;let o=na.join(r,s.name);if(s.isDirectory())t.push(...await Jf(o,e));else if(s.isFile()){let i=na.extname(s.name).toLowerCase();Nx.has(i)&&t.push(na.relative(e,o))}}return t}async function Gx(r){let e=await Jf(r,r),t={},n={},s=0,o=50;for(let a=0;a<e.length;a+=o){let c=e.slice(a,a+o),u=await Promise.all(c.map(async p=>{try{let m=await zf.readFile(na.join(r,p),"utf-8"),d=Hx(m,p);return{filePath:p,tokens:d}}catch{return{filePath:p,tokens:[]}}}));for(let{filePath:p,tokens:m}of u){if(m.length===0)continue;t[p]={tokens:m,length:m.length},s+=m.length;let d=new Map;for(let g of m)d.set(g,(d.get(g)||0)+1);for(let[g,f]of d)n[g]||(n[g]=[]),n[g].push({path:p,tf:f})}}let i=Object.keys(t).length;return{documents:t,invertedIndex:n,avgDocLength:i>0?s/i:0,totalDocs:i,builtAt:new Date().toISOString()}}function Jx(r,e){let t={invertedIndex:e.invertedIndex,avgDocLength:e.avgDocLength,totalDocs:e.totalDocs,builtAt:e.builtAt,docLengths:Object.fromEntries(Object.entries(e.documents).map(([n,s])=>[n,s.length]))};xt.setDoc(r,zx,t)}async function Wf(r,e){let t=await Gx(r);return Jx(e,t),t}var Nx,Lx,Ux,zx,Bf=y(()=>{"use strict";Yt();Nx=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".cs",".rb",".php",".vue",".svelte"]),Lx=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"]),Ux=new Set(["node_modules",".git","dist","build","out",".next","coverage",".cache",".turbo",".vercel","__pycache__","vendor","target"]);l(ao,"splitIdentifier");l(Hx,"tokenizeFile");l(Jf,"listFiles");l(Gx,"buildIndex");zx="bm25-index";l(Jx,"saveIndex");l(Wf,"indexProject")});import bu from"node:fs/promises";import hn from"node:path";function Kx(r){let e=[],t,n=new RegExp(qx.source,"g");for(;(t=n.exec(r))!==null;){let s=t[1];(s.startsWith(".")||s.startsWith("@/"))&&e.push(s)}return e}async function Xx(r,e,t){let n;if(r.startsWith("@/"))n=hn.join(t,"src",r.slice(2));else{let s=hn.dirname(hn.join(t,e));n=hn.resolve(s,r)}for(let s of Vx){let o=n+s;try{if((await bu.stat(o)).isFile())return hn.relative(t,o)}catch{}}return null}async function Vf(r,e){let t=[],n=await bu.readdir(r,{withFileTypes:!0});for(let s of n){if(Bx.has(s.name))continue;let o=hn.join(r,s.name);if(s.isDirectory())t.push(...await Vf(o,e));else if(s.isFile()){let i=hn.extname(s.name).toLowerCase();Wx.has(i)&&t.push(hn.relative(e,o))}}return t}async function Yx(r){let e=await Vf(r,r),t={},n={},s=0,o=50;for(let i=0;i<e.length;i+=o){let a=e.slice(i,i+o),c=await Promise.all(a.map(async u=>{try{let p=await bu.readFile(hn.join(r,u),"utf-8"),m=Kx(p),d=[];for(let g of m){let f=await Xx(g,u,r);f&&f!==u&&d.push(f)}return{filePath:u,imports:d}}catch{return{filePath:u,imports:[]}}}));for(let{filePath:u,imports:p}of c)if(p.length!==0){t[u]=p,s+=p.length;for(let m of p)n[m]||(n[m]=[]),n[m].push(u)}}return{forward:t,reverse:n,fileCount:e.length,edgeCount:s,builtAt:new Date().toISOString()}}function Qx(r,e){xt.setDoc(r,qf,e)}function Kf(r){return xt.getDoc(r,qf)}async function Xf(r,e){let t=await Yx(r);return Qx(e,t),t}var Wx,Bx,Vx,qx,qf,Pu=y(()=>{"use strict";Yt();Wx=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),Bx=new Set(["node_modules",".git","dist","build","out",".next","coverage",".cache",".turbo",".vercel"]),Vx=["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"],qx=/(?:import|from)\s+['"]([^'"]+)['"]/g;l(Kx,"extractImportSources");l(Xx,"resolveImport");l(Vf,"listFiles");l(Yx,"buildGraph");qf="import-graph";l(Qx,"saveGraph");l(Kf,"loadGraph");l(Xf,"indexImports")});function Yf(r,e){let t=[...r.added,...r.modified],n=new Set(t),s=new Set,o=Kf(e);if(o)for(let c of t){let u=o.reverse[c];if(u)for(let p of u)n.has(p)||s.add(p)}let i=Array.from(s),a=[...t,...i];return{directlyChanged:t,affectedByImports:i,deleted:r.deleted,allAffected:a}}function Qf(r){let e=new Set;for(let t of r){let n=t.toLowerCase();(n.endsWith(".tsx")||n.endsWith(".jsx")||n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".vue")||n.endsWith(".svelte")||n.includes("/components/")||n.includes("/pages/")||n.includes("/app/"))&&(e.add("frontend"),e.add("uxui")),(n.includes(".test.")||n.includes(".spec.")||n.includes("__tests__")||n.includes("/test/"))&&e.add("testing"),(n.includes("dockerfile")||n.includes("docker-compose")||n.includes(".dockerignore")||n.includes(".github/")||n.includes("ci/")||n.includes("cd/"))&&e.add("devops"),(n.endsWith(".sql")||n.includes("prisma")||n.includes("drizzle")||n.includes("migration")||n.includes("/db/"))&&e.add("database"),(n.endsWith(".ts")||n.endsWith(".js"))&&!n.includes(".test.")&&!n.includes(".spec.")&&!n.endsWith(".d.ts")&&e.add("backend")}return e}var Zf=y(()=>{"use strict";Pu();l(Yf,"propagateChanges");l(Qf,"affectedDomains")});import Cu from"node:fs/promises";import sa from"node:path";async function eh(r,e){let t=[],n=await Cu.readdir(r,{withFileTypes:!0}).catch(()=>[]);for(let s of n){let o=String(s.name);if(eT.has(o)||o.startsWith(".")&&o!==".env.example")continue;let i=sa.join(r,o);if(s.isDirectory())t.push(...await eh(i,e));else if(s.isFile()){let a=sa.extname(o).toLowerCase();Zx.has(a)&&t.push(sa.relative(e,i))}}return t}function tT(r){if(typeof Bun<"u"&&Bun.hash)return`xxh64:${Bun.hash(r).toString(36)}`;let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return`fnv1a:${(e>>>0).toString(36)}`}async function nT(r){let e=await eh(r,r),t=new Map,n=100;for(let s=0;s<e.length;s+=n){let o=e.slice(s,s+n),i=await Promise.all(o.map(async a=>{try{let c=sa.join(r,a),[u,p]=await Promise.all([Cu.readFile(c,"utf-8"),Cu.stat(c)]);return{path:a,hash:tT(u),size:p.size,mtime:p.mtime.toISOString()}}catch{return null}}));for(let a of i)a&&t.set(a.path,a)}return t}function sT(r,e){let t=[],n=[],s=[];for(let[i,a]of r){let c=e.get(i);c?c.hash!==a.hash?n.push(i):s.push(i):t.push(i)}let o=[];for(let i of e.keys())r.has(i)||o.push(i);return{added:t,modified:n,deleted:o,unchanged:s}}function vu(r,e){let t=xt.getDb(r);t.transaction(()=>{t.prepare("DELETE FROM index_checksums").run();let n=t.prepare("INSERT INTO index_checksums (path, checksum, size, mtime) VALUES (?, ?, ?, ?)");for(let[,s]of e)n.run(s.path,s.hash,s.size,s.mtime)})(),xt.setDoc(r,"file-hashes-meta",{fileCount:e.size,builtAt:new Date().toISOString()})}function rT(r){let e=new Map;try{let t=xt.query(r,"SELECT path, checksum, size, mtime FROM index_checksums");for(let n of t)e.set(n.path,{path:n.path,hash:n.checksum,size:n.size||0,mtime:n.mtime||""})}catch{}return e}async function xu(r,e){let[t,n]=await Promise.all([nT(r),Promise.resolve(rT(e))]);return{diff:sT(t,n),currentHashes:t}}function th(r){return xt.hasDoc(r,"file-hashes-meta")}var Zx,eT,nh=y(()=>{"use strict";Yt();Zx=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".css",".scss",".html",".vue",".svelte",".py",".go",".rs",".yaml",".yml",".toml"]),eT=new Set(["node_modules",".git","dist","build","out",".next","coverage",".cache",".turbo",".vercel",".prjct"]);l(eh,"listProjectFiles");l(tT,"hashContent");l(nT,"computeHashes");l(sT,"diffHashes");l(vu,"saveHashes");l(rT,"loadHashes");l(xu,"detectChanges");l(th,"hasHashRegistry")});import{exec as oT}from"node:child_process";import{promisify as iT}from"node:util";async function lT(r,e=100){try{let{stdout:t}=await aT(`git log --name-only --pretty=format:'---COMMIT---' -${e}`,{cwd:r,maxBuffer:10485760}),n=[],s=null;for(let o of t.split(`
1166
- `)){let i=o.trim();i==="---COMMIT---"?(s&&s.size>0&&s.size<=rh&&n.push(s),s=new Set):i&&s&&uT(i)&&s.add(i)}return s&&s.size>0&&s.size<=rh&&n.push(s),n}catch{return[]}}function uT(r){return/\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|cs|rb|php|vue|svelte)$/i.test(r)&&!r.includes("node_modules/")}async function pT(r,e=100){let t=await lT(r,e),n=new Map,s=new Map;for(let i of t){let a=Array.from(i);for(let c of a)n.set(c,(n.get(c)||0)+1);for(let c=0;c<a.length;c++)for(let u=c+1;u<a.length;u++){let p=dT(a[c],a[u]);s.set(p,(s.get(p)||0)+1)}}let o={};for(let[i,a]of s){let[c,u]=i.split("\0"),p=n.get(c)||0,m=n.get(u)||0;if(p<sh||m<sh)continue;let d=p+m-a,g=d>0?a/d:0;g<cT||(o[c]||(o[c]={}),o[u]||(o[u]={}),o[c][u]=g,o[u][c]=g)}return{matrix:o,commitsAnalyzed:t.length,filesAnalyzed:n.size,builtAt:new Date().toISOString()}}function dT(r,e){return r<e?`${r}\0${e}`:`${e}\0${r}`}function gT(r,e){xt.setDoc(r,mT,e)}async function oh(r,e,t=100){let n=await pT(r,t);return gT(e,n),n}var aT,cT,sh,rh,mT,ih=y(()=>{"use strict";Yt();aT=iT(oT),cT=.1,sh=2,rh=30;l(lT,"parseGitLog");l(uT,"isSourceFile");l(pT,"buildMatrix");l(dT,"pairKey");mT="cochange-index";l(gT,"saveMatrix");l(oh,"indexCoChanges")});function We(r){return`<!-- source: ${r.file}, ${r.type} -->`}function yn(){let r={file:"unknown",type:"detected"};return{name:{...r},version:{...r},ecosystem:{...r},languages:{...r},frameworks:{...r},commands:{...r},projectType:{...r},git:{file:"git",type:"detected"}}}var ra=y(()=>{"use strict";l(We,"cite");l(yn,"defaultSources")});function fT(r,e){let t=r.sources||yn();return`# ${r.name} - Project Rules
1167
- <!-- projectId: ${r.projectId} -->
1168
- <!-- Generated: ${new Date().toISOString()} -->
1169
- <!-- Ecosystem: ${r.ecosystem} | Type: ${r.projectType} -->
1170
-
1171
- ## THIS PROJECT (${r.ecosystem})
1172
-
1173
- ${We(t.ecosystem)}
1174
- **Type:** ${r.projectType}
1175
- **Path:** ${r.repoPath}
1176
-
1177
- ### Commands (USE THESE, NOT OTHERS)
1178
-
1179
- ${We(t.commands)}
1180
- | Action | Command |
1181
- |--------|---------|
1182
- | Install dependencies | \`${r.commands.install}\` |
1183
- | Run dev server | \`${r.commands.dev}\` |
1184
- | Run tests | \`${r.commands.test}\` |
1185
- | Build | \`${r.commands.build}\` |
1186
- | Lint | \`${r.commands.lint}\` |
1187
- | Format | \`${r.commands.format}\` |
1188
-
1189
- ### Code Conventions
1190
-
1191
- ${We(t.languages)}
1192
- - **Languages**: ${r.languages.join(", ")||"Not detected"}
1193
- ${We(t.frameworks)}
1194
- - **Frameworks**: ${r.frameworks.join(", ")||"Not detected"}
1195
-
1196
- ---
1197
-
1198
- ## PRJCT RULES
1199
-
1200
- ### Path Resolution
1201
- **ALL prjct writes go to**: \`~/.prjct-cli/projects/${r.projectId}/\`
1202
- - NEVER write to \`.prjct/\`
1203
- - NEVER write to \`./\` for prjct data
1204
-
1205
- ### Workflow
1206
- \`\`\`
1207
- p. sync \u2192 p. task "desc" \u2192 [work] \u2192 p. done \u2192 p. ship
1208
- \`\`\`
1209
-
1210
- | Command | Action |
1211
- |---------|--------|
1212
- | \`p. sync\` | Re-analyze project |
1213
- | \`p. task X\` | Start task |
1214
- | \`p. done\` | Complete subtask |
1215
- | \`p. ship X\` | Ship feature |
1216
-
1217
- ---
1218
-
1219
- ## PROJECT STATE
1220
-
1221
- ${We(t.name)}
1222
- | Field | Value |
1223
- |-------|-------|
1224
- | Name | ${r.name} |
1225
- | Version | ${r.version} |
1226
- | Ecosystem | ${r.ecosystem} |
1227
- | Branch | ${r.branch} |
1228
- | Files | ~${r.fileCount} |
1229
- | Commits | ${r.commits} |
1230
-
1231
- ---
1232
-
1233
- ## AGENTS
1234
-
1235
- Load from \`~/.prjct-cli/projects/${r.projectId}/agents/\`:
1236
-
1237
- **Workflow**: ${r.agents.workflow.join(", ")}
1238
- **Domain**: ${r.agents.domain.join(", ")||"none"}
1239
- `}function hT(r,e){let t=r.sources||yn(),n=[];return n.push("---"),n.push(`description: prjct context for ${r.name}`),n.push("globs:"),n.push("alwaysApply: true"),n.push("---"),n.push(""),n.push(`You are working on ${r.name}, a ${r.projectType} ${r.ecosystem} project.`),n.push(""),n.push(We(t.languages)),n.push("## Tech Stack"),r.languages.length>0&&n.push(`- Languages: ${r.languages.join(", ")}`),r.frameworks.length>0&&n.push(`- Frameworks: ${r.frameworks.join(", ")}`),n.push(""),n.push(We(t.commands)),n.push("## Commands"),n.push(`- Install: \`${r.commands.install}\``),n.push(`- Dev: \`${r.commands.dev}\``),n.push(`- Test: \`${r.commands.test}\``),n.push(`- Build: \`${r.commands.build}\``),n.push(""),n.push("## Code Style"),n.push(`- Follow ${r.ecosystem} conventions`),n.push("- Match existing code patterns in this project"),n.push("- Use idiomatic constructs for the language"),n.push(""),n.push("## Best Practices"),n.push("- Write clean, readable code"),n.push("- Add comments only for complex logic"),n.push("- Keep functions small and focused"),n.push("- Handle errors appropriately"),n.push("- Write tests for new functionality"),n.join(`
1240
- `)}function yT(r,e){let t=r.sources||yn(),n=[];return n.push("# Copilot Instructions"),n.push(""),n.push(`This is ${r.name}, a ${r.ecosystem} project.`),n.push(""),n.push(We(t.ecosystem)),n.push("## Project Info"),n.push(`- Type: ${r.projectType}`),n.push(`- Stack: ${r.frameworks.join(", ")||r.ecosystem}`),n.push(""),n.push("## Conventions"),n.push(`- Follow ${r.ecosystem} conventions`),n.push("- Match existing code patterns"),n.push("- Keep code clean and readable"),n.push(""),n.push(We(t.commands)),n.push("## Commands"),n.push(`- Test: \`${r.commands.test}\``),n.push(`- Build: \`${r.commands.build}\``),n.join(`
1241
- `)}function wT(r,e){let t=r.sources||yn(),n=[];return n.push("---"),n.push(`description: prjct context for ${r.name}`),n.push("trigger: always_on"),n.push("---"),n.push(""),n.push(`# ${r.name}`),n.push(""),n.push(`${r.projectType} project using ${r.ecosystem}.`),n.push(""),n.push(We(t.languages)),n.push("## Stack"),n.push(`- ${r.languages.join(", ")}`),r.frameworks.length>0&&n.push(`- ${r.frameworks.join(", ")}`),n.push(""),n.push(We(t.commands)),n.push("## Commands"),n.push("```bash"),n.push("# Install"),n.push(r.commands.install),n.push("# Dev"),n.push(r.commands.dev),n.push("# Test"),n.push(r.commands.test),n.push("# Build"),n.push(r.commands.build),n.push("```"),n.push(""),n.push("## Rules"),n.push(`- Follow ${r.ecosystem} conventions`),n.push("- Match existing project patterns"),n.push("- Clean code, minimal comments"),n.push("- Test new functionality"),n.join(`
1242
- `)}function kT(r,e){let n={systemMessage:[`You are working on ${r.name}, a ${r.projectType} ${r.ecosystem} project.`,"",`Stack: ${r.languages.join(", ")}${r.frameworks.length>0?` with ${r.frameworks.join(", ")}`:""}`,"","Commands:",`- Install: ${r.commands.install}`,`- Dev: ${r.commands.dev}`,`- Test: ${r.commands.test}`,`- Build: ${r.commands.build}`,"",`Follow ${r.ecosystem} conventions. Match existing code patterns.`].join(`
1243
- `),models:[],contextProviders:[{name:"code"},{name:"docs"},{name:"diff"},{name:"terminal"},{name:"problems"},{name:"folder"},{name:"codebase"}],slashCommands:[{name:"edit",description:"Edit selected code"},{name:"comment",description:"Add comments to code"},{name:"share",description:"Export conversation"},{name:"cmd",description:"Run terminal command"}],customCommands:[{name:"test",prompt:`Write tests for the selected code. Use the project's testing conventions. Test command: ${r.commands.test}`}]};return JSON.stringify(n,null,2)}function ah(r){return{claude:fT,cursor:hT,copilot:yT,windsurf:wT,continue:kT}[r]||null}var Tu=y(()=>{"use strict";ra();l(fT,"formatForClaude");l(hT,"formatForCursor");l(yT,"formatForCopilot");l(wT,"formatForWindsurf");l(kT,"formatForContinue");l(ah,"getFormatter")});import{exec as ST}from"node:child_process";import bT from"node:os";import co from"node:path";import{promisify as PT}from"node:util";function ch(r){return oa[r]||null}async function Eu(r){try{return await CT(`which ${r}`),!0}catch{return!1}}async function ia(r=process.cwd()){let e=[];return await Eu("claude")&&e.push("claude"),(await Eu("cursor")||await C(co.join(r,".cursor")))&&e.push("cursor"),await C(co.join(r,".github"))&&e.push("copilot"),(await Eu("windsurf")||await C(co.join(r,".windsurf")))&&e.push("windsurf"),(await C(co.join(r,".continue"))||await C(co.join(bT.homedir(),".continue")))&&e.push("continue"),e}async function lh(r,e=process.cwd()){if(r==="auto"){let t=await ia(e);return t.length>0?t:["claude"]}return r==="all"?vT:r.filter(t=>oa[t])}var CT,oa,lo,vT,ju=y(()=>{"use strict";me();CT=PT(ST),oa={claude:{id:"claude",name:"Claude Code",outputFile:"CLAUDE.md",outputPath:"global",maxTokens:6e3,format:"detailed",description:"Anthropic Claude Code CLI"},cursor:{id:"cursor",name:"Cursor",outputFile:".cursor/rules/prjct.mdc",outputPath:"repo",maxTokens:2e3,format:"concise",description:"Cursor AI Editor"},copilot:{id:"copilot",name:"GitHub Copilot",outputFile:".github/copilot-instructions.md",outputPath:"repo",maxTokens:1500,format:"minimal",description:"GitHub Copilot"},windsurf:{id:"windsurf",name:"Windsurf",outputFile:".windsurf/rules/prjct.md",outputPath:"repo",maxTokens:2e3,format:"concise",description:"Codeium Windsurf Editor"},continue:{id:"continue",name:"Continue.dev",outputFile:".continue/config.json",outputPath:"repo",maxTokens:1500,format:"json",description:"Continue.dev open-source AI assistant"}},lo=["claude"],vT=Object.keys(oa);l(ch,"getAIToolConfig");l(Eu,"commandExists");l(ia,"detectInstalledTools");l(lh,"resolveToolIds")});import Au from"node:fs/promises";import Iu from"node:path";async function uh(r,e,t,n=lo){let s=[];for(let o of n){let i=ch(o);if(!i){s.push({toolId:o,outputFile:"",outputPath:"",success:!1,error:`Unknown tool: ${o}`});continue}let a=await xT(r,i,e,t);s.push(a)}return s}async function xT(r,e,t,n){let s=ah(e.id);if(!s)return{toolId:e.id,outputFile:e.outputFile,outputPath:"",success:!1,error:`No formatter for: ${e.id}`};try{let o=s(r,e),i;e.outputPath==="repo"?i=Iu.join(n,e.outputFile):i=Iu.join(t,"context",e.outputFile),await Au.mkdir(Iu.dirname(i),{recursive:!0});try{let a=await Au.readFile(i,"utf-8"),c=Qr(a);if(!c.valid){console.warn(`\u26A0\uFE0F ${e.outputFile} has invalid preserve blocks:`);for(let u of c.errors)console.warn(` ${u}`)}o=Yr(o,a)}catch{}return await Au.writeFile(i,o,"utf-8"),{toolId:e.id,outputFile:e.outputFile,outputPath:i,success:!0}}catch(o){return{toolId:e.id,outputFile:e.outputFile,outputPath:"",success:!1,error:w(o)}}}var ph=y(()=>{"use strict";M();Ni();Tu();ju();l(uh,"generateAIToolContexts");l(xT,"generateForTool")});var dh=y(()=>{"use strict";Tu();ph();ju()});import ds from"node:fs/promises";import ct from"node:path";var aa,mh=y(()=>{"use strict";ee();ra();ne();Ni();mu();aa=class{static{l(this,"ContextFileGenerator")}config;constructor(e){this.config=e}async writeWithPreservation(e,t){let n=t;try{let s=await ds.readFile(e,"utf-8"),o=Qr(s);if(!o.valid){let i=ct.basename(e);console.warn(`\u26A0\uFE0F ${i} has invalid preserve blocks:`);for(let a of o.errors)console.warn(` ${a}`)}n=Yr(t,s)}catch{}await ds.writeFile(e,n,"utf-8")}async generate(e,t,n,s,o){let i=ct.join(this.config.globalPath,"context");return await Promise.all([this.generateClaudeMd(i,e,t,n,s,o),this.generateNowMd(i),this.generateNextMd(i),this.generateIdeasMd(i),this.generateShippedMd(i)]),["context/CLAUDE.md","context/now.md","context/next.md","context/ideas.md","context/shipped.md"]}async generateClaudeMd(e,t,n,s,o,i){let a=o.filter(d=>d.type==="workflow").map(d=>d.name),c=o.filter(d=>d.type==="domain").map(d=>d.name),u=i||yn(),p=`# ${n.name} - Project Rules
1244
- <!-- projectId: ${this.config.projectId} -->
1245
- <!-- Generated: ${b()} -->
1246
- <!-- Ecosystem: ${n.ecosystem} | Type: ${n.projectType} -->
1247
-
1248
- ## THIS PROJECT (${n.ecosystem})
1249
-
1250
- ${We(u.ecosystem)}
1251
- **Type:** ${n.projectType}
1252
- **Path:** ${this.config.projectPath}
1253
-
1254
- ### Commands (USE THESE, NOT OTHERS)
1255
-
1256
- ${We(u.commands)}
1257
- | Action | Command |
1258
- |--------|---------|
1259
- | Install dependencies | \`${s.install}\` |
1260
- | Run dev server | \`${s.dev}\` |
1261
- | Run tests | \`${s.test}\` |
1262
- | Build | \`${s.build}\` |
1263
- | Lint | \`${s.lint}\` |
1264
- | Format | \`${s.format}\` |
1265
-
1266
- ### Code Conventions
1267
-
1268
- ${We(u.languages)}
1269
- - **Languages**: ${n.languages.join(", ")||"Not detected"}
1270
- ${We(u.frameworks)}
1271
- - **Frameworks**: ${n.frameworks.join(", ")||"Not detected"}
1272
-
1273
- ---
1274
-
1275
- ## PRJCT RULES
1276
-
1277
- ### Path Resolution
1278
- **ALL prjct writes go to**: \`~/.prjct-cli/projects/${this.config.projectId}/\`
1279
- - NEVER write to \`.prjct/\`
1280
- - NEVER write to \`./\` for prjct data
1281
-
1282
- ### Workflow
1283
- \`\`\`
1284
- p. sync \u2192 p. task "desc" \u2192 [work] \u2192 p. done \u2192 p. ship
1285
- \`\`\`
1286
-
1287
- | Command | Action |
1288
- |---------|--------|
1289
- | \`p. sync\` | Re-analyze project |
1290
- | \`p. task X\` | Start task |
1291
- | \`p. done\` | Complete subtask |
1292
- | \`p. ship X\` | Ship feature |
1293
-
1294
- ---
1295
-
1296
- ## PROJECT STATE
1297
-
1298
- ${We(u.name)}
1299
- | Field | Value |
1300
- |-------|-------|
1301
- | Name | ${n.name} |
1302
- | Version | ${n.version} |
1303
- | Ecosystem | ${n.ecosystem} |
1304
- | Branch | ${t.branch} |
1305
- | Files | ~${n.fileCount} |
1306
- | Commits | ${t.commits} |
1307
-
1308
- ---
1309
-
1310
- ## AGENTS
1311
-
1312
- Load from \`~/.prjct-cli/projects/${this.config.projectId}/agents/\`:
1313
-
1314
- **Workflow**: ${a.join(", ")}
1315
- **Domain**: ${c.join(", ")||"none"}
1316
- `,m=ct.join(e,"CLAUDE.md");await this.writeWithPreservation(m,p)}async generateNowMd(e){let t=null;try{let s=ct.join(this.config.globalPath,"storage","state.json");t=JSON.parse(await ds.readFile(s,"utf-8")).currentTask}catch{}let n=t?`# NOW
1317
-
1318
- **${t.description}**
1319
-
1320
- Started: ${t.startedAt}
1321
- ${t.branch?`Branch: ${t.branch.name}`:""}
1322
- `:`# NOW
1323
-
1324
- _No active task_
1325
-
1326
- Use \`p. task "description"\` to start working.
1327
- `;await this.writeWithPreservation(ct.join(e,"now.md"),n)}async generateNextMd(e){let t={tasks:[]};try{let s=ct.join(this.config.globalPath,"storage","queue.json");t=JSON.parse(await ds.readFile(s,"utf-8"))}catch{}let n=`# NEXT
1328
-
1329
- ${t.tasks.length>0?t.tasks.map((s,o)=>`${o+1}. ${s.description}${s.priority?` [${s.priority}]`:""}`).join(`
1330
- `):"_Empty queue_"}
1331
- `;await this.writeWithPreservation(ct.join(e,"next.md"),n)}async generateIdeasMd(e){let t={ideas:[]};try{let s=ct.join(this.config.globalPath,"storage","ideas.json");t=JSON.parse(await ds.readFile(s,"utf-8"))}catch{}let n=`# IDEAS
1332
-
1333
- ${t.ideas.length>0?t.ideas.map(s=>`- ${s.text}${s.priority?` [${s.priority}]`:""}`).join(`
1334
- `):"_No ideas captured yet_"}
1335
- `;await this.writeWithPreservation(ct.join(e,"ideas.md"),n)}async generateShippedMd(e){let t={shipped:[]};try{let s=ct.join(this.config.globalPath,"storage","shipped.json");t=JSON.parse(await ds.readFile(s,"utf-8"))}catch{}let n=`# SHIPPED \u{1F680}
1336
-
1337
- ${t.shipped.length>0?t.shipped.slice(-10).map(s=>`- **${s.name}**${s.version?` v${s.version}`:""} - ${s.shippedAt}`).join(`
1338
- `):"_Nothing shipped yet_"}
1339
-
1340
- **Total shipped:** ${t.shipped.length}
1341
- `;await this.writeWithPreservation(ct.join(e,"shipped.md"),n)}async generateMonorepoContexts(e,t,n,s){let o=await P.detectMonorepo(this.config.projectPath);if(!o.isMonorepo)return[];let i=[],a=new Zr(this.config.projectPath);await a.initialize();for(let c of o.packages){if(!c.hasPrjctMd)continue;let u=await a.getPackageContext(c.name);if(!u)continue;let p=await this.generatePackageClaudeMd(c,u,e,t,n,s),m=ct.join(c.path,"CLAUDE.md");await this.writeWithPreservation(m,p),i.push(ct.relative(this.config.projectPath,m))}return i}async generatePackageClaudeMd(e,t,n,s,o,i){let a=i.filter(m=>m.type==="workflow").map(m=>m.name),c=i.filter(m=>m.type==="domain").map(m=>m.name),u=s.version,p=e.name;try{let m=ct.join(e.path,"package.json"),d=JSON.parse(await ds.readFile(m,"utf-8"));u=d.version||s.version,p=d.name||e.name}catch{}return`# ${p} - Package Rules
1342
- <!-- package: ${e.relativePath} -->
1343
- <!-- monorepo: ${s.name} -->
1344
- <!-- Generated: ${b()} -->
1345
- <!-- Sources: ${t.sources.join(" \u2192 ")} -->
1346
-
1347
- ## THIS PACKAGE
1348
-
1349
- **Name:** ${p}
1350
- **Path:** ${e.relativePath}
1351
- **Version:** ${u}
1352
- **Monorepo:** ${s.name}
1353
-
1354
- ---
1355
-
1356
- ## INHERITED CONTEXT
1357
-
1358
- ${t.content||"_No PRJCT.md rules defined_"}
1359
-
1360
- ${t.overrides.length>0?`
1361
- **Overrides:** ${t.overrides.join(", ")}
1362
- `:""}
1363
-
1364
- ---
1365
-
1366
- ## COMMANDS
1367
-
1368
- | Action | Command |
1369
- |--------|---------|
1370
- | Install | \`${o.install}\` |
1371
- | Dev | \`${o.dev}\` |
1372
- | Test | \`${o.test}\` |
1373
- | Build | \`${o.build}\` |
1374
-
1375
- ---
1376
-
1377
- ## PROJECT STATE
1378
-
1379
- | Field | Value |
1380
- |-------|-------|
1381
- | Package | ${p} |
1382
- | Monorepo | ${s.name} |
1383
- | Branch | ${n.branch} |
1384
- | Ecosystem | ${s.ecosystem} |
1385
-
1386
- ---
1387
-
1388
- ## AGENTS
1389
-
1390
- Load from \`~/.prjct-cli/projects/${this.config.projectId}/agents/\`:
1391
-
1392
- **Workflow**: ${a.join(", ")}
1393
- **Domain**: ${c.join(", ")||"none"}
1394
- `}}});import Du from"node:fs/promises";import Ru from"node:path";var $u,Mu,gh,fh=y(()=>{"use strict";M();$u=".prjct-state.md",Mu=class{static{l(this,"LocalStateGenerator")}async generate(e,t){let n=Ru.join(e,$u),s=this.toMarkdown(t);await Du.writeFile(n,s,"utf-8")}async remove(e){let t=Ru.join(e,$u);try{await Du.unlink(t)}catch(n){if(!k(n))throw n}}async exists(e){let t=Ru.join(e,$u);try{return await Du.access(t),!0}catch{return!1}}toMarkdown(e){let t=["<!-- Auto-generated by prjct - DO NOT EDIT -->","<!-- This file provides local state persistence for AI tools -->","","# prjct State",""];if(e.currentTask){let n=e.currentTask;if(t.push("## Current Task"),t.push(""),t.push(`**${n.description}**`),t.push(""),t.push(`- Started: ${n.startedAt}`),n.linearId&&t.push(`- Linear: ${n.linearId}`),n.branch&&t.push(`- Branch: ${n.branch}`),t.push(`- Status: ${n.status||"active"}`),t.push(""),n.subtasks&&n.subtasks.length>0){t.push("### Subtasks"),t.push(""),n.subtasks.forEach((a,c)=>{let u=a.status==="completed"?"\u2705":a.status==="in_progress"?"\u25B6\uFE0F":"\u23F3",p=c===n.currentSubtaskIndex?" \u2190 **Active**":"";t.push(`${c+1}. ${u} ${a.description}${p}`)}),t.push("");let s=n.subtasks.filter(a=>a.status==="completed").length,o=n.subtasks.length,i=Math.round(s/o*100);t.push(`**Progress**: ${s}/${o} (${i}%)`),t.push("")}}else t.push("*No active task*"),t.push(""),t.push('Start a task with `p. task "description"`'),t.push("");if(e.previousTask){let n=e.previousTask;t.push("---"),t.push(""),t.push("## Previous Task"),t.push(""),t.push(`**${n.description}**`),t.push(""),t.push(`- Status: ${n.status}`),n.prUrl&&t.push(`- PR: ${n.prUrl}`),t.push("")}return t.push("---"),t.push(`*Last updated: ${e.lastUpdated||new Date().toISOString()}*`),t.push(""),t.join(`
1395
- `)}},gh=new Mu});import Fu from"node:fs/promises";import TT from"node:os";import hh from"node:path";function Ou(){return hh.join(TT.homedir(),".prjct-cli","skills",ET)}function jT(){return{version:1,generatedAt:new Date().toISOString(),skills:{}}}async function uo(){try{let r=await Fu.readFile(Ou(),"utf-8");return JSON.parse(r)}catch{return jT()}}async function _u(r){let e=Ou();await Fu.mkdir(hh.dirname(e),{recursive:!0}),r.generatedAt=new Date().toISOString(),await Fu.writeFile(e,JSON.stringify(r,null,2),"utf-8")}async function AT(r){let e=await uo();e.skills[r.name]=r,await _u(e)}async function IT(r){let e=await uo();return r in e.skills?(delete e.skills[r],await _u(e),!0):!1}async function DT(r){return(await uo()).skills[r]||null}async function RT(){return(await uo()).skills}function $T(){return Ou()}var ET,po,yh=y(()=>{"use strict";ET=".skill-lock.json";l(Ou,"getLockFilePath");l(jT,"createEmptyLockFile");l(uo,"read");l(_u,"write");l(AT,"addEntry");l(IT,"removeEntry");l(DT,"getEntry");l(RT,"getAll");l($T,"getPath");po={read:uo,write:_u,addEntry:AT,removeEntry:IT,getEntry:DT,getAll:RT,getPath:$T}});import{exec as MT}from"node:child_process";import wn from"node:fs/promises";import Lu from"node:os";import Qe from"node:path";import{promisify as FT}from"node:util";import{glob as wh}from"glob";function Sh(r){if(r.startsWith("./")||r.startsWith("/")||r.startsWith("~")){let n=r.startsWith("~")?Qe.join(Lu.homedir(),r.slice(1)):Qe.resolve(r);return{type:"local",localPath:n,url:n}}let e=r.indexOf("@");if(e>0){let n=r.slice(0,e),s=r.slice(e+1),[o,i]=n.split("/");if(o&&i)return{type:"github",owner:o,repo:i,skillName:s,url:`https://github.com/${o}/${i}`}}let t=r.split("/");if(t.length===2&&t[0]&&t[1])return{type:"github",owner:t[0],repo:t[1],url:`https://github.com/${t[0]}/${t[1]}`};throw new Error(`Invalid source format: "${r}". Expected "owner/repo", "owner/repo@skill-name", or "./local-path"`)}async function bh(r){let e=[];try{let s=Qe.join(r,"SKILL.md");await wn.access(s);let o=Qe.basename(r);e.push({name:o,filePath:s})}catch{}let t=await wh("*/SKILL.md",{cwd:r,absolute:!0});for(let s of t){let o=Qe.basename(Qe.dirname(s));e.some(i=>i.name===o)||e.push({name:o,filePath:s})}let n=await wh("skills/*/SKILL.md",{cwd:r,absolute:!0});for(let s of n){let o=Qe.basename(Qe.dirname(s));e.some(i=>i.name===o)||e.push({name:o,filePath:s})}return e}function OT(r,e,t){let n=new Date().toISOString(),s=["_prjct:",` sourceUrl: ${e.url}`,` sourceType: ${e.type}`,` installedAt: ${n}`];t&&s.push(` sha: ${t}`);let o=/^---\s*\n([\s\S]*?)\n---/,i=r.match(o);if(i){let a=i[1];a=a.replace(/\n?_prjct:[\s\S]*?(?=\n[a-zA-Z]|\n---|\s*$)/g,"");let c=`${a.trimEnd()}
1396
- ${s.join(`
1397
- `)}`;return r.replace(o,`---
1398
- ${c}
1399
- ---`)}return`---
1400
- ${s.join(`
1401
- `)}
1402
- ---
1403
-
1404
- ${r}`}function Uu(){return Qe.join(Lu.homedir(),".claude","skills")}async function Nu(r,e,t,n){let s=Uu(),o=Qe.join(s,e),i=Qe.join(o,"SKILL.md"),a=await wn.readFile(r,"utf-8"),c=OT(a,t,n);return await wn.mkdir(o,{recursive:!0}),await wn.writeFile(i,c,"utf-8"),{name:e,filePath:i,source:t,sha:n}}async function _T(r){let e={installed:[],skipped:[],errors:[]};if(!Qs.isAvailable("git")){let n=Qs.checkTool("git");return e.errors.push(`Cannot install from GitHub: git is not available. ${n.error?.hint||"Install git and try again."}`),e}let t=Qe.join(Lu.tmpdir(),`prjct-skill-${Date.now()}`);try{let n=`https://github.com/${r.owner}/${r.repo}.git`;await kh(`git clone --depth 1 ${n} ${t}`,{timeout:Es("GIT_CLONE")});let s;try{let{stdout:a}=await kh("git rev-parse HEAD",{cwd:t,timeout:Es("TOOL_CHECK")});s=a.trim()}catch{}let o=await bh(t);if(o.length===0)return e.errors.push(`No SKILL.md files found in ${r.owner}/${r.repo}`),e;let i=r.skillName?o.filter(a=>a.name===r.skillName):o;if(r.skillName&&i.length===0)return e.errors.push(`Skill "${r.skillName}" not found in ${r.owner}/${r.repo}`),e;for(let a of i)try{let c=await Nu(a.filePath,a.name,r,s),u={name:a.name,source:{type:"github",url:`${r.owner}/${r.repo}`,sha:s},installedAt:new Date().toISOString(),filePath:c.filePath};await po.addEntry(u),e.installed.push(c)}catch(c){e.errors.push(`Failed to install ${a.name}: ${w(c)}`)}}finally{try{await wn.rm(t,{recursive:!0,force:!0})}catch{}}return e}async function NT(r){let e={installed:[],skipped:[],errors:[]},t=r.localPath;try{await wn.access(t)}catch{return e.errors.push(`Local path not found: ${t}`),e}if((await wn.stat(t)).isFile()){let s=Qe.basename(Qe.dirname(t));try{let o=await Nu(t,s,r),i={name:s,source:{type:"local",url:t},installedAt:new Date().toISOString(),filePath:o.filePath};await po.addEntry(i),e.installed.push(o)}catch(o){e.errors.push(`Failed to install from ${t}: ${w(o)}`)}}else{let s=await bh(t);if(s.length===0)return e.errors.push(`No SKILL.md files found in ${t}`),e;for(let o of s)try{let i=await Nu(o.filePath,o.name,r),a={name:o.name,source:{type:"local",url:t},installedAt:new Date().toISOString(),filePath:i.filePath};await po.addEntry(a),e.installed.push(i)}catch(i){e.errors.push(`Failed to install ${o.name}: ${w(i)}`)}}return e}async function LT(r){let e=Uu(),t=Qe.join(e,r);try{await wn.rm(t,{recursive:!0,force:!0})}catch{}let n=Qe.join(e,`${r}.md`);try{await wn.rm(n,{force:!0})}catch{}return po.removeEntry(r)}async function UT(r){let e=Sh(r);switch(e.type){case"github":return _T(e);case"local":return NT(e);default:return{installed:[],skipped:[],errors:[`Unsupported source type: ${e.type}`]}}}var kh,Ph,Ch=y(()=>{"use strict";M();Kt();Ki();yh();kh=FT(MT);l(Sh,"parseSource");l(bh,"discoverSkills");l(OT,"injectSourceMetadata");l(Uu,"getInstallDir");l(Nu,"installSkillFile");l(_T,"installFromGitHub");l(NT,"installFromLocal");l(LT,"remove");l(UT,"install");Ph={install:UT,remove:LT,parseSource:Sh,getInstallDir:Uu}});import jt from"node:fs/promises";import HT from"node:os";import St from"node:path";async function vh(r,e,t,n){let s=[],o=St.join(r,"agents");try{let c=await jt.readdir(o);for(let u of c)u.endsWith(".md")&&await jt.unlink(St.join(o,u))}catch(c){F.debug("Failed to purge old agents",{path:o,error:Y(c)})}let i=["prjct-workflow","prjct-planner","prjct-shipper"];await Promise.all(i.map(c=>GT(c,o)));for(let c of i)s.push({name:c,type:"workflow"});let a=[];e.hasFrontend&&(a.push({name:"frontend",skill:"javascript-typescript"}),a.push({name:"uxui",skill:"frontend-design"})),e.hasBackend&&a.push({name:"backend",skill:"javascript-typescript"}),e.hasDatabase&&a.push({name:"database"}),e.hasTesting&&a.push({name:"testing",skill:"developer-kit"}),e.hasDocker&&a.push({name:"devops",skill:"developer-kit"}),await Promise.all(a.map(c=>zT(c.name,o,t,e,n)));for(let c of a)s.push({name:c.name,type:"domain",skill:c.skill});return s}async function xh(r){let e=St.join(r,"agents"),t=[];try{let n=await jt.readdir(e),s=new Set(["prjct-workflow","prjct-planner","prjct-shipper"]);for(let o of n){if(!o.endsWith(".md"))continue;let i=o.replace(".md",""),a=s.has(i)?"workflow":"domain";t.push({name:i,type:a})}}catch{return[]}return t}async function Th(r){let e=/\{\{>\s*([\w-]+)\s*\}\}/g,t=[...r.matchAll(e)];if(t.length===0)return r;let n=r;for(let s of t){let o=s[1],i=Se(`subagents/${o}.md`);if(!i){let a=St.join(__dirname,"..","..","templates","subagents",`${o}.md`);try{i=await jt.readFile(a,"utf-8")}catch{n=n.replace(s[0],`<!-- partial "${o}" not found -->`);continue}}n=n.replace(s[0],i.trim())}return n}async function GT(r,e){let t="";try{let n=St.join(__dirname,"..","..","templates","subagents","workflow",`${r}.md`);t=await jt.readFile(n,"utf-8"),t=await Th(t)}catch(n){F.debug("Workflow agent template not found, generating minimal",{name:r,error:Y(n)}),t=WT(r)}await jt.writeFile(St.join(e,`${r}.md`),t,"utf-8")}async function zT(r,e,t,n,s){let o="";try{let i=St.join(__dirname,"..","..","templates","subagents","domain",`${r}.md`);o=await jt.readFile(i,"utf-8"),o=await Th(o),o=o.replace("{projectName}",t.name),o=o.replace("{frameworks}",n.frameworks.join(", ")||"None detected"),o=o.replace("{ecosystem}",t.ecosystem)}catch(i){F.debug("Domain agent template not found, generating minimal",{name:r,error:Y(i)}),o=BT(r,t,n)}o=JT(o,r,s),await jt.writeFile(St.join(e,`${r}.md`),o,"utf-8")}function JT(r,e,t){if(!t)return r;let{patternsDiscovered:n,knownGotchas:s,agentAccuracy:o}=t,i=o.filter(u=>u.agent===`${e}.md`||u.agent===e);if(!(n.length>0||s.length>0||i.length>0))return r;let c=[`
1405
- ## Recent Learnings (from completed tasks)
1406
- `];if(n.length>0){c.push("### Discovered Patterns");for(let u of n)c.push(`- ${u}`);c.push("")}if(s.length>0){c.push("### Known Gotchas");for(let u of s)c.push(`- ${u}`);c.push("")}if(i.length>0){c.push("### Agent Accuracy Notes");for(let u of i){let p=u.note?` \u2014 ${u.note}`:"";c.push(`- ${u.rating}${p}`)}c.push("")}return r+c.join(`
1407
- `)}function WT(r){return`---
1408
- name: ${r}
1409
- description: ${{"prjct-workflow":"Task lifecycle: now, done, pause, resume","prjct-planner":"Planning: task, prd, spec, bug","prjct-shipper":"Shipping: ship, merge, review"}[r]||"Workflow agent"}
1410
- tools: Read, Write, Glob
1411
- ---
1412
-
1413
- # ${r.toUpperCase()}
1414
-
1415
- Workflow agent for prjct operations.
1416
-
1417
- ## Project Context
1418
-
1419
- When invoked:
1420
- 1. Read \`.prjct/prjct.config.json\` \u2192 extract \`projectId\`
1421
- 2. Read \`~/.prjct-cli/projects/{projectId}/storage/state.json\`
1422
- 3. Execute requested operation
1423
- `}function BT(r,e,t){return`---
1424
- name: ${r}
1425
- description: ${r.charAt(0).toUpperCase()+r.slice(1)} specialist for ${e.name}
1426
- tools: Read, Write, Glob, Grep
1427
- skills: []
1428
- ---
1429
-
1430
- # ${r.toUpperCase()} AGENT
1431
-
1432
- Domain specialist for ${r} tasks.
1433
-
1434
- ## Project Context
1435
-
1436
- - **Project**: ${e.name}
1437
- - **Ecosystem**: ${e.ecosystem}
1438
- - **Frameworks**: ${t.frameworks.join(", ")||"None detected"}
1439
-
1440
- ## Your Role
1441
-
1442
- You are the ${r} expert for this project. Apply best practices for the detected stack.
1443
- `}function Eh(r,e,t){let n=[];for(let o of r)o.skill&&n.push({agent:o.name,skill:o.skill});let s={projectId:e,syncedAt:b(),skills:n.map(o=>({name:o.skill,linkedAgents:[o.agent]})),agentSkillMap:Object.fromEntries(n.map(o=>[o.agent,o.skill]))};return jt.writeFile(St.join(t,"config","skills.json"),JSON.stringify(s,null,2),"utf-8").catch(o=>{F.debug("Failed to write skills.json",{error:Y(o)})}),n}async function jh(r){let e=[];try{let t=St.join(__dirname,"..","..","templates","config","skill-mappings.json"),n=await jt.readFile(t,"utf-8"),o=JSON.parse(n).agentToSkillMap||{},i=[];for(let c of r){let u=o[c.name];if(u?.packages)for(let p of u.packages)i.push({pkg:p,agent:c.name})}if(i.length===0)return e;let a=St.join(HT.homedir(),".claude","skills");for(let{pkg:c,agent:u}of i){let p=c.split("/").pop()||c,m=St.join(a,p,"SKILL.md"),d=St.join(a,`${p}.md`),g=!1;try{await jt.access(m),g=!0}catch{try{await jt.access(d),g=!0}catch{}}if(g){e.push({name:p,agent:u,status:"skipped"});continue}try{let f=c.split("/"),S;f.length===3?S=`${f[0]}/${f[1]}@${f[2]}`:S=c;let E=await Ph.install(S);E.installed.length>0?(e.push({name:p,agent:u,status:"installed"}),F.info(`Installed skill: ${p} for agent: ${u}`)):E.errors.length>0?(e.push({name:p,agent:u,status:"error"}),F.debug(`Failed to install skill ${p}`,{errors:E.errors})):e.push({name:p,agent:u,status:"skipped"})}catch(f){e.push({name:p,agent:u,status:"error"}),F.debug(`Skill install error for ${p}`,{error:Y(f)})}}}catch(t){F.debug("Skill auto-installation failed (non-critical)",{error:Y(t)})}return e}var Ah=y(()=>{"use strict";Yn();an();ne();Gn();Ch();l(vh,"generateAgents");l(xh,"loadExistingAgents");l(Th,"resolveTemplateIncludes");l(GT,"generateWorkflowAgent");l(zT,"generateDomainAgent");l(JT,"injectFeedbackSection");l(WT,"generateMinimalWorkflowAgent");l(BT,"generateMinimalDomainAgent");l(Eh,"configureSkills");l(jh,"autoInstallSkills")});import Ih from"node:fs/promises";import Dh from"node:path";var ca,Rh=y(()=>{"use strict";ca=class{static{l(this,"StackDetector")}projectPath;constructor(e){this.projectPath=e}async detect(){let e={hasFrontend:!1,hasBackend:!1,hasDatabase:!1,hasDocker:!1,hasTesting:!1,frontendType:null,frameworks:[]},t=await this.readPackageJson();if(t){let n={...t.dependencies,...t.devDependencies};this.detectFrontend(n,e),this.detectBackend(n,e),this.detectDatabase(n,e),this.detectTesting(n,t,e),this.collectFrameworks(n,e)}return e.hasDocker=await this.detectDocker(),e}detectFrontend(e,t){(e.react||e.vue||e.svelte||e["@angular/core"])&&(t.hasFrontend=!0,t.frontendType="web"),(e["react-native"]||e.expo)&&(t.hasFrontend=!0,t.frontendType=t.frontendType==="web"?"both":"mobile")}detectBackend(e,t){["express","fastify","hono","koa","@nestjs/core","nest","@hapi/hapi","restify","polka"].some(s=>e[s])&&(t.hasBackend=!0)}detectDatabase(e,t){["prisma","@prisma/client","mongoose","pg","mysql2","sequelize","typeorm","drizzle-orm","knex","better-sqlite3","mongodb","redis","ioredis"].some(s=>e[s])&&(t.hasDatabase=!0)}detectTesting(e,t,n){["jest","vitest","mocha","@testing-library/react","@testing-library/vue","cypress","playwright","@playwright/test","ava","tap","bun-types"].some(o=>e[o]||t.devDependencies?.[o])&&(n.hasTesting=!0)}async detectDocker(){let e=["Dockerfile","docker-compose.yml","docker-compose.yaml",".dockerignore"];for(let t of e)if(await this.fileExists(t))return!0;return!1}collectFrameworks(e,t){e.react&&t.frameworks.push("React"),e.next&&t.frameworks.push("Next.js"),e.vue&&t.frameworks.push("Vue"),e.nuxt&&t.frameworks.push("Nuxt"),e.svelte&&t.frameworks.push("Svelte"),e["@angular/core"]&&t.frameworks.push("Angular"),e["react-native"]&&t.frameworks.push("React Native"),e.expo&&t.frameworks.push("Expo"),e.express&&t.frameworks.push("Express"),e.fastify&&t.frameworks.push("Fastify"),e.hono&&t.frameworks.push("Hono"),e.koa&&t.frameworks.push("Koa"),(e["@nestjs/core"]||e.nest)&&t.frameworks.push("NestJS"),e.astro&&t.frameworks.push("Astro"),e.remix&&t.frameworks.push("Remix"),e.gatsby&&t.frameworks.push("Gatsby")}async readPackageJson(){try{let e=Dh.join(this.projectPath,"package.json"),t=await Ih.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async fileExists(e){try{return await Ih.access(Dh.join(this.projectPath,e)),!0}catch{return!1}}}});import{exec as VT}from"node:child_process";import $h from"node:fs/promises";import Hu from"node:path";import{promisify as qT}from"node:util";async function Mh(r){let e={branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0};try{let{stdout:t}=await ms("git branch --show-current",{cwd:r});e.branch=t.trim()||"main";let{stdout:n}=await ms("git rev-list --count HEAD",{cwd:r});e.commits=parseInt(n.trim(),10)||0;let{stdout:s}=await ms("git shortlog -sn --all | wc -l",{cwd:r});e.contributors=parseInt(s.trim(),10)||0;let{stdout:o}=await ms("git status --porcelain",{cwd:r}),i=o.trim().split(`
1444
- `).filter(Boolean);e.hasChanges=i.length>0;for(let u of i){let p=u.substring(0,2),m=u.substring(3);p.startsWith("A")||p.startsWith("M ")?e.stagedFiles.push(m):p.includes("M")?e.modifiedFiles.push(m):p.startsWith("??")&&e.untrackedFiles.push(m)}let{stdout:a}=await ms('git log --oneline -20 --pretty=format:"%h|%s|%ad" --date=short',{cwd:r});e.recentCommits=a.split(`
1445
- `).filter(Boolean).map(u=>{let[p,m,d]=u.split("|");return{hash:p,message:m,date:d}});let{stdout:c}=await ms('git log --oneline --since="1 week ago" | wc -l',{cwd:r});e.weeklyCommits=parseInt(c.trim(),10)||0}catch(t){F.debug("Git analysis failed (not a git repo?)",{error:Y(t)})}return e}async function on(r,e){try{return await $h.access(Hu.join(r,e)),!0}catch(t){return F.debug("File not found",{filename:e,error:Y(t)}),!1}}async function Fh(r){let e={fileCount:0,version:"0.0.0",name:Hu.basename(r),ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]};try{let{stdout:t}=await ms('find . -type f \\( -name "*.js" -o -name "*.ts" -o -name "*.tsx" -o -name "*.py" -o -name "*.go" -o -name "*.rs" \\) -not -path "./node_modules/*" -not -path "./.git/*" | wc -l',{cwd:r});e.fileCount=parseInt(t.trim(),10)||0}catch(t){F.debug("File count failed",{path:r,error:Y(t)}),e.fileCount=0}try{let t=Hu.join(r,"package.json"),n=JSON.parse(await $h.readFile(t,"utf-8"));e.version=n.version||"0.0.0",e.name=n.name||e.name,e.ecosystem="JavaScript";let s={...n.dependencies,...n.devDependencies};(s.react||s["react-dom"])&&e.frameworks.push("React"),s.next&&e.frameworks.push("Next.js"),s.vue&&e.frameworks.push("Vue"),s.express&&e.frameworks.push("Express"),s.hono&&e.frameworks.push("Hono"),s["@angular/core"]&&e.frameworks.push("Angular"),s.svelte&&e.frameworks.push("Svelte"),n.devDependencies?.typescript||await on(r,"tsconfig.json")?e.languages.push("TypeScript"):e.languages.push("JavaScript")}catch(t){F.debug("No package.json found",{path:r,error:Y(t)})}return await on(r,"Cargo.toml")&&(e.ecosystem="Rust",e.languages.push("Rust")),await on(r,"go.mod")&&(e.ecosystem="Go",e.languages.push("Go")),(await on(r,"requirements.txt")||await on(r,"pyproject.toml"))&&(e.ecosystem="Python",e.languages.push("Python")),e.fileCount>300||e.frameworks.length>=3?e.projectType="enterprise":(e.fileCount>50||e.frameworks.length>=2)&&(e.projectType="complex"),e}async function Oh(r){let e={install:"npm install",run:"npm run",test:"npm test",build:"npm run build",dev:"npm run dev",lint:"npm run lint",format:"npm run format"};return await on(r,"bun.lockb")?(e.install="bun install",e.run="bun run",e.test="bun test",e.build="bun run build",e.dev="bun run dev",e.lint="bun run lint",e.format="bun run format"):await on(r,"pnpm-lock.yaml")?(e.install="pnpm install",e.run="pnpm run",e.test="pnpm test",e.build="pnpm run build",e.dev="pnpm run dev",e.lint="pnpm run lint",e.format="pnpm run format"):await on(r,"yarn.lock")&&(e.install="yarn",e.run="yarn",e.test="yarn test",e.build="yarn build",e.dev="yarn dev",e.lint="yarn lint",e.format="yarn format"),await on(r,"Cargo.toml")&&(e.install="cargo build",e.run="cargo run",e.test="cargo test",e.build="cargo build --release",e.dev="cargo run",e.lint="cargo clippy",e.format="cargo fmt"),await on(r,"go.mod")&&(e.install="go mod download",e.run="go run .",e.test="go test ./...",e.build="go build",e.dev="go run .",e.lint="golangci-lint run",e.format="go fmt ./..."),e}function _h(r,e){let t=yn(),s={JavaScript:"package.json",Rust:"Cargo.toml",Go:"go.mod",Python:"pyproject.toml"}[r.ecosystem]||"filesystem",o=l(a=>({file:a,type:"detected"}),"detected"),i=l(a=>({file:a,type:"inferred"}),"inferred");return t.ecosystem=o(s),t.name=o(s),t.version=o(s),t.languages=o(s),t.frameworks=o(s),e.install.startsWith("bun")?t.commands=o("bun.lockb"):e.install.startsWith("pnpm")?t.commands=o("pnpm-lock.yaml"):e.install==="yarn"?t.commands=o("yarn.lock"):e.install.startsWith("cargo")?t.commands=o("Cargo.toml"):e.install.startsWith("go")?t.commands=o("go.mod"):t.commands=o("package.json"),t.projectType=i("file count + frameworks"),t.git=o("git"),t}async function Nh(r){return new ca(r).detect()}var ms,Lh=y(()=>{"use strict";an();ra();Gn();Rh();ms=qT(VT);l(Mh,"analyzeGit");l(on,"fileExists");l(Fh,"gatherStats");l(Oh,"detectCommands");l(_h,"buildSources");l(Nh,"detectStack")});import{exec as KT}from"node:child_process";import la from"node:fs/promises";import ua from"node:path";import{promisify as XT}from"node:util";var YT,Gu,zu,Uh,Hh=y(()=>{"use strict";M();YT=XT(KT),Gu={async contextFilesExist(r){let e=Date.now(),t=["context/CLAUDE.md"],n=[];for(let s of t){let o=ua.join(r,s);try{await la.access(o)}catch{n.push(s)}}return{name:"Context files exist",passed:n.length===0,output:n.length===0?`${t.length} files verified`:void 0,error:n.length>0?`Missing: ${n.join(", ")}`:void 0,durationMs:Date.now()-e}},async jsonFilesValid(r){let e=Date.now(),t=["storage/state.json"],n=[];for(let s of t){let o=ua.join(r,s);try{let i=await la.readFile(o,"utf-8");JSON.parse(i)}catch(i){k(i)||n.push(`${s}: ${i instanceof SyntaxError?"invalid JSON":"read error"}`)}}return{name:"JSON files valid",passed:n.length===0,output:n.length===0?`${t.length} files validated`:void 0,error:n.length>0?n.join("; "):void 0,durationMs:Date.now()-e}},async noSensitiveData(r){let e=Date.now(),t=ua.join(r,"context"),n=[/(?:api[_-]?key|apikey)\s*[:=]\s*['"][^'"]{10,}/i,/(?:password|passwd|pwd)\s*[:=]\s*['"][^'"]{4,}/i,/(?:secret|token)\s*[:=]\s*['"][^'"]{10,}/i],s=[];try{let o=await la.readdir(t);for(let i of o){if(!i.endsWith(".md"))continue;let a=await la.readFile(ua.join(t,i),"utf-8");for(let c of n)if(c.test(a)){s.push(`${i}: potential sensitive data detected`);break}}}catch(o){if(!k(o))return{name:"No sensitive data",passed:!1,error:`Could not scan: ${w(o)}`,durationMs:Date.now()-e}}return{name:"No sensitive data",passed:s.length===0,output:s.length===0?"No sensitive patterns found":void 0,error:s.length>0?s.join("; "):void 0,durationMs:Date.now()-e}}},zu=class{static{l(this,"SyncVerifier")}async verify(e,t,n){let s=Date.now(),o=[],i=n?.failFast??!1,a=0,c=[Gu.contextFilesExist(t),Gu.jsonFilesValid(t),Gu.noSensitiveData(t)];for(let d of c){let g=await d;if(o.push(g),!g.passed&&i){a=n?.checks?.filter(f=>f.enabled!==!1).length??0;break}}if((!i||o.every(d=>d.passed))&&n?.checks)for(let d of n.checks){if(d.enabled===!1){a++;continue}let g=await this.runCustomCheck(d,e);if(o.push(g),!g.passed&&i){let f=n.checks.slice(n.checks.indexOf(d)+1);a+=f.filter(S=>S.enabled!==!1).length;break}}let p=o.filter(d=>!d.passed).length,m=o.filter(d=>d.passed).length;return{passed:p===0,checks:o,totalMs:Date.now()-s,failedCount:p,passedCount:m,skippedCount:a}}async runCustomCheck(e,t){let n=Date.now(),s=e.command||(e.script?`sh ${e.script}`:null);if(!s)return{name:e.name,passed:!1,error:"No command or script specified",durationMs:Date.now()-n};try{let{stdout:o,stderr:i}=await YT(s,{cwd:t,timeout:3e4});return{name:e.name,passed:!0,output:(o.trim()||i.trim()).slice(0,200)||void 0,durationMs:Date.now()-n}}catch(o){let i=o;return{name:e.name,passed:!1,error:(i.stderr?.trim()||i.message).slice(0,200),durationMs:Date.now()-n}}}},Uh=new zu});import kn from"node:fs/promises";import gs from"node:path";var pa,cs,Ju=y(()=>{"use strict";Vs();Bf();Zf();nh();ih();Pu();an();En();Ye();ee();ki();Rn();ul();Ir();gl();hl();wl();Cl();dh();ne();Gn();Nl();Ll();mh();fh();du();Ah();Lh();Hh();pa=class{static{l(this,"SyncService")}projectPath;projectId=null;globalPath="";cliVersion="0.0.0";constructor(){this.projectPath=process.cwd()}async sync(e=process.cwd(),t={}){this.projectPath=e;let n=Date.now(),s;if(!t.aiTools||t.aiTools.length===0){let o=(await ia(e)).filter(i=>!lo.includes(i));s=[...lo,...o]}else t.aiTools[0]==="auto"?(s=await ia(e),s.length===0&&(s=["claude"])):t.aiTools[0]==="all"?s=await lh("all",e):s=t.aiTools;try{if(this.projectId=await I.getProjectId(e),!this.projectId)return{success:!1,projectId:"",cliVersion:"",git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),agents:[],skills:[],skillsInstalled:[],contextFiles:[],aiTools:[],error:"No prjct project. Run p. init first."};this.globalPath=P.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await this.ensureDirectories(),await ml(this.projectId);let[i,a,c,u]=await Promise.all([Mh(this.projectPath),Fh(this.projectPath),Oh(this.projectPath),Nh(this.projectPath)]),p=t.full===!0,m,d=!0,g=!0,f=new Set;if(!p&&th(this.projectId))try{let{diff:B,currentHashes:Uy}=await xu(this.projectPath,this.projectId),xp=B.added.length+B.modified.length+B.deleted.length;if(xp===0&&!t.changedFiles?.length)d=!1,g=!1,m={isIncremental:!0,filesChanged:0,filesUnchanged:B.unchanged.length,indexesRebuilt:!1,agentsRegenerated:!1,affectedDomains:[]};else{let Ia=Yf(B,this.projectId);f=Qf(Ia.allAffected);let Hy=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);d=Ia.allAffected.some(Ln=>{let Gy=Ln.substring(Ln.lastIndexOf("."));return Hy.has(Gy)}),g=Ia.directlyChanged.some(Ln=>Ln==="package.json"||Ln==="tsconfig.json"||Ln.includes("Dockerfile")||Ln.includes("docker-compose")),m={isIncremental:!0,filesChanged:xp,filesUnchanged:B.unchanged.length,indexesRebuilt:d,agentsRegenerated:g,affectedDomains:Array.from(f)}}vu(this.projectId,Uy)}catch(B){F.debug("Incremental detection failed, falling back to full sync",{error:Y(B)})}else try{let{currentHashes:B}=await xu(this.projectPath,this.projectId);vu(this.projectId,B)}catch(B){F.debug("Hash computation failed (non-critical)",{error:Y(B)})}if(d)try{await Promise.all([Wf(this.projectPath,this.projectId),Xf(this.projectPath,this.projectId),oh(this.projectPath,this.projectId)])}catch(B){F.debug("File ranking index build failed (non-critical)",{error:Y(B)})}let S;if(g)try{let B=await le.getAggregatedFeedback(this.projectId);(B.patternsDiscovered.length>0||B.knownGotchas.length>0||B.agentAccuracy.length>0)&&(S=B)}catch{}let E=g?await vh(this.globalPath,u,a,S):await xh(this.globalPath),x=Eh(E,this.projectId,this.globalPath),$=g?await jh(E):[],z=_h(a,c),_e=await this.generateContextFiles(i,a,c,E,z),nt={projectId:this.projectId,name:a.name,version:a.version,ecosystem:a.ecosystem,projectType:a.projectType,languages:a.languages,frameworks:a.frameworks,repoPath:this.projectPath,branch:i.branch,fileCount:a.fileCount,commits:i.commits,hasChanges:i.hasChanges,commands:c,agents:{workflow:E.filter(B=>B.type==="workflow").map(B=>B.name),domain:E.filter(B=>B.type==="domain").map(B=>B.name)},sources:z},Dt=await uh(nt,this.globalPath,this.projectPath,s);await Promise.all([this.updateProjectJson(i,a),this.updateStateJson(a,u),this.logToMemory(i,a),this.saveDraftAnalysis(i,a,u)]);let v=Date.now()-n,D=await this.recordSyncMetrics(a,_e,E,v);await this.archiveStaleData(),await this.autoLearnFromHistory(),await be.installGlobalConfig(),await be.syncCommands();let Re;try{let B=await I.readConfig(this.projectPath);Re=await Uh.verify(this.projectPath,this.globalPath,B?.verification)}catch(B){F.debug("Verification failed (non-critical)",{error:Y(B)})}return{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:i,stats:a,commands:c,stack:u,agents:E,skills:x,skillsInstalled:$,contextFiles:_e,aiTools:Dt.map(B=>({toolId:B.toolId,outputFile:B.outputFile,success:B.success})),syncMetrics:D,verification:Re,incremental:m}}catch(o){return{success:!1,projectId:this.projectId||"",cliVersion:this.cliVersion,git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),agents:[],skills:[],skillsInstalled:[],contextFiles:[],aiTools:[],error:Y(o)}}}async ensureDirectories(){let e=["storage","context","agents","memory","analysis","config","sync"];await Promise.all(e.map(t=>kn.mkdir(gs.join(this.globalPath,t),{recursive:!0})))}async generateContextFiles(e,t,n,s,o){return new aa({projectId:this.projectId,projectPath:this.projectPath,globalPath:this.globalPath}).generate(e,t,n,s,o)}async updateProjectJson(e,t){let n=gs.join(this.globalPath,"project.json"),s={};try{s=JSON.parse(await kn.readFile(n,"utf-8"))}catch(i){F.debug("No existing project.json",{path:n,error:Y(i)})}let o={...s,projectId:this.projectId,repoPath:this.projectPath,name:t.name,version:t.version,cliVersion:this.cliVersion,techStack:t.frameworks,fileCount:t.fileCount,commitCount:e.commits,stack:t.ecosystem,currentBranch:e.branch,hasUncommittedChanges:e.hasChanges,createdAt:s.createdAt||b(),lastSync:b(),lastSyncCommit:e.recentCommits[0]?.hash||null,lastSyncBranch:e.branch};await kn.writeFile(n,JSON.stringify(o,null,2),"utf-8")}async updateStateJson(e,t){let n=gs.join(this.globalPath,"storage","state.json"),s={};try{s=JSON.parse(await kn.readFile(n,"utf-8"))}catch(o){F.debug("No existing state.json",{path:n,error:Y(o)})}s.projectId=this.projectId,s.stack={language:e.languages[0]||"Unknown",framework:e.frameworks[0]||null},s.domains={hasFrontend:t.hasFrontend,hasBackend:t.hasBackend,hasDatabase:t.hasDatabase,hasTesting:t.hasTesting,hasDocker:t.hasDocker},s.projectType=e.projectType,s.metrics={totalFiles:e.fileCount},s.lastSync=b(),s.lastUpdated=b(),s.context={...s.context||{},lastSession:b(),lastAction:"Synced project",nextAction:'Run `p. task "description"` to start working'},await kn.writeFile(n,JSON.stringify(s,null,2),"utf-8");try{await gh.generate(this.projectPath,s)}catch(o){F.debug("Local state generation failed (optional)",{error:Y(o)})}}async logToMemory(e,t){let n=gs.join(this.globalPath,"memory","events.jsonl"),s={ts:b(),action:"sync",branch:e.branch,uncommitted:e.hasChanges,fileCount:t.fileCount,commitCount:e.commits};await kn.appendFile(n,`${JSON.stringify(s)}
1446
- `,"utf-8")}async recordSyncMetrics(e,t,n,s){let i=0;for(let m of t)try{let d=gs.join(this.globalPath,m),g=await kn.readFile(d,"utf-8");i+=g.length}catch(d){F.debug("Context file not found for metrics",{file:m,error:Y(d)})}for(let m of n)try{let d=gs.join(this.globalPath,"agents",`${m.name}.md`),g=await kn.readFile(d,"utf-8");i+=g.length}catch(d){F.debug("Agent file not found for metrics",{agent:m.name,error:Y(d)})}let a=Math.floor(i/4),u=e.fileCount*500,p=u>0?Math.max(0,(u-a)/u):0;try{await pn.recordSync(this.projectId,{originalSize:u,filteredSize:a,duration:s,isWatch:!1,agents:n.filter(m=>m.type==="domain").map(m=>m.name)})}catch(m){F.debug("Failed to record sync metrics",{error:Y(m)})}return{duration:s,originalSize:u,filteredSize:a,compressionRate:p}}async saveDraftAnalysis(e,t,n){try{let s=e.recentCommits[0]?.hash||null,o=[],i=[];try{let a=await le.getAggregatedFeedback(this.projectId);a.patternsDiscovered.length>0&&(o=a.patternsDiscovered.map(c=>({name:c,description:`Discovered during task execution: ${c}`}))),a.knownGotchas.length>0&&(i=a.knownGotchas.map(c=>({issue:c,file:"multiple",suggestion:`Recurring issue reported across tasks: ${c}`})))}catch{}await nn.saveDraft(this.projectId,{projectId:this.projectId,languages:t.languages,frameworks:t.frameworks,configFiles:[],fileCount:t.fileCount,patterns:o,antiPatterns:i,analyzedAt:b(),status:"draft",commitHash:s??void 0})}catch(s){F.debug("Failed to save draft analysis (non-critical)",{error:Y(s)})}}async archiveStaleData(){if(this.projectId)try{let[e,t,n,s,o]=await Promise.all([es.archiveOldShipped(this.projectId).catch(()=>0),dn.markDormantIdeas(this.projectId).catch(()=>0),ot.removeStaleCompleted(this.projectId).catch(()=>0),le.archiveStalePausedTasks(this.projectId).catch(()=>[]),at.capEntries(this.projectId).catch(()=>0)]),i=e+t+n+s.length+o;if(i>0){F.info("Archived stale data",{shipped:e,dormant:t,staleQueue:n,stalePaused:s.length,memoryCapped:o,total:i});let a=yt.getStats(this.projectId);F.debug("Archive stats",a)}}catch(e){F.debug("Archival failed (non-critical)",{error:Y(e)})}}async autoLearnFromHistory(){if(this.projectId)try{let e=await le.getTaskHistory(this.projectId);if(e.length===0)return;let t=new Zn,n=await _l.learnFromTaskHistory(this.projectId,e,t);try{let s=await Rg.getFeatureOutcomes(this.projectId);s.length>0&&await _l.learnFromOutcomes(this.projectId,s,t)}catch{}n.memoriesInjected>0&&F.info("Auto-learned from task history",{patternsExtracted:n.patternsExtracted,memoriesInjected:n.memoriesInjected,patternsSkipped:n.patternsSkipped})}catch(e){F.debug("Auto-learning failed (non-critical)",{error:Y(e)})}}async getCliVersion(){try{let e=gs.join(__dirname,"..","..","package.json");return JSON.parse(await kn.readFile(e,"utf-8")).version||"0.0.0"}catch(e){return F.debug("Failed to read CLI version",{error:Y(e)}),"0.0.0"}}emptyGitData(){return{branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0}}emptyStats(){return{fileCount:0,version:"0.0.0",name:"unknown",ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]}}emptyCommands(){return{install:"npm install",run:"npm run",test:"npm test",build:"npm run build",dev:"npm run dev",lint:"npm run lint",format:"npm run format"}}emptyStack(){return{hasFrontend:!1,hasBackend:!1,hasDatabase:!1,hasDocker:!1,hasTesting:!1,frontendType:null,frameworks:[]}}},cs=new pa});var Fn=y(()=>{"use strict";lf();ff();hf();wf();Sf();lu();Pf();du();mu();Cf();Hf();Gf();Ju()});var ve,tt=y(()=>{"use strict";Zl();Fc();Xl();Ye();ee();cf();Fn();ne();me();Ar();Xt();ve=class{static{l(this,"PrjctCommandsBase")}prjctDir;updateChecker;updateNotificationShown;commandExecutor;constructor(){this.prjctDir=".prjct",this.updateChecker=new af,this.updateNotificationShown=!1,this.commandExecutor=Oi}get agent(){return Ys.getAgent()}get agentInfo(){return Ys.getInfo()}get currentAuthor(){return On.getCurrentAuthor()}async initializeAgent(){return Ys.initialize()}async ensureProjectInit(e){return On.ensureInit(e)}async ensureAuthor(){return On.ensureAuthor()}async getGlobalProjectPath(e){return On.getGlobalPath(e)}async logToMemory(e,t,n){let s=await this.ensureAuthor();return at.log(e,t,n,s.name)}async _detectEmptyDirectory(e){return On.isEmptyDirectory(e)}async _detectExistingCode(e){return On.hasExistingCode(e)}_breakdownFeatureTasks(e){return zi.breakdownFeature(e)}_detectBugSeverity(e){return zi.detectBugSeverity(e)}async _assignAgentForTask(e,t,n){return Ys.assignForTask(e,t,n)}}});var Wh={};Ne(Wh,{UninstallCommands:()=>go,uninstall:()=>Jh});import{execSync as da}from"node:child_process";import lt from"node:fs/promises";import QT from"node:os";import Sn from"node:path";import ZT from"node:readline";import we from"chalk";async function Wu(r){let e=0;try{let t=await lt.readdir(r,{withFileTypes:!0});for(let n of t){let s=Sn.join(r,n.name);if(n.isDirectory())e+=await Wu(s);else try{let o=await lt.stat(s);e+=o.size}catch{}}}catch{}return e}function Gh(r){if(r===0)return"0 B";let e=["B","KB","MB","GB"],t=Math.floor(Math.log(r)/Math.log(1024));return`${(r/1024**t).toFixed(1)} ${e[t]}`}async function eE(r){try{return(await lt.readdir(r,{withFileTypes:!0})).filter(t=>t.isDirectory()).length}catch{return 0}}function tE(){let r={homebrew:!1,npm:!1};try{da("brew list prjct-cli 2>/dev/null",{encoding:"utf-8"})&&(r.homebrew=!0,r.homebrewFormula="prjct-cli")}catch{}try{da("npm list -g prjct-cli --depth=0 2>/dev/null",{encoding:"utf-8"}).includes("prjct-cli")&&(r.npm=!0)}catch{}return r}async function nE(){let r=[],e=im(),t=P.getGlobalBasePath(),n=await C(t),s=n?await eE(Sn.join(t,"projects")):0,o=n?await Wu(t):0;r.push({path:t,type:"directory",description:`All project data${s>0?`, ${s} project${s>1?"s":""}`:""}`,size:o,count:s,exists:n});let i=Sn.join(e.claude.config,"CLAUDE.md"),a=await C(i),c=!1;if(a)try{let nt=await lt.readFile(i,"utf-8");c=nt.includes(ma)&&nt.includes(mo)}catch{}r.push({path:i,type:"section",description:"prjct section in CLAUDE.md",exists:a&&c});let u=e.claude.commands,p=await C(u),m=p?await Wu(u):0;r.push({path:u,type:"directory",description:"Claude commands",size:m,exists:p});let d=e.claude.router,g=await C(d);r.push({path:d,type:"file",description:"Claude router",exists:g});let f=Sn.join(e.claude.config,"prjct-statusline.sh"),S=await C(f);r.push({path:f,type:"file",description:"Status line script",exists:S});let E=e.gemini.router,x=await C(E);r.push({path:E,type:"file",description:"Gemini router",exists:x});let $=Sn.join(e.gemini.config,"GEMINI.md"),z=await C($),_e=!1;if(z)try{let nt=await lt.readFile($,"utf-8");_e=nt.includes(ma)&&nt.includes(mo)}catch{}return z&&_e&&r.push({path:$,type:"section",description:"prjct section in GEMINI.md",exists:!0}),r}async function sE(r){try{let e=await lt.readFile(r,"utf-8");if(!e.includes(ma)||!e.includes(mo))return!1;let t=e.indexOf(ma),n=e.indexOf(mo)+mo.length,s=e.substring(0,t)+e.substring(n);return s=s.replace(/\n{3,}/g,`
1447
-
1448
- `).trim(),!s||s.trim().length===0?await lt.unlink(r):await lt.writeFile(r,`${s}
1449
- `,"utf-8"),!0}catch{return!1}}async function rE(){let r=QT.homedir(),e=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19),t=Sn.join(r,`.prjct-backup-${e}`);try{await lt.mkdir(t,{recursive:!0});let n=P.getGlobalBasePath();return await C(n)&&await zh(n,Sn.join(t,".prjct-cli")),t}catch{return null}}async function zh(r,e){await lt.mkdir(e,{recursive:!0});let t=await lt.readdir(r,{withFileTypes:!0});for(let n of t){let s=Sn.join(r,n.name),o=Sn.join(e,n.name);n.isDirectory()?await zh(s,o):await lt.copyFile(s,o)}}async function oE(r,e,t){let n=[],s=[];for(let o of r)if(o.exists)try{o.type==="section"?await sE(o.path)&&n.push(o.path):o.type==="directory"?(await lt.rm(o.path,{recursive:!0,force:!0}),n.push(o.path)):o.type==="file"&&(await lt.unlink(o.path),n.push(o.path))}catch(i){s.push(`${o.path}: ${w(i)}`)}if(!t.keepPackage){if(e.homebrew&&e.homebrewFormula)try{t.dryRun||da(`brew uninstall ${e.homebrewFormula}`,{stdio:"pipe"}),n.push("Homebrew: prjct-cli")}catch(o){s.push(`Homebrew: ${w(o)}`)}if(e.npm)try{t.dryRun||da("npm uninstall -g prjct-cli",{stdio:"pipe"}),n.push("npm: prjct-cli")}catch(o){s.push(`npm: ${w(o)}`)}}return{deleted:n,errors:s}}async function iE(r){let e=ZT.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.toLowerCase()==="uninstall")})})}async function Jh(r={},e=process.cwd()){let t=await nE(),n=tE(),s=t.filter(c=>c.exists);if(s.length===0&&!n.homebrew&&!n.npm)return console.log(we.yellow(`
1450
- No prjct installation found.`)),{success:!0,message:"Nothing to uninstall"};let o=s.reduce((c,u)=>c+(u.size||0),0);console.log(""),console.log(we.red.bold(" WARNING: This action is DANGEROUS and IRREVERSIBLE")),console.log(""),console.log(we.white("The following will be permanently deleted:")),console.log("");for(let c of s){let u=P.getDisplayPath(c.path),p="";c.type==="section"?p=we.dim("(section only)"):c.size&&(p=we.dim(`(${Gh(c.size)})`)),console.log(` ${we.cyan(u.padEnd(35))} ${p}`),console.log(` ${we.dim(c.description)}`),console.log("")}if(n.homebrew&&(console.log(` ${we.cyan("Homebrew".padEnd(35))} ${we.dim("prjct-cli formula")}`),console.log("")),n.npm&&(console.log(` ${we.cyan("npm global".padEnd(35))} ${we.dim("prjct-cli package")}`),console.log("")),o>0&&(console.log(we.dim(` Total size: ${Gh(o)}`)),console.log("")),r.dryRun)return console.log(we.yellow("Dry run - no changes made")),{success:!0,message:"Dry run complete",itemsFound:s.length};if(r.backup){console.log(we.blue("Creating backup..."));let c=await rE();c?(console.log(we.green(`Backup created: ${P.getDisplayPath(c)}`)),console.log("")):console.log(we.yellow("Failed to create backup, continuing..."))}if(!r.force&&(console.log(we.yellow('Type "uninstall" to confirm:')),!await iE("> ")))return console.log(we.yellow(`
1451
- Uninstall cancelled.`)),{success:!1,message:"Uninstall cancelled by user"};console.log(""),console.log(we.blue("Removing prjct..."));let{deleted:i,errors:a}=await oE(t,n,r);if(console.log(""),i.length>0&&console.log(we.green(`Removed ${i.length} items`)),a.length>0){console.log(we.yellow(`
1452
- ${a.length} errors:`));for(let c of a)console.log(we.red(` - ${c}`))}return console.log(""),console.log(we.green("prjct has been uninstalled.")),console.log(we.dim("Thanks for using prjct! We hope to see you again.")),console.log(""),{success:a.length===0,message:`Removed ${i.length} items`,deleted:i,errors:a.length>0?a:void 0}}var ma,mo,go,Bu=y(()=>{"use strict";En();ee();M();me();tt();ma="<!-- prjct:start - DO NOT REMOVE THIS MARKER -->",mo="<!-- prjct:end - DO NOT REMOVE THIS MARKER -->";l(Wu,"getDirectorySize");l(Gh,"formatSize");l(eE,"countDirectoryItems");l(tE,"detectInstallation");l(nE,"gatherUninstallItems");l(sE,"removePrjctSection");l(rE,"createBackup");l(zh,"copyDirectory");l(oE,"performUninstall");l(iE,"promptConfirmation");l(Jh,"uninstall");go=class extends ve{static{l(this,"UninstallCommands")}async uninstall(e={},t=process.cwd()){return Jh(e,t)}}});var Bh={};Ne(Bh,{WatchService:()=>ga,watchService:()=>pE});import aE from"node:path";import qe from"chalk";import cE from"chokidar";var lE,uE,ga,pE,Vh=y(()=>{"use strict";Ye();M();ne();Ju();lE=["package.json","package-lock.json","bun.lockb","pnpm-lock.yaml","yarn.lock","tsconfig.json","tsconfig.*.json",".env",".env.*","Cargo.toml","go.mod","pyproject.toml","requirements.txt","src/**/*.ts","src/**/*.tsx","src/**/*.js","src/**/*.jsx","lib/**/*.ts","core/**/*.ts","app/**/*.ts","app/**/*.tsx","pages/**/*.ts","pages/**/*.tsx"],uE=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/coverage/**","**/*.log","**/*.tmp","**/CLAUDE.md","**/.cursorrules","**/.windsurfrules","**/.prjct/**","**/.prjct-cli/**"],ga=class{static{l(this,"WatchService")}watcher=null;projectPath="";projectId=null;debounceTimer=null;lastSyncTime=0;pendingChanges=new Set;options={debounceMs:2e3,minIntervalMs:3e4,verbose:!1,quiet:!1};isRunning=!1;syncCount=0;sigintHandler=null;sigtermHandler=null;async start(e=process.cwd(),t={}){return this.projectPath=e,this.options={...this.options,...t},this.projectId=await I.getProjectId(e),this.projectId?this.isRunning?{success:!1,error:"Watch mode is already running"}:(this.isRunning=!0,this.options.quiet||this.printStartup(),this.watcher=cE.watch(lE,{cwd:this.projectPath,ignored:uE,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}}),this.watcher.on("add",n=>this.handleChange("add",n)).on("change",n=>this.handleChange("change",n)).on("unlink",n=>this.handleChange("unlink",n)).on("error",n=>this.handleError(n)),this.sigintHandler&&process.off("SIGINT",this.sigintHandler),this.sigtermHandler&&process.off("SIGTERM",this.sigtermHandler),this.sigintHandler=()=>this.stop(),this.sigtermHandler=()=>this.stop(),process.on("SIGINT",this.sigintHandler),process.on("SIGTERM",this.sigtermHandler),{success:!0}):{success:!1,error:'No prjct project. Run "prjct init" first.'}}async stop(){this.options.quiet||(console.log(""),console.log(qe.dim(`
1453
- \u{1F44B} Stopped watching (${this.syncCount} syncs performed)`))),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.watcher&&(await this.watcher.close(),this.watcher=null),this.sigintHandler&&(process.off("SIGINT",this.sigintHandler),this.sigintHandler=null),this.sigtermHandler&&(process.off("SIGTERM",this.sigtermHandler),this.sigtermHandler=null),this.pendingChanges.clear(),this.isRunning=!1,process.exit(0)}handleChange(e,t){if(this.pendingChanges.add(t),this.options.verbose&&!this.options.quiet){let n=e==="add"?"\u2795":e==="unlink"?"\u2796":"\u{1F4DD}";console.log(qe.dim(` ${n} ${t}`))}this.scheduleSyncIfNeeded()}scheduleSyncIfNeeded(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(async()=>{let t=Date.now()-this.lastSyncTime;if(t<this.options.minIntervalMs&&this.lastSyncTime>0){let n=this.options.minIntervalMs-t;this.options.verbose&&!this.options.quiet&&console.log(qe.dim(` \u23F3 Rate limited, waiting ${Math.round(n/1e3)}s...`)),this.debounceTimer=setTimeout(()=>this.performSync(),n);return}await this.performSync()},this.options.debounceMs)}async performSync(){let e=Array.from(this.pendingChanges);if(this.pendingChanges.clear(),e.length===0)return;let t=b().split("T")[1].split(".")[0];if(!this.options.quiet){let n=e.length===1?e[0]:`${e.length} files`;console.log(`
1454
- ${qe.dim(`[${t}]`)} ${qe.cyan("\u27F3")} ${n} changed \u2192 syncing...`)}try{let n=await cs.sync(this.projectPath,{changedFiles:e});if(this.lastSyncTime=Date.now(),this.syncCount++,n.success){if(!this.options.quiet){let s=n.agents.filter(i=>i.type==="domain").map(i=>i.name),o=s.length>0?` [${s.join(", ")}]`:"";console.log(`${qe.dim(`[${t}]`)} ${qe.green("\u2713")} Synced${o}`)}}else console.error(`${qe.dim(`[${t}]`)} ${qe.red("\u2717")} Sync failed: ${n.error}`)}catch(n){console.error(`${qe.dim(`[${t}]`)} ${qe.red("\u2717")} Error: ${w(n)}`)}}handleError(e){console.error(qe.red(`Watch error: ${e.message}`))}printStartup(){console.log(""),console.log(qe.cyan("\u{1F441}\uFE0F Watching for changes...")),console.log(qe.dim(` Project: ${aE.basename(this.projectPath)}`)),console.log(qe.dim(` Debounce: ${this.options.debounceMs}ms`)),console.log(qe.dim(` Min interval: ${this.options.minIntervalMs/1e3}s`)),console.log(""),console.log(qe.dim(" Press Ctrl+C to stop")),console.log("")}},pE=new ga});var fo,tr,Vu=y(()=>{"use strict";fo={core:{title:"Core Workflow",description:"13 essential commands for daily development workflow",order:1},optional:{title:"Optional Commands",description:"Advanced features for specialized workflows",order:2},setup:{title:"Setup",description:"Installation and configuration (not for daily use)",order:3}},tr=[{name:"init",group:"core",description:"Deep project analysis and initialization",usage:{claude:'/p:init "[idea]"',terminal:'prjct init "[idea]"'},params:"[idea]",implemented:!0,hasTemplate:!0,requiresProject:!1,features:["Architect mode for blank projects","Auto tech stack recommendation","Analyzes existing codebases"]},{name:"idea",group:"core",description:"Transform ideas into complete technical architectures",usage:{claude:'/p:idea "build a CRM"',terminal:'prjct idea "build a CRM"'},params:"<description>",implemented:!0,hasTemplate:!0,requiresProject:!0,features:["Simple ideas -> Quick capture","Complex ideas -> Full architecture"]},{name:"task",group:"core",description:"Start task with agentic classification and 7-phase workflow",usage:{claude:'/p:task "<description>"',terminal:'prjct task "<description>"'},params:"<description>",implemented:!0,hasTemplate:!0,requiresProject:!0,features:["Agentic type classification","7-phase workflow","Git branch management","Task breakdown"]},{name:"spec",group:"core",description:"Create detailed specifications for complex features",usage:{claude:'/p:spec "Dark Mode"',terminal:'prjct spec "Dark Mode"'},params:"[feature]",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"pause",group:"core",description:"Pause active task to handle interruption",usage:{claude:'/p:pause ["reason"]',terminal:'prjct pause ["reason"]'},params:"[reason]",implemented:!0,hasTemplate:!0,requiresProject:!0,blockingRules:{check:"Active task exists",message:"No active task to pause"}},{name:"resume",group:"core",description:"Resume paused task or recover abandoned session",usage:{claude:"/p:resume",terminal:"prjct resume"},params:"[task_id]",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"next",group:"core",description:"Show priority queue or roadmap view",usage:{claude:"/p:next",terminal:"prjct next"},params:"[roadmap]",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"done",group:"core",description:"Mark current task as complete",usage:{claude:"/p:done",terminal:"prjct done"},implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"ship",group:"core",description:"Commit, push, and celebrate shipped feature",usage:{claude:'/p:ship "feature"',terminal:'prjct ship "feature"'},params:"<feature>",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"bug",group:"core",description:"Report and track bugs with priority",usage:{claude:'/p:bug "description"',terminal:'prjct bug "description"'},params:"<description>",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"dash",group:"core",description:"Unified dashboard - status, progress, and roadmap",usage:{claude:"/p:dash [view]",terminal:"prjct dash [view]"},params:"[week|month|roadmap|compact]",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"stats",group:"core",description:"Value dashboard - token savings, performance, and impact",usage:{claude:"/p:stats",terminal:"prjct stats"},params:"[--json] [--export]",implemented:!0,hasTemplate:!0,requiresProject:!0,features:["Token savings tracking","Compression metrics","Cost estimates","30-day trends"]},{name:"sync",group:"core",description:"Sync project state and update workflow agents",usage:{claude:"/p:sync",terminal:"prjct sync [--package=<name>] [--full]"},implemented:!0,hasTemplate:!0,requiresProject:!0,features:["Incremental sync: only re-analyzes changed files (default)","Force full sync: --full bypasses incremental cache","Monorepo support: --package=<name> for single package sync","Nested PRJCT.md inheritance","Per-package CLAUDE.md generation"]},{name:"perf",group:"core",description:"Performance dashboard - startup, memory, context, and handoff metrics",usage:{claude:"/p:perf",terminal:"prjct perf [days]"},params:"[days]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["Startup time tracking","Memory usage snapshots","Context correctness rate","Subtask handoff rate","Command duration breakdown"]},{name:"velocity",group:"core",description:"Sprint-based velocity dashboard with trend detection and projections",usage:{claude:"/p:velocity",terminal:"prjct velocity [backlogPoints]"},params:"[backlogPoints]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["Sprint-by-sprint velocity breakdown","Trend detection (improving/stable/declining)","Estimation accuracy tracking","Over/under estimation pattern detection","Completion projections for backlog"]},{name:"suggest",group:"core",description:"Smart recommendations based on project state",usage:{claude:"/p:suggest",terminal:"prjct suggest"},implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"status",group:"core",description:"Check if CLAUDE.md context is stale and needs resync",usage:{claude:"/p:status",terminal:"prjct status"},params:"[--json]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["Compares current HEAD with last sync commit","Counts commits and days since sync","Detects significant file changes","Configurable staleness thresholds"]},{name:"seal",group:"core",description:"Seal the current draft analysis with a commit-hash signature",usage:{claude:"/p:seal",terminal:"prjct seal"},params:"[--json]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["Locks draft analysis with SHA-256 signature","Only sealed analysis feeds task context","Detects staleness when HEAD moves past sealed commit"]},{name:"verify",group:"core",description:"Verify integrity of sealed analysis",usage:{claude:"/p:verify",terminal:"prjct verify"},params:"[--json]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["Recomputes SHA-256 signature and compares","Detects if sealed analysis was modified"]},{name:"help",group:"core",description:"Contextual help and guidance",usage:{claude:"/p:help [topic]",terminal:"prjct help [topic]"},params:"[topic]",implemented:!0,hasTemplate:!0,requiresProject:!1},{name:"design",group:"optional",description:"Design system architecture, APIs, and components",usage:{claude:"/p:design [target]",terminal:"prjct design [target]"},params:"[target] --type architecture|api|component",implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"cleanup",group:"optional",description:"Clean up temp files and old entries",usage:{claude:"/p:cleanup",terminal:"prjct cleanup"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"analyze",group:"optional",description:"Analyze repository and sync tasks",usage:{claude:"/p:analyze",terminal:"prjct analyze"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"undo",group:"optional",description:"Revert to previous snapshot",usage:{claude:"/p:undo",terminal:"prjct undo"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0,features:["Git-based snapshots","Preserves redo history"]},{name:"redo",group:"optional",description:"Redo previously undone changes",usage:{claude:"/p:redo",terminal:"prjct redo"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"history",group:"optional",description:"View snapshot history",usage:{claude:"/p:history",terminal:"prjct history"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"recover",group:"optional",description:"Recover abandoned session with context",usage:{claude:"/p:recover",terminal:"prjct recover"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"git",group:"optional",description:"Smart git operations with context",usage:{claude:"/p:git [op]",terminal:"prjct git [op]"},params:"[operation]",implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"test",group:"optional",description:"Run tests with auto-fix",usage:{claude:"/p:test",terminal:"prjct test"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"workflow",group:"optional",description:"Configure workflow hooks via natural language",usage:{claude:'/p:workflow ["config"]',terminal:'prjct workflow ["config"]'},params:'["natural language config"]',implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0,features:["Natural language configuration","Before/after hooks for task, done, ship, sync","Permanent, session, or one-time preferences"]},{name:"start",group:"setup",description:"First-time setup (install commands to editors)",usage:{claude:null,terminal:"prjct start"},implemented:!0,hasTemplate:!1,requiresProject:!1},{name:"setup",group:"setup",description:"Reconfigure editor installations",usage:{claude:"/p:setup",terminal:"prjct setup"},params:"[--force] [--editor <name>]",implemented:!0,hasTemplate:!0,requiresProject:!1},{name:"migrate",group:"setup",description:"Migrate project to UUID format + sync",usage:{claude:"/p:migrate",terminal:null},implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"auth",group:"setup",description:"Manage cloud authentication",usage:{claude:"/p:auth [action]",terminal:"prjct auth [action]"},params:"[login|logout|status]",implemented:!0,hasTemplate:!0,requiresProject:!1},{name:"context",group:"setup",description:"Smart context filtering tools for AI agents",usage:{claude:null,terminal:"prjct context <tool> [args]"},params:"<tool> [args]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["files - Find relevant files for a task","signatures - Extract code structure (~90% compression)","imports - Analyze dependency graphs","recent - Find hot files from git history","summary - Intelligent file summarization"]},{name:"uninstall",group:"setup",description:"Complete system removal of prjct",usage:{claude:null,terminal:"prjct uninstall"},params:"[--force] [--backup] [--dry-run]",implemented:!0,hasTemplate:!1,requiresProject:!1,features:["Removes ~/.prjct-cli/ data","Cleans CLAUDE.md prjct section","Uninstalls Homebrew/npm packages","Backup option before deletion"]}]});var ey={};Ne(ey,{formatAgentCommandHelp:()=>Yh,formatCommandHelp:()=>Qh,formatCommandList:()=>Zh,formatMainHelp:()=>Kh,formatTerminalCommandHelp:()=>Xh,getHelp:()=>mE});import H from"chalk";function Kh(){let r=[];r.push(""),r.push(`${H.cyan.bold("prjct")} v${se} - Context layer for AI coding agents`),r.push(H.dim("Works with Claude Code, Gemini CLI, Cursor, Windsurf, and more.")),r.push(""),r.push(H.bold("QUICK START")),r.push(H.dim("\u2500".repeat(60))),r.push(` ${H.green("1.")} prjct start ${H.dim("# Configure AI providers")}`),r.push(` ${H.green("2.")} cd my-project && prjct init`),r.push(` ${H.green("3.")} Open in Claude Code / Gemini CLI / Cursor`),r.push(` ${H.green("4.")} p. sync ${H.dim("# Analyze project")}`),r.push(""),r.push(H.bold("TERMINAL COMMANDS")),r.push(H.dim("\u2500".repeat(60)));for(let t of qh){let n=`prjct ${t.name}`.padEnd(22);r.push(` ${n} ${t.description}`)}r.push(""),r.push(`${H.bold("AI AGENT COMMANDS")} ${H.dim("(inside Claude/Gemini/Cursor)")}`),r.push(H.dim("\u2500".repeat(60))),r.push(` ${"Command".padEnd(22)} Description`),r.push(` ${H.dim("\u2500".repeat(56))}`);let e=tr.filter(t=>t.group==="core"&&t.usage?.claude);for(let t of e.slice(0,10)){let n=`p. ${t.name}`.padEnd(22);r.push(` ${n} ${t.description}`)}r.push(` ${H.dim(`... and ${e.length-10} more (run 'prjct help commands')`)}`),r.push(""),r.push(H.bold("FLAGS")),r.push(H.dim("\u2500".repeat(60)));for(let t of dE)r.push(` ${t.flag.padEnd(22)} ${t.description}`);return r.push(""),r.push(H.bold("MORE INFO")),r.push(H.dim("\u2500".repeat(60))),r.push(` Documentation: ${H.cyan("https://prjct.app")}`),r.push(` GitHub: ${H.cyan("https://github.com/jlopezlira/prjct-cli")}`),r.push(" Per-command: prjct help <command>"),r.push(""),r.join(`
1455
- `)}function Xh(r){let e=qh.find(n=>n.name===r);if(!e)return null;let t=[];if(t.push(""),t.push(`${H.cyan.bold(`prjct ${e.name}`)} - ${e.description}`),t.push(""),t.push(H.bold("USAGE")),t.push(` ${e.example}`),t.push(""),e.options){t.push(H.bold("OPTIONS"));for(let n of e.options)t.push(` ${n}`);t.push("")}if(e.subcommands){t.push(H.bold("SUBCOMMANDS"));for(let n of e.subcommands)t.push(` ${n}`);t.push("")}return t.join(`
1456
- `)}function Yh(r){let e=tr.find(s=>s.name===r);if(!e)return null;let t=[];if(t.push(""),t.push(`${H.cyan.bold(`p. ${e.name}`)} - ${e.description}`),t.push(""),t.push(H.bold("USAGE")),e.usage?.claude&&t.push(` Claude/Gemini: ${e.usage.claude.replace("/p:","p. ")}`),e.usage?.terminal&&t.push(` Terminal: ${e.usage.terminal}`),t.push(""),e.params&&(t.push(H.bold("PARAMETERS")),t.push(` ${e.params}`),t.push("")),e.features&&e.features.length>0){t.push(H.bold("FEATURES"));for(let s of e.features)t.push(` \u2022 ${s}`);t.push("")}e.blockingRules&&(t.push(H.bold("REQUIREMENTS")),t.push(` ${H.yellow("\u26A0")} ${e.blockingRules.check}`),t.push(""));let n=fo[e.group];return n&&(t.push(H.dim(`Category: ${n.title}`)),e.isOptional&&t.push(H.dim("This is an optional command.")),t.push("")),t.join(`
1457
- `)}function Qh(r){let e=Xh(r);if(e)return e;let t=Yh(r);return t||`
1458
- ${H.yellow(`Command '${r}' not found.`)}
1459
-
1460
- Run 'prjct help' to see all available commands.
1461
- `}function Zh(){let r=[];r.push(""),r.push(H.cyan.bold("All Commands")),r.push("");let e=Object.entries(fo).sort((t,n)=>t[1].order-n[1].order);for(let[t,n]of e){let s=tr.filter(o=>o.group===t);if(s.length!==0){r.push(`${H.bold(n.title)} ${H.dim(`(${s.length} commands)`)}`),r.push(H.dim(n.description)),r.push("");for(let o of s){let i=`p. ${o.name}`.padEnd(18),a=o.description.length>45?`${o.description.slice(0,42)}...`:o.description;r.push(` ${i} ${a}`)}r.push("")}}return r.push(H.dim("Run 'prjct help <command>' for detailed help on a specific command.")),r.push(""),r.join(`
1462
- `)}function mE(r){return r?r==="commands"||r==="all"?Zh():Qh(r):Kh()}var qh,dE,ty=y(()=>{"use strict";Vu();st();qh=[{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:"linear",description:"Linear issue tracker CLI",example:"prjct linear list",subcommands:["list","get","create","update"]},{name:"uninstall",description:"Complete system removal of prjct",example:"prjct uninstall --backup",options:["--force","--backup","--dry-run","--keep-package"]}],dE=[{flag:"-q, --quiet",description:"Suppress all output (errors to stderr only)"},{flag:"-v, --version",description:"Show version and provider status"},{flag:"-h, --help",description:"Show this help message"}];l(Kh,"formatMainHelp");l(Xh,"formatTerminalCommandHelp");l(Yh,"formatAgentCommandHelp");l(Qh,"formatCommandHelp");l(Zh,"formatCommandList");l(mE,"getHelp")});var iy={};Ne(iy,{installAntigravitySkill:()=>oy,needsAntigravityInstallation:()=>wE,run:()=>ry});import{execSync as gE}from"node:child_process";import L from"node:fs/promises";import fs from"node:os";import Z from"node:path";import ue from"chalk";async function fE(r){let e=r.name==="claude"?"@anthropic-ai/claude-code":"@google/gemini-cli";if(!Qs.isAvailable("npm"))return console.log(`${ue.yellow("\u26A0\uFE0F npm is not available")}`),console.log(""),console.log(`${ue.dim(`Install ${r.displayName} using one of:`)}`),console.log(ue.dim(" \u2022 Install Node.js: https://nodejs.org")),console.log(ue.dim(` \u2022 Use Homebrew: brew install ${r.name==="claude"?"claude":"gemini"}`)),console.log(ue.dim(` \u2022 Use npx directly: npx ${e}`)),console.log(""),!1;try{return console.log(ue.yellow(`\u{1F4E6} ${r.displayName} not found. Installing...`)),console.log(""),gE(`npm install -g ${e}`,{stdio:"inherit",timeout:Es("NPM_INSTALL")}),console.log(""),console.log(`${ue.green("\u2713")} ${r.displayName} installed successfully`),console.log(""),!0}catch(t){let n=t;return n.killed&&n.signal==="SIGTERM"?(console.log(ue.yellow(`\u26A0\uFE0F Installation timed out for ${r.displayName}`)),console.log(""),console.log(ue.dim("The npm install took too long. Try:")),console.log(ue.dim(" \u2022 Set PRJCT_TIMEOUT_NPM_INSTALL=300000 for 5 minutes")),console.log(ue.dim(` \u2022 Run manually: npm install -g ${e}`))):console.log(ue.yellow(`\u26A0\uFE0F Failed to install ${r.displayName}: ${n.message}`)),console.log(""),console.log(ue.dim("Alternative installation methods:")),console.log(ue.dim(` \u2022 npm: npm install -g ${e}`)),console.log(ue.dim(` \u2022 yarn: yarn global add ${e}`)),console.log(ue.dim(` \u2022 pnpm: pnpm add -g ${e}`)),console.log(ue.dim(` \u2022 brew: brew install ${r.name==="claude"?"claude":"gemini"}`)),console.log(""),!1}}async function ry(){let r=await Pt(),e=await Oa(),t=$e[e.provider],n={provider:e.provider,providers:[],cliInstalled:!1,commandsAdded:0,commandsUpdated:0,configAction:null},s=["claude","gemini"];for(let i of s){let a=$e[i],c=r[i],u={provider:i,cliInstalled:!1,commandsAdded:0,commandsUpdated:0,configAction:null};if(!c.installed)if(i===e.provider)if(await fE(a))u.cliInstalled=!0,n.cliInstalled=!0;else throw new Error(`${a.displayName} installation failed`);else continue;if(i==="claude"){if(await be.detectClaude()){let m=await be.syncCommands();m.success&&(u.commandsAdded=m.added,u.commandsUpdated=m.updated,n.commandsAdded+=m.added,n.commandsUpdated+=m.updated);let d=await be.installGlobalConfig();d.success&&(u.configAction=d.action,n.configAction||(n.configAction=d.action)),await be.installDocs(),await SE(),await bE()}}else if(i==="gemini"){await hE()&&(u.commandsAdded=1,n.commandsAdded+=1);let m=await yE();m.success&&(u.configAction=m.action)}n.providers.push(u)}(await bs()).installed&&(await oy()).success&&console.log(` ${ue.green("\u2713")} Antigravity skill installed`),await Fo.saveConfig(se,await be.getInstallPath(),e.provider),await kE();for(let i of n.providers)PE(i,$e[i.provider]);return n}async function hE(){try{let r=Z.join(fs.homedir(),".gemini","commands"),e=Z.join(r,"p.toml");await L.mkdir(r,{recursive:!0});let t=Se("commands/p.toml");if(t)return await L.writeFile(e,t,"utf-8"),!0;let n=Z.join(ce,"templates","commands","p.toml");return await C(n)?(await L.copyFile(n,e),!0):!1}catch(r){return F.warn(`Gemini router warning: ${w(r)}`),!1}}async function yE(){try{let r=Z.join(fs.homedir(),".gemini"),e=Z.join(r,"GEMINI.md");await L.mkdir(r,{recursive:!0});let t=Se("global/GEMINI.md");if(!t){let d=Z.join(ce,"templates","global","GEMINI.md");t=await L.readFile(d,"utf-8")}let n="",s=!1;try{n=await L.readFile(e,"utf-8"),s=!0}catch(d){if(k(d))s=!1;else throw d}if(!s)return await L.writeFile(e,t,"utf-8"),{success:!0,action:"created"};let o="<!-- prjct:start - DO NOT REMOVE THIS MARKER -->",i="<!-- prjct:end - DO NOT REMOVE THIS MARKER -->";if(!(n.includes(o)&&n.includes(i))){let d=`${n}
1463
-
1464
- ${t}`;return await L.writeFile(e,d,"utf-8"),{success:!0,action:"appended"}}let c=n.substring(0,n.indexOf(o)),u=n.substring(n.indexOf(i)+i.length),p=t.substring(t.indexOf(o),t.indexOf(i)+i.length),m=c+p+u;return await L.writeFile(e,m,"utf-8"),{success:!0,action:"updated"}}catch(r){return F.warn(`Gemini config warning: ${w(r)}`),{success:!1,action:null}}}async function oy(){try{let r=Z.join(fs.homedir(),".gemini","antigravity","skills"),e=Z.join(r,"prjct"),t=Z.join(e,"SKILL.md");await L.mkdir(e,{recursive:!0});let n=await C(t),s=Se("antigravity/SKILL.md");if(!s){let o=Z.join(ce,"templates","antigravity","SKILL.md");if(!await C(o))return F.warn("Antigravity SKILL.md template not found"),{success:!1,action:null};s=await L.readFile(o,"utf-8")}return await L.writeFile(t,s,"utf-8"),{success:!0,action:n?"updated":"created"}}catch(r){return F.warn(`Antigravity skill warning: ${w(r)}`),{success:!1,action:null}}}async function wE(){let r=await bs();return r.installed&&!r.skillInstalled}async function kE(){try{let r=Z.join(fs.homedir(),".prjct-cli","projects");if(!await C(r))return;let e=(await L.readdir(r,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name),t=0;for(let n of e){let s=Z.join(r,n,"project.json");if(await C(s))try{let o=await L.readFile(s,"utf8"),i=JSON.parse(o);i.cliVersion!==se&&(i.cliVersion=se,await L.writeFile(s,JSON.stringify(i,null,2)),t++)}catch(o){if(!k(o)&&!(o instanceof SyntaxError))throw o}}t>0&&console.log(` ${ue.green("\u2713")} Updated ${t} project(s) to v${se}`)}catch(r){k(r)||F.warn(`Migration warning: ${w(r)}`)}}async function ny(r,e){let t={};if(await C(r))try{t=JSON.parse(await L.readFile(r,"utf8"))}catch(n){if(!(n instanceof SyntaxError))throw n}t.statusLine={type:"command",command:e},await L.writeFile(r,JSON.stringify(t,null,2))}async function SE(){try{let r=Z.join(fs.homedir(),".claude"),e=Z.join(r,"settings.json"),t=Z.join(r,"prjct-statusline.sh"),n=Z.join(fs.homedir(),".prjct-cli","statusline"),s=Z.join(n,"statusline.sh"),o=Z.join(n,"themes"),i=Z.join(n,"lib"),a=Z.join(n,"components"),c=Z.join(n,"config.json"),u=Z.join(ce,"assets","statusline"),p=Z.join(u,"statusline.sh"),m=Z.join(u,"themes"),d=Z.join(u,"lib"),g=Z.join(u,"components"),f=Z.join(u,"default-config.json");if(await C(r)||await L.mkdir(r,{recursive:!0}),await C(n)||await L.mkdir(n,{recursive:!0}),await C(o)||await L.mkdir(o,{recursive:!0}),await C(i)||await L.mkdir(i,{recursive:!0}),await C(a)||await L.mkdir(a,{recursive:!0}),await C(s)){let S=await L.readFile(s,"utf8");if(S.includes("CLI_VERSION=")){let E=S.match(/CLI_VERSION="([^"]*)"/);if(E&&E[1]!==se){let x=S.replace(/CLI_VERSION="[^"]*"/,`CLI_VERSION="${se}"`);await L.writeFile(s,x,{mode:493})}await fa(d,i),await fa(g,a),await sy(t,s),await ny(e,t);return}}if(await C(p)){let S=await L.readFile(p,"utf8");if(S=S.replace(/CLI_VERSION="[^"]*"/,`CLI_VERSION="${se}"`),await L.writeFile(s,S,{mode:493}),await fa(d,i),await fa(g,a),await C(m)){let E=await L.readdir(m);for(let x of E){let $=Z.join(m,x),z=Z.join(o,x);await L.copyFile($,z)}}!await C(c)&&await C(f)&&await L.copyFile(f,c)}else{let S=`#!/bin/bash
1465
- # prjct Status Line for Claude Code
1466
- CLI_VERSION="${se}"
1467
- input=$(cat)
1468
- CWD=$(echo "$input" | jq -r '.workspace.current_dir // "~"' 2>/dev/null)
1469
- CONFIG="$CWD/.prjct/prjct.config.json"
1470
- if [ -f "$CONFIG" ]; then
1471
- PROJECT_ID=$(jq -r '.projectId // ""' "$CONFIG" 2>/dev/null)
1472
- if [ -n "$PROJECT_ID" ]; then
1473
- PROJECT_JSON="$HOME/.prjct-cli/projects/$PROJECT_ID/project.json"
1474
- if [ -f "$PROJECT_JSON" ]; then
1475
- PROJECT_VERSION=$(jq -r '.cliVersion // ""' "$PROJECT_JSON" 2>/dev/null)
1476
- if [ -z "$PROJECT_VERSION" ] || [ "$PROJECT_VERSION" != "$CLI_VERSION" ]; then
1477
- echo "prjct v$CLI_VERSION - run p. sync"
1478
- exit 0
1479
- fi
1480
- else
1481
- echo "prjct v$CLI_VERSION - run p. sync"
1482
- exit 0
1483
- fi
1484
- STATE="$HOME/.prjct-cli/projects/$PROJECT_ID/storage/state.json"
1485
- if [ -f "$STATE" ]; then
1486
- TASK=$(jq -r '.currentTask.description // ""' "$STATE" 2>/dev/null)
1487
- if [ -n "$TASK" ]; then
1488
- echo "$TASK"
1489
- exit 0
1490
- fi
1491
- fi
1492
- fi
1493
- fi
1494
- echo "prjct"
1495
- `;await L.writeFile(s,S,{mode:493})}await sy(t,s),await ny(e,t)}catch(r){k(r)||F.warn(`Status line warning: ${w(r)}`)}}async function bE(){try{let r=Z.join(fs.homedir(),".claude"),e=Z.join(r,"mcp.json");await C(r)||await L.mkdir(r,{recursive:!0});let t={mcpServers:{context7:{command:"npx",args:["-y","@upstash/context7-mcp@latest"]}}};if(await C(e)){let n=await L.readFile(e,"utf-8"),s=JSON.parse(n);if(s.mcpServers?.context7)return;s.mcpServers=s.mcpServers||{},s.mcpServers.context7=t.mcpServers.context7,await L.writeFile(e,JSON.stringify(s,null,2),"utf-8")}else await L.writeFile(e,JSON.stringify(t,null,2),"utf-8")}catch(r){F.warn(`Context7 MCP setup warning: ${w(r)}`)}}async function fa(r,e){if(!await C(r))return;let t=await L.readdir(r);for(let n of t)if(n.endsWith(".sh")){let s=Z.join(r,n),o=Z.join(e,n);await L.copyFile(s,o),await L.chmod(o,493)}}async function sy(r,e){try{if(await C(r)){if((await L.lstat(r)).isSymbolicLink()&&await L.readlink(r)===e)return;await L.unlink(r)}await L.symlink(e,r)}catch{try{await C(e)&&(await L.copyFile(e,r),await L.chmod(r,493))}catch(n){k(n)||F.warn(`Symlink fallback warning: ${n.message}`)}}}function PE(r,e){if(console.log(""),r.cliInstalled?console.log(` ${ue.green("\u2713")} ${e.displayName} CLI installed`):console.log(` ${ue.green("\u2713")} ${e.displayName} CLI found`),r.commandsAdded+r.commandsUpdated>0){let n=[];r.commandsAdded>0&&n.push(`${r.commandsAdded} new`),r.commandsUpdated>0&&n.push(`${r.commandsUpdated} updated`),console.log(` ${ue.green("\u2713")} Commands synced (${n.join(", ")})`)}else console.log(` ${ue.green("\u2713")} Commands up to date`);r.configAction==="created"?console.log(` ${ue.green("\u2713")} Global config created (${e.contextFile})`):r.configAction==="updated"?console.log(` ${ue.green("\u2713")} Global config updated (${e.contextFile})`):r.configAction==="appended"&&console.log(` ${ue.green("\u2713")} Global config merged (${e.contextFile})`),console.log("")}var CE,ay=y(()=>{"use strict";Yn();Ki();M();Kt();me();Gn();st();He();En();Va();l(fE,"installAICLI");l(ry,"run");l(hE,"installGeminiRouter");l(yE,"installGeminiGlobalConfig");l(oy,"installAntigravitySkill");l(wE,"needsAntigravityInstallation");l(kE,"migrateProjectsCliVersion");l(ny,"ensureStatusLineSettings");l(SE,"installStatusLine");l(bE,"installContext7MCP");l(fa,"installStatusLineModules");l(sy,"ensureStatusLineSymlink");l(PE,"showResults");CE=process.argv[1]?.includes("setup.ts")||process.argv[1]?.includes("setup.js");CE&&ry().catch(r=>{console.error("Setup error:",r.message),process.exit(1)})});var ha,G,ho=y(()=>{"use strict";Ye();ee();M();ne();ha=class{static{l(this,"CommandRegistry")}handlers=new Map;handlerFns=new Map;metadata=new Map;categories=new Map;noProjectCommands=new Set(["init","setup","start","migrateAll"]);register(e,t){this.handlers.set(e.name,e),this.setMeta(e.name,t)}registerFn(e,t,n){this.handlerFns.set(e,t),this.setMeta(e,n)}setMeta(e,t){let n=t?.requiresProject??!this.noProjectCommands.has(e);this.metadata.set(e,{name:e,group:t?.group??"unknown",description:t?.description??"",requiresProject:n,usage:t?.usage??{claude:null,terminal:null},implemented:t?.implemented??!0,hasTemplate:t?.hasTemplate??!1,params:t?.params,blockingRules:t?.blockingRules,features:t?.features,isOptional:t?.isOptional,deprecated:t?.deprecated,replacedBy:t?.replacedBy})}registerCategory(e,t){this.categories.set(e,t)}registerMethod(e,t,n,s){let o=t[n];if(typeof o!="function")throw new Error(`${String(n)} is not a function`);let i=l(async(a,c)=>a!=null?o.call(t,a,c.projectPath):o.call(t,c.projectPath),"wrapper");this.handlerFns.set(e,i),this.setMeta(e,s)}has(e){return this.handlers.has(e)||this.handlerFns.has(e)}list(){return[...this.handlers.keys(),...this.handlerFns.keys()]}listByGroup(e){return Array.from(this.metadata.entries()).filter(([,t])=>t.group===e).map(([t])=>t)}getGroups(){let e=new Set;for(let t of this.metadata.values())e.add(t.group);return Array.from(e)}getMeta(e){return this.metadata.get(e)}getAll(){return Array.from(this.metadata.values())}getByName(e){return this.metadata.get(e)}getByCategory(e){return this.getAll().filter(t=>t.group===e)}getAllImplemented(){return this.getAll().filter(e=>e.implemented)}getAllWithTemplates(){return this.getAll().filter(e=>e.hasTemplate)}getClaudeCommands(){return this.getAll().filter(e=>e.usage.claude!==null)}getTerminalCommands(){return this.getAll().filter(e=>e.usage.terminal!==null)}getAllCategories(){return new Map(this.categories)}getCategory(e){return this.categories.get(e)}getRequiresInit(){return this.getAll().filter(e=>e.requiresProject)}getWithBlockingRules(){return this.getAll().filter(e=>e.blockingRules!==void 0)}getOptionalCommands(){return this.getAll().filter(e=>e.isOptional)}getDeprecatedCommands(){return this.getAll().filter(e=>e.deprecated)}getStats(){let e=this.getAll(),t={};for(let n of this.categories.keys())t[n]=e.filter(s=>s.group===n).length;return{total:e.length,implemented:e.filter(n=>n.implemented).length,withTemplates:e.filter(n=>n.hasTemplate).length,claudeOnly:e.filter(n=>n.usage.claude&&!n.usage.terminal).length,terminalOnly:e.filter(n=>!n.usage.claude&&n.usage.terminal).length,both:e.filter(n=>n.usage.claude&&n.usage.terminal).length,requiresInit:e.filter(n=>n.requiresProject).length,byCategory:t}}validate(){let e=[],t=this.getAll(),n=t.map(a=>a.name),s=n.filter((a,c)=>n.indexOf(a)!==c);s.length>0&&e.push(`Duplicate command names: ${s.join(", ")}`);let o=t.filter(a=>a.hasTemplate&&!a.implemented);o.length>0&&e.push(`Commands with templates but not implemented: ${o.map(a=>a.name).join(", ")}`);let i=Array.from(this.categories.keys());if(i.length>0){let a=t.filter(c=>!i.includes(c.group));a.length>0&&e.push(`Invalid categories: ${a.map(c=>`${c.name}:${c.group}`).join(", ")}`)}return{valid:e.length===0,issues:e}}async buildContext(e){let t=await I.getProjectId(e);if(!t)throw new Error("No prjct project found. Run /p:init first.");return{projectId:t,projectPath:e,globalPath:P.getGlobalProjectPath(t),timestamp:b()}}async execute(e,t,n=process.cwd()){let s=this.metadata.get(e),o;if(s?.requiresProject===!1)o={projectId:"",projectPath:n,globalPath:"",timestamp:b()};else try{o=await this.buildContext(n)}catch(c){return{success:!1,error:w(c)}}let i=this.handlers.get(e);if(i)return i.execute(t,o);let a=this.handlerFns.get(e);return a?a(t,o):{success:!1,error:`Command not found: ${e}`}}async executeWithoutProject(e,t,n=process.cwd()){let s=this.handlers.get(e);if(s){let i={projectId:"",projectPath:n,globalPath:"",timestamp:b()};return s.execute(t,i)}let o=this.handlerFns.get(e);if(o){let i={projectId:"",projectPath:n,globalPath:"",timestamp:b()};return o(t,i)}return{success:!1,error:`Command not found: ${e}`}}clear(){this.handlers.clear(),this.handlerFns.clear(),this.metadata.clear(),this.categories.clear()}},G=new ha});import vE from"node:path";var nr,qu=y(()=>{"use strict";Fn();sn();M();tt();ho();nr=class extends ve{static{l(this,"AnalyticsCommands")}async dash(e="default",t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await I.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=vE.basename(t),i=await le.getCurrentTask(s),a=await ot.getActiveTasks(s),c=await es.getRecent(s,5),u=await dn.getPending(s);if(e==="compact"){let g=i?`\u{1F3AF} ${i.description.slice(0,30)}`:"\u{1F4A4} idle",f=`\u{1F4CB} ${a.length}`,S=`\u{1F680} ${c.length}`;return h.done(`${g} | ${f} | ${S}`),{success:!0,view:"compact"}}if(e==="week"||e==="month"){let g=e==="week"?7:30,f=U.getDaysAgo(g),S=P.getFilePath(s,"memory","context.jsonl"),E=[];try{E=(await Mt.readJsonLines(S)).filter(_e=>new Date(_e.timestamp)>=f)}catch{E=[]}let x={tasksCompleted:E.filter(z=>z.action==="task_completed").length,featuresShipped:E.filter(z=>z.action==="feature_shipped").length,totalActions:E.length};console.log(`
1496
- \u{1F4CA} ${e.toUpperCase()} PROGRESS - ${o}
1497
- `),console.log("\u2550".repeat(50)),console.log(` Tasks completed: ${x.tasksCompleted}`),console.log(` Features shipped: ${x.featuresShipped}`),console.log(` Total actions: ${x.totalActions}`),console.log("\u2550".repeat(50));let $=this._generateSparkline(E,g);return console.log(`
1498
- Activity: ${$}
1499
- `),{success:!0,view:e,metrics:x}}if(e==="roadmap"){let g=await rt.build(t),f=await ze.get("Read")(g.paths.roadmap);if(console.log(`
1500
- \u{1F5FA}\uFE0F ROADMAP - ${o}
1501
- `),console.log("\u2550".repeat(50)),!f||f.trim()==="# ROADMAP")console.log(" No features planned yet."),console.log(` Use /p:feature to add features.
1502
- `);else{let S=f.split("##").filter(E=>E.trim()&&!E.includes("ROADMAP"));S.slice(0,5).forEach((E,x)=>{let $=E.split(`
1503
- `)[0].trim();console.log(` ${x+1}. ${$}`)}),S.length>5&&console.log(` ... and ${S.length-5} more`)}return console.log(`${"\u2550".repeat(50)}
1504
- `),{success:!0,view:"roadmap"}}console.log(`
1505
- \u{1F4CA} DASHBOARD - ${o}
1506
- `),console.log("\u2550".repeat(50));let p=io(t),m=await p.check(s),d=p.getWarning(m);if(d&&console.log(`
1507
- ${d}`),console.log(`
1508
- \u{1F3AF} CURRENT FOCUS`),i){if(console.log(` ${i.description}`),i.startedAt){let g=U.calculateDuration(new Date(i.startedAt));console.log(` Started: ${g} ago`)}}else console.log(" No active task. Use /p:work to start.");return console.log(`
1509
- \u{1F4CB} QUEUE`),a.length===0?console.log(" Queue is empty"):(a.slice(0,3).forEach((g,f)=>{let S=g.priority?`[${g.priority}]`:"";console.log(` ${f+1}. ${g.description.slice(0,40)} ${S}`)}),a.length>3&&console.log(` ... and ${a.length-3} more`)),console.log(`
1510
- \u{1F680} RECENT SHIPS`),c.length===0?console.log(" Nothing shipped yet"):c.slice(0,3).forEach(g=>{let f=g.shippedAt?new Date(g.shippedAt).toLocaleDateString():"";console.log(` \u2022 ${g.name} ${f?`(${f})`:""}`)}),console.log(`
1511
- \u{1F4A1} IDEAS`),console.log(` ${u.length} pending ideas`),console.log(`
1512
- ${"\u2550".repeat(50)}`),console.log(`\u{1F4A1} /p:work to start | /p:done to complete | /p:ship to ship
1513
- `),await this.logToMemory(t,"dash_viewed",{view:e,timestamp:U.getTimestamp()}),{success:!0,view:"default",stats:{currentTask:i?.description||null,queueCount:a.length,shippedCount:c.length,ideasCount:u.length}}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}async help(e="",t=process.cwd()){try{if(!e){console.log(`
1514
- PRJCT COMMANDS
1515
- `),console.log("=".repeat(50));let i=G.getAllCategories(),a=G.getAll(),c={};return a.forEach(u=>{u.deprecated||(c[u.group]||(c[u.group]=[]),c[u.group].push(u))}),Object.entries(c).forEach(([u,p])=>{let m=i.get(u);console.log(`
1516
- ${m?.title||u}:`),p.forEach(d=>{let g=d.params?` ${d.params}`:"";console.log(` ${d.name}${g}`),console.log(` ${d.description}`)})}),console.log(`
1517
- ${"\u2550".repeat(50)}`),console.log(`\u{1F4A1} Use /p:help <command> for detailed help
1518
- `),{success:!0,topic:"overview"}}let n=G.getByName(e);if(n){if(console.log(`
1519
- \u{1F4DA} HELP: /p:${n.name}
1520
- `),console.log("\u2550".repeat(50)),console.log(`Description: ${n.description}`),n.params&&console.log(`Parameters: ${n.params}`),n.usage&&(console.log(`
1521
- Usage:`),n.usage.claude&&console.log(` Claude: ${n.usage.claude}`),n.usage.terminal&&console.log(` Terminal: ${n.usage.terminal}`)),n.features){console.log(`
1522
- Features:`);for(let i of n.features)console.log(` \u2022 ${i}`)}return console.log(`
1523
- ${"\u2550".repeat(50)}
1524
- `),{success:!0,topic:e,command:n}}let s={start:{command:"work",hint:"Start working on a task"},begin:{command:"work",hint:"Start working on a task"},finish:{command:"done",hint:"Mark current task complete"},complete:{command:"done",hint:"Mark current task complete"},deploy:{command:"ship",hint:"Ship a feature"},release:{command:"ship",hint:"Ship a feature"},status:{command:"dash",hint:"View project dashboard"},overview:{command:"dash",hint:"View project dashboard"},queue:{command:"next",hint:"View task queue"},tasks:{command:"next",hint:"View task queue"},add:{command:"feature",hint:"Add a new feature"},new:{command:"feature",hint:"Add a new feature"},break:{command:"pause",hint:"Pause current task"},stop:{command:"pause",hint:"Pause current task"},continue:{command:"resume",hint:"Resume paused task"},back:{command:"resume",hint:"Resume paused task"}},o=e.toLowerCase();for(let[i,a]of Object.entries(s))if(o.includes(i))return console.log(`
1525
- \u{1F4A1} Did you mean /p:${a.command}?`),console.log(` ${a.hint}
1526
- `),{success:!0,topic:e,suggestion:a.command};return console.log(`
1527
- \u2753 Unknown topic: ${e}`),console.log(` Use /p:help to see all commands
1528
- `),{success:!1,error:`Unknown topic: ${e}`}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}_generateSparkline(e,t){let n=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],s=new Date,o=[];for(let a=t-1;a>=0;a--){let c=new Date(s);c.setDate(c.getDate()-a);let u=new Date(c.setHours(0,0,0,0)),p=new Date(c.setHours(23,59,59,999)),m=e.filter(d=>{let g=new Date(d.timestamp);return g>=u&&g<=p}).length;o.push(m)}let i=Math.max(...o,1);return o.map(a=>n[Math.floor(a/i*(n.length-1))]).join("")}}});import xE from"node:fs/promises";import TE from"node:path";var hs,IW,Ku=y(()=>{"use strict";$l();Ye();ee();sn();M();hs=class{static{l(this,"ContextCommands")}async context(e=null,t=process.cwd()){try{let n=(e||"").trim().split(/\s+/),s=n[0]||"task",o=n.slice(1).join(" "),i=await I.readConfig(t);if(!i||!i.projectId)return console.log(JSON.stringify({projectId:"",globalPath:"",currentTask:null,domains:[],primaryDomain:null,agents:[],subtasks:null,repoAnalysis:{ecosystem:"unknown",frameworks:[],hasTests:!1,technologies:[]}},null,2)),{success:!1,message:"No prjct project. Run `p. init` first."};let a=i.projectId,c=P.getGlobalProjectPath(a),u=await le.read(a),p=u?.currentTask?{id:u.currentTask.id,description:u.currentTask.description,startedAt:u.currentTask.startedAt,subtasks:u.currentTask.subtasks?.map(f=>({id:f.id,description:f.description,status:f.status,domain:f.domain})),currentSubtaskIndex:u.currentTask.currentSubtaskIndex}:null,m=null;if(o)try{m=await Ci.execute(s,o,t)}catch(f){console.error(`Warning: Orchestrator failed: ${w(f)}`)}let d=await this.loadRepoAnalysis(c),g={projectId:a,globalPath:c,currentTask:p,domains:m?.detectedDomains||[],primaryDomain:m?.primaryDomain||null,agents:m?.agents.map(f=>({name:f.name,domain:f.domain,filePath:f.filePath,skills:f.skills,preview:f.content.substring(0,500)}))||[],subtasks:m?.subtasks?.map(f=>({id:f.id,description:f.description,domain:f.domain,agent:f.agent,status:f.status,order:f.order}))||null,repoAnalysis:{ecosystem:d?.ecosystem||"unknown",frameworks:d?.frameworks||[],hasTests:d?.hasTests||!1,technologies:d?.technologies||[]}};return console.log(JSON.stringify(g,null,2)),{success:!0,message:""}}catch(n){return{success:!1,message:`Context error: ${w(n)}`}}}async loadRepoAnalysis(e){try{let t=TE.join(e,"analysis","repo-analysis.json"),n=await xE.readFile(t,"utf-8"),s=JSON.parse(n);return{ecosystem:s.ecosystem||"unknown",frameworks:s.frameworks||[],hasTests:s.hasTests??!1,technologies:s.technologies||[]}}catch(t){return k(t),null}}},IW=new hs});import EE from"node:path";async function ya(r){let e=await I.getProjectId(r),t={rotated:[],totalSize:0,freedSpace:0},n=[P.getFilePath(e,"memory","context.jsonl"),P.getFilePath(e,"progress","shipped.md"),P.getFilePath(e,"planning","ideas.md")];for(let s of n)try{let o=await Mt.getFileSizeMB(s);o>0&&(t.totalSize+=o,await Mt.rotateJsonLinesIfNeeded(s,10)&&(t.rotated.push(EE.basename(s)),t.freedSpace+=o))}catch(o){k(o)||console.error(`Cleanup warning for ${s}: ${w(o)}`)}return{success:!0,results:t}}async function wa(r){let e=await I.getProjectId(r),t=P.getFilePath(e,"memory","context.jsonl");await Mt.rotateJsonLinesIfNeeded(t,10)}async function Xu(r={},e=process.cwd()){try{if(r.memory===!0||r.type==="memory"){h.spin("cleaning memory...");let i=await ya(e);return h.done("memory cleaned"),i}h.spin("cleaning up...");let n=await I.getProjectId(e);if(!n)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let s=[],o=P.getFilePath(n,"memory","context.jsonl");try{let i=await Mt.readJsonLines(o);if(i.length>100){let a=i.slice(-100);await Mt.writeJsonLines(o,a),s.push(`Memory: ${i.length-100} old entries removed`)}else s.push("Memory: No cleanup needed")}catch(i){k(i)?s.push("Memory: No file found"):s.push(`Memory: Error - ${w(i)}`)}try{let i=await dn.cleanup(n);i.removed>0?s.push(`Ideas: ${i.removed} old archived ideas removed`):s.push("Ideas: No cleanup needed")}catch(i){k(i)?s.push("Ideas: No file found"):s.push(`Ideas: Error - ${w(i)}`)}try{let a=(await ot.getActiveTasks(n)).filter(c=>c.completed).length;a>0?s.push(`Queue: ${a} completed tasks found (not removed - use /p:done to clear)`):s.push("Queue: No completed tasks")}catch(i){k(i)?s.push("Queue: No file found"):s.push(`Queue: Error - ${w(i)}`)}return await wa(e),await at.log(e,"cleanup_performed",{items:s.length,timestamp:U.getTimestamp()}),h.done(`${s.length} items cleaned`),{success:!0,cleaned:s}}catch(t){return h.fail(w(t)),{success:!1,error:w(t)}}}var Yu=y(()=>{"use strict";Fn();sn();M();tt();l(ya,"cleanupMemory");l(wa,"cleanupMemoryInternal");l(Xu,"cleanup")});import cy from"node:path";async function Qu(r=null,e={},t=process.cwd()){try{let n=e.type||"architecture";if(!["architecture","api","component","database","flow"].includes(n))return h.fail(`invalid type: ${n}`),{success:!1,error:"Invalid design type"};let o=r||"system";h.spin(`designing ${n}...`);let i=await I.getProjectId(t),a=cy.join(P.getGlobalProjectPath(i),"planning","designs");await ae.ensureDir(a);let c="";switch(n){case"architecture":c=`# Architecture Design: ${o}
1529
-
1530
- *Use templates/design/architecture.md for full design*
1531
- `;break;case"api":c=`# API Design: ${o}
1532
-
1533
- *Use templates/design/api.md for full design*
1534
- `;break;case"component":c=`# Component Design: ${o}
1535
-
1536
- *Use templates/design/component.md for full design*
1537
- `;break;case"database":c=`# Database Design: ${o}
1538
-
1539
- *Use templates/design/database.md for full design*
1540
- `;break;case"flow":c=`# Flow Design: ${o}
1541
-
1542
- *Use templates/design/flow.md for full design*
1543
- `;break}let u=`${n}-${o.toLowerCase().replace(/\s+/g,"-")}.md`,p=cy.join(a,u);return await ae.writeFile(p,c),await at.log(t,"design_created",{type:n,target:o,timestamp:U.getTimestamp()}),h.done(`${n} design created`),{success:!0,designPath:p,type:n,target:o}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}var Zu=y(()=>{"use strict";Fn();M();tt();l(Qu,"design")});import sr from"node:path";async function ep(r=process.cwd()){try{let e=await I.getProjectId(r);if(!e)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};h.spin("checking for abandoned sessions...");let t=P.getFilePath(e,"progress","sessions/current.json"),n=null;try{let s=await ae.readFile(t);n=JSON.parse(s)}catch(s){if(k(s)||s instanceof SyntaxError)n=null;else throw s}if(!n||!n.task)return h.warn("no abandoned session found"),{success:!0,message:"No abandoned session found"};if(console.log(`
1544
- Found abandoned session:
1545
- `),console.log(` Task: ${n.task}`),n.startedAt){let s=U.calculateDuration(new Date(n.startedAt));console.log(` Started: ${s} ago`)}return n.context&&console.log(` Context: ${n.context.slice(0,100)}...`),console.log(`
1546
- Options:`),console.log(" 1. Use /p:work to resume working"),console.log(" 2. Use /p:done to mark as complete"),console.log(` 3. Delete session file to discard
1547
- `),{success:!0,session:n}}catch(e){return h.fail(w(e)),{success:!1,error:w(e)}}}async function tp(r=process.cwd()){try{h.spin("creating undo point...");let e=await I.getProjectId(r);if(!e)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let t=sr.join(P.getGlobalProjectPath(e),"snapshots");await ae.ensureDir(t);let{execSync:n}=await import("node:child_process");try{if(!n("git status --porcelain",{cwd:r,encoding:"utf-8"}).trim())return h.warn("nothing to undo (no changes)"),{success:!0,message:"No changes to undo"};let i=`prjct-undo-${new Date().toISOString().replace(/[:.]/g,"-")}`;n(`git stash push -m "${i}"`,{cwd:r,encoding:"utf-8"});let a=sr.join(t,"history.json"),c={snapshots:[],current:-1};try{let u=await ae.readFile(a);c=JSON.parse(u)}catch(u){if(!k(u)&&!(u instanceof SyntaxError))throw u}return c.snapshots.push({id:i,timestamp:new Date().toISOString(),message:i}),c.current=c.snapshots.length-1,await ae.writeFile(a,JSON.stringify(c,null,2)),await at.log(r,"undo_performed",{snapshotId:i,timestamp:U.getTimestamp()}),h.done("changes stashed (use /p:redo to restore)"),{success:!0,snapshotId:i}}catch(s){return h.failWithHint("GIT_OPERATION_FAILED"),{success:!1,error:w(s)}}}catch(e){return h.fail(w(e)),{success:!1,error:w(e)}}}async function np(r=process.cwd()){try{h.spin("restoring changes...");let e=await I.getProjectId(r);if(!e)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let t=sr.join(P.getGlobalProjectPath(e),"snapshots"),n=sr.join(t,"history.json"),s;try{let i=await ae.readFile(n);s=JSON.parse(i)}catch(i){if(k(i)||i instanceof SyntaxError)return h.warn("no undo history found"),{success:!1,message:"No undo history found"};throw i}if(s.snapshots.length===0)return h.warn("nothing to redo"),{success:!1,message:"Nothing to redo"};let{execSync:o}=await import("node:child_process");try{let i=o("git stash list",{cwd:r,encoding:"utf-8"}).trim();return i?i.split(`
1548
- `).find(c=>c.includes("prjct-undo-"))?(o("git stash pop",{cwd:r,encoding:"utf-8"}),s.snapshots.pop(),s.current=Math.max(0,s.current-1),await ae.writeFile(n,JSON.stringify(s,null,2)),await at.log(r,"redo_performed",{timestamp:U.getTimestamp()}),h.done("changes restored"),{success:!0}):(h.warn("no prjct undo point found"),{success:!1,message:"No prjct undo point found"}):(h.warn("no stashed changes"),{success:!1,message:"No stashed changes found"})}catch(i){return h.failWithHint("GIT_OPERATION_FAILED"),{success:!1,error:w(i)}}}catch(e){return h.fail(w(e)),{success:!1,error:w(e)}}}async function sp(r=process.cwd()){try{let e=await I.getProjectId(r);if(!e)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let t=sr.join(P.getGlobalProjectPath(e),"snapshots"),n=sr.join(t,"history.json"),s;try{let o=await ae.readFile(n);s=JSON.parse(o)}catch(o){if(k(o)||o instanceof SyntaxError)return console.log(`
1549
- SNAPSHOT HISTORY
1550
- `),console.log("=".repeat(50)),console.log(" No snapshots yet."),console.log(` Use /p:undo to create a snapshot.
1551
- `),{success:!0,snapshots:[]};throw o}return console.log(`
1552
- SNAPSHOT HISTORY
1553
- `),console.log("=".repeat(50)),s.snapshots.length===0?(console.log(" No snapshots yet."),console.log(` Use /p:undo to create a snapshot.
1554
- `)):(s.snapshots.forEach((o,i)=>{let a=i===s.current?">":" ",c=new Date(o.timestamp).toLocaleString();console.log(` ${a} ${i+1}. ${c}`)}),console.log(""),console.log(` ${s.snapshots.length} snapshot(s) available`),console.log(` Use /p:redo to restore the latest
1555
- `)),console.log(`${"=".repeat(50)}
1556
- `),{success:!0,snapshots:s.snapshots,current:s.current}}catch(e){return h.fail(w(e)),{success:!1,error:w(e)}}}var rp=y(()=>{"use strict";Fn();M();tt();l(ep,"recover");l(tp,"undo");l(np,"redo");l(sp,"history")});var rr,op=y(()=>{"use strict";tt();Yu();Zu();rp();Yu();Zu();rp();rr=class extends ve{static{l(this,"MaintenanceCommands")}_cleanupMemory=ya;_cleanupMemoryInternal=wa;async cleanup(e={},t=process.cwd()){let n=await this.ensureProjectInit(t);return n.success?Xu(e,t):n}async design(e=null,t={},n=process.cwd()){let s=await this.ensureProjectInit(n);return s.success?Qu(e,t,n):s}async recover(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?ep(e):t}async undo(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?tp(e):t}async redo(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?np(e):t}async history(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?sp(e):t}}});import xe from"chalk";function ka(r,e,t){return t==="below"?r<=e?xe.green("\u2713"):xe.yellow("\u26A0"):r>=e?xe.green("\u2713"):xe.yellow("\u26A0")}var _n,or,ip=y(()=>{"use strict";Bo();M();tt();_n={startup:{max:500,unit:"ms"},heapMB:{max:80,unit:"MB"},contextRate:{min:100,unit:"%"},handoffRate:{min:100,unit:"%"}};l(ka,"statusIcon");or=class extends ve{static{l(this,"PerformanceCommands")}async perf(e="7",t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await I.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=parseInt(e,10)||7,i=await qn.getReport(s,o);if(!(i.startup||i.memory||i.contextCorrectness||i.subtaskHandoff||i.commandDurations))return console.log(`
1557
- ${xe.dim("No performance data yet.")}`),console.log(`${xe.dim("Metrics are collected automatically as you use the CLI.")}
1558
- `),{success:!0,message:"No data"};if(console.log(`
1559
- ${xe.cyan("Performance Report")} ${xe.dim(`(last ${o} days)`)}`),console.log("\u2550".repeat(55)),i.startup){let c=ka(i.startup.avg,_n.startup.max,"below");console.log(` Startup: avg ${xe.bold(`${i.startup.avg}ms`)} ${xe.dim(`(min ${i.startup.min}, max ${i.startup.max}, n=${i.startup.count})`)} ${c} ${xe.dim(`target: <${_n.startup.max}ms`)}`)}if(i.memory){let c=ka(i.memory.peakHeapMB,_n.heapMB.max,"below");console.log(` Memory: avg ${xe.bold(`${i.memory.avgHeapMB}MB`)} heap, peak ${i.memory.peakHeapMB}MB, rss ${i.memory.avgRssMB}MB ${c} ${xe.dim(`target: <${_n.heapMB.max}MB`)}`)}if(i.contextCorrectness){let c=ka(i.contextCorrectness.rate,_n.contextRate.min,"above");console.log(` Context: ${xe.bold(`${i.contextCorrectness.rate}%`)} tasks received sync ${xe.dim(`(${i.contextCorrectness.receivedSync}/${i.contextCorrectness.total})`)} ${c} ${xe.dim(`target: ${_n.contextRate.min}%`)}`)}if(i.subtaskHandoff){let c=ka(i.subtaskHandoff.rate,_n.handoffRate.min,"above");console.log(` Handoff: ${xe.bold(`${i.subtaskHandoff.rate}%`)} subtasks with output ${xe.dim(`(${i.subtaskHandoff.outputPopulated}/${i.subtaskHandoff.total})`)} ${c} ${xe.dim(`target: ${_n.handoffRate.min}%`)}`)}if(i.commandDurations&&Object.keys(i.commandDurations).length>0){console.log(`
1560
- ${xe.dim("Command Durations:")}`);for(let[c,u]of Object.entries(i.commandDurations))console.log(` ${c.padEnd(12)} avg ${xe.bold(`${u.avg}ms`)} ${xe.dim(`(min ${u.min}, max ${u.max}, n=${u.count})`)}`)}return console.log("\u2550".repeat(55)),console.log(""),{success:!0}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}}});import ap from"node:fs/promises";import jE from"node:path";import oe from"chalk";var ir,cp=y(()=>{"use strict";En();ee();M();me();st();tt();ir=class extends ve{static{l(this,"SetupCommands")}async start(){let t=await(He(),bt(mt)).getActiveProvider();if(console.log(`\u{1F680} Setting up prjct for ${t.displayName}...
1561
- `),!(await be.checkInstallation()).claudeDetected)return{success:!1,message:`\u274C ${t.displayName} not detected.
1562
-
1563
- Please install it first:
1564
- - ${t.displayName}: ${t.docsUrl}`};console.log("\u{1F4E6} Installing /p:* commands...");let s=await be.installCommands();if(!s.success)return{success:!1,message:`\u274C Installation failed: ${s.error}`};if(console.log(`
1565
- \u2705 Installed ${s.installed?.length??0} commands to:
1566
- ${P.getDisplayPath(s.path||"")}`),(s.errors?.length??0)>0){console.log(`
1567
- \u26A0\uFE0F ${s.errors?.length??0} errors:`);for(let o of s.errors??[])console.log(` - ${o.file}: ${o.error}`)}return console.log(`
1568
- \u{1F389} Setup complete!`),console.log(`
1569
- Next steps:`),console.log(` 1. Open ${t.displayName}`),console.log(" 2. Navigate to your project"),console.log(" 3. Run: /p:init"),{success:!0,message:""}}async setup(e={}){console.log(`\u{1F527} Reconfiguring prjct...
1570
- `),e.force&&(console.log("\u{1F5D1}\uFE0F Removing existing installation..."),await be.uninstallCommands()),console.log("\u{1F4E6} Installing /p:* commands...");let t=await be.updateCommands();if(!t.success)return{success:!1,message:`\u274C Setup failed: ${t.error}`};if(console.log(`
1571
- \u2705 Installed ${t.installed?.length??0} commands`),(t.errors?.length??0)>0){console.log(`
1572
- \u26A0\uFE0F ${t.errors?.length??0} errors:`);for(let a of t.errors??[])console.log(` - ${a.file}: ${a.error}`)}console.log(`
1573
- \u{1F4DD} Installing global configuration...`);let n=await be.installGlobalConfig(),s=n.path?P.getDisplayPath(n.path):"global config";if(n.success?n.action==="created"?console.log(`\u2705 Created ${s}`):n.action==="updated"?console.log(`\u2705 Updated ${s}`):n.action==="appended"&&console.log(`\u2705 Added prjct config to ${s}`):console.log(`\u26A0\uFE0F ${n.error}`),(await(He(),bt(mt)).getActiveProvider()).name==="claude"){console.log(`
1574
- \u26A1 Installing status line...`);let a=await this.installStatusLine();a.success?console.log("\u2705 Status line configured"):console.log(`\u26A0\uFE0F ${a.error}`)}return console.log(`
1575
- \u{1F389} Setup complete!
1576
- `),this.showAsciiArt(),{success:!0,message:""}}async installStatusLine(){try{let e=P.getClaudeDir(),t=P.getClaudeSettingsPath(),n=jE.join(e,"prjct-statusline.sh"),s=`#!/bin/bash
1577
- # prjct Status Line for Claude Code
1578
- # Shows version update notifications and current task
1579
-
1580
- # Current CLI version (embedded at install time)
1581
- CLI_VERSION="${se}"
1582
-
1583
- # Read JSON context from stdin (provided by Claude Code)
1584
- read -r json
1585
-
1586
- # Extract cwd from JSON
1587
- CWD=$(echo "$json" | grep -o '"cwd"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"cwd"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/')
1588
-
1589
- # Check if this is a prjct project
1590
- CONFIG="$CWD/.prjct/prjct.config.json"
1591
- if [[ -f "$CONFIG" ]]; then
1592
- # Extract projectId
1593
- PROJECT_ID=$(grep -o '"projectId"[[:space:]]*:[[:space:]]*"[^"]*"' "$CONFIG" | sed 's/.*"projectId"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/')
1594
-
1595
- if [[ -n "$PROJECT_ID" ]]; then
1596
- PROJECT_JSON="$HOME/.prjct-cli/projects/$PROJECT_ID/project.json"
1597
-
1598
- # Check version mismatch
1599
- if [[ -f "$PROJECT_JSON" ]]; then
1600
- PROJECT_VERSION=$(grep -o '"cliVersion"[[:space:]]*:[[:space:]]*"[^"]*"' "$PROJECT_JSON" | sed 's/.*"cliVersion"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/')
1601
-
1602
- # If no cliVersion or different version, show update notice
1603
- if [[ -z "$PROJECT_VERSION" ]] || [[ "$PROJECT_VERSION" != "$CLI_VERSION" ]]; then
1604
- echo "\u26A0\uFE0F prjct v$CLI_VERSION available! Run /p:sync"
1605
- exit 0
1606
- fi
1607
- else
1608
- # No project.json means project needs sync
1609
- echo "\u26A0\uFE0F prjct v$CLI_VERSION available! Run /p:sync"
1610
- exit 0
1611
- fi
1612
-
1613
- # Show current task if exists
1614
- STATE="$HOME/.prjct-cli/projects/$PROJECT_ID/storage/state.json"
1615
- if [[ -f "$STATE" ]]; then
1616
- TASK=$(grep -o '"description"[[:space:]]*:[[:space:]]*"[^"]*"' "$STATE" | head -1 | sed 's/.*"description"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/')
1617
- STATUS=$(grep -o '"status"[[:space:]]*:[[:space:]]*"[^"]*"' "$STATE" | head -1 | sed 's/.*"status"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/')
1618
-
1619
- if [[ -n "$TASK" ]] && [[ "$STATUS" == "active" ]]; then
1620
- # Truncate task to 40 chars
1621
- TASK_SHORT="\${TASK:0:40}"
1622
- [[ \${#TASK} -gt 40 ]] && TASK_SHORT="$TASK_SHORT..."
1623
- echo "\u{1F3AF} $TASK_SHORT"
1624
- exit 0
1625
- fi
1626
- fi
1627
- fi
1628
- fi
1629
-
1630
- # Default: show prjct branding
1631
- echo "\u26A1 prjct"
1632
- `;await ap.writeFile(n,s,{mode:493});let o={};if(await C(t))try{o=JSON.parse(await ap.readFile(t,"utf8"))}catch{}return o.statusLine={type:"command",command:n},await ap.writeFile(t,JSON.stringify(o,null,2)),{success:!0}}catch(e){return{success:!1,error:w(e)}}}showAsciiArt(){console.log(oe.cyan("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")),console.log(""),console.log(oe.bold.cyan(" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")),console.log(oe.bold.cyan(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D")),console.log(oe.bold.cyan(" \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551")),console.log(oe.bold.cyan(" \u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551")),console.log(oe.bold.cyan(" \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551")),console.log(oe.bold.cyan(" \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D")),console.log(""),console.log(` ${oe.bold.cyan("prjct")}${oe.magenta("/")}${oe.green("cli")} ${oe.dim.white(`v${se} installed`)}`),console.log(""),console.log(` ${oe.yellow("\u26A1")} Ship faster with zero friction`),console.log(` ${oe.green("\u{1F4DD}")} From idea to technical tasks in minutes`),console.log(` ${oe.cyan("\u{1F916}")} Perfect context for AI agents`),console.log(""),console.log(oe.cyan("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")),console.log(""),console.log(oe.bold.cyan("\u{1F680} Quick Start")),console.log(oe.dim("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(` ${oe.bold("1.")} Initialize your project:`),console.log(` ${oe.green("cd your-project && prjct init")}`),console.log(""),console.log(` ${oe.bold("2.")} Start your first task:`),console.log(` ${oe.green('prjct task "build auth"')}`),console.log(""),console.log(` ${oe.bold("3.")} Ship & celebrate:`),console.log(` ${oe.green('prjct ship "user login"')}`),console.log(""),console.log(oe.dim("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(` ${oe.dim("Documentation:")} ${oe.cyan("https://prjct.app")}`),console.log(` ${oe.dim("Report issues:")} ${oe.cyan("https://github.com/jlopezlira/prjct-cli/issues")}`),console.log(""),console.log(oe.bold.magenta("Happy shipping! \u{1F680}")),console.log("")}}});import ut from"node:path";async function AE(r,e){let t=e?.packageManager?.trim().toLowerCase();return t?.startsWith("pnpm@")?"pnpm":t?.startsWith("yarn@")?"yarn":t?.startsWith("bun@")?"bun":t?.startsWith("npm@")?"npm":await C(ut.join(r,"pnpm-lock.yaml"))?"pnpm":await C(ut.join(r,"yarn.lock"))?"yarn":await C(ut.join(r,"bun.lockb"))||await C(ut.join(r,"bun.lock"))?"bun":(await C(ut.join(r,"package-lock.json")),"npm")}function ly(r,e){return r==="yarn"?`yarn ${e}`:r==="pnpm"?`pnpm run ${e}`:r==="bun"?`bun run ${e}`:`npm run ${e}`}function IE(r){return r==="yarn"?"yarn test":r==="pnpm"?"pnpm test":r==="bun"?"bun test":"npm test"}async function lp(r){let e=ut.join(r,"package.json"),t=await Un(e,null);if(t){let o=await AE(r,t),i=t.scripts||{},a={stack:"js",packageManager:o};return i.lint&&(a.lint={tool:o,command:ly(o,"lint")}),i.typecheck&&(a.typecheck={tool:o,command:ly(o,"typecheck")}),i.test&&(a.test={tool:o,command:IE(o)}),a}if(await C(ut.join(r,"pytest.ini")))return{stack:"python",test:{tool:"pytest",command:"pytest"}};let n=await ws(ut.join(r,"pyproject.toml"),"");return n.includes("[tool.pytest")||n.includes("pytest")?{stack:"python",test:{tool:"pytest",command:"pytest"}}:await C(ut.join(r,"Cargo.toml"))?{stack:"rust",test:{tool:"cargo",command:"cargo test"}}:await C(ut.join(r,"go.mod"))?{stack:"go",test:{tool:"go",command:"go test ./..."}}:(await ks(r)).some(o=>o.endsWith(".sln")||o.endsWith(".csproj")||o.endsWith(".fsproj"))?{stack:"dotnet",test:{tool:"dotnet",command:"dotnet test"}}:await C(ut.join(r,"pom.xml"))?{stack:"java",test:{tool:"maven",command:"mvn test"}}:await C(ut.join(r,"gradlew"))&&(await C(ut.join(r,"build.gradle"))||await C(ut.join(r,"build.gradle.kts")))?{stack:"java",test:{tool:"gradle",command:"./gradlew test"}}:{stack:"unknown"}}var uy=y(()=>{"use strict";me();l(AE,"detectPackageManager");l(ly,"pmRun");l(IE,"pmTest");l(lp,"detectProjectCommands")});import{exec as DE}from"node:child_process";import{promisify as RE}from"node:util";import zt from"chalk";function yo(r,e){return`workflow:${r}_${e}`}async function py(r,e){let t=yo(e.hook,e.command);switch(e.scope){case"permanent":await Ce.recordDecision(r,t,e.action,"workflow");break;case"session":Sa.set(t,e);break;case"once":ar.set(t,e);break}}async function ME(r,e){let t={};for(let n of["before","after","skip"]){let s=yo(n,e),o=ar.get(s);if(o){n==="skip"?t.skip=o.action==="true":t[n]=o.action;continue}let i=Sa.get(s);if(i){n==="skip"?t.skip=i.action==="true":t[n]=i.action;continue}let a=await Ce.getSmartDecision(r,s);a&&(n==="skip"?t.skip=a==="true":t[n]=a)}return t}async function Nn(r,e,t,n={}){if(n.skipHooks)return{success:!0};let s=await ME(r,t);if(s.skip)return{success:!0,skipped:[t]};let o=s[e];if(!o)return{success:!0};let i=yo(e,t);ar.has(i)&&ar.delete(i),console.log(`
1633
- ${zt.dim(`Running ${e}-${t}: ${o}`)}`);try{let a=Date.now();await $E(o,{timeout:6e4,cwd:n.projectPath||process.cwd(),env:{...process.env}});let c=Date.now()-a,u=c>1e3?`${(c/1e3).toFixed(1)}s`:`${c}ms`;return console.log(`${zt.green("\u2713")} ${zt.dim(`(${u})`)}`),{success:!0}}catch(a){console.log(zt.red("\u2717 failed"));let c=w(a)||"Unknown error";return console.log(zt.dim(c.split(`
1634
- `)[0])),{success:!1,failed:o,output:c}}}async function up(r){let e=[],t=["task","done","ship","sync"],n=["before","after","skip"];for(let s of t)for(let o of n){let i=yo(o,s),a=ar.get(i);if(a){e.push({key:`${o} ${s}`,action:a.action,scope:"once"});continue}let c=Sa.get(i);if(c){e.push({key:`${o} ${s}`,action:c.action,scope:"session"});continue}let u=await Ce.getSmartDecision(r,i);u&&e.push({key:`${o} ${s}`,action:u,scope:"permanent"})}return e}async function dy(r,e,t){let n=yo(e,t);return ar.delete(n),Sa.delete(n),await Ce.recordDecision(r,n,"","workflow:remove"),!0}function my(r){if(r.length===0)return`${zt.dim(Tr.NO_PREFERENCES)}
1635
-
1636
- Set one: "${Tr.SET_EXAMPLE}"`;let e=["","WORKFLOW PREFERENCES","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let t of r){let n=t.scope==="permanent"?zt.green("permanent"):t.scope==="session"?zt.yellow("session"):zt.dim("once");e.push(` [${n}] ${t.key.padEnd(15)} \u2192 ${t.action}`)}return e.push(""),e.push(zt.dim(`Modify: "${Tr.MODIFY_EXAMPLE}"`)),e.push(zt.dim(`Remove: "${Tr.REMOVE_EXAMPLE}"`)),e.join(`
1637
- `)}var $E,Sa,ar,pp=y(()=>{"use strict";Vs();M();Kt();$E=RE(DE),Sa=new Map,ar=new Map;l(yo,"prefKey");l(py,"setWorkflowPreference");l(ME,"getWorkflowPreferences");l(Nn,"runWorkflowHooks");l(up,"listWorkflowPreferences");l(dy,"removeWorkflowPreference");l(my,"formatWorkflowPreferences")});import gy from"node:path";var cr,dp=y(()=>{"use strict";Vs();sn();M();no();uy();pp();tt();cr=class extends ve{static{l(this,"ShippingCommands")}async _runWithExitCode(e){let t=ze.get("Bash"),s=`bash -lc "set +e; ${e.replace(/"/g,'\\"')} 2>&1; echo __EXIT:$?"`,o=await t(s),i=`${o.stdout}
1638
- ${o.stderr}`.trim(),a=i.split(`
1639
- `),c;for(let m=a.length-1;m>=0;m--)if(a[m].startsWith("__EXIT:")){c=a[m];break}let u=c?Number(c.replace("__EXIT:","").trim()):1,p=i.split(`
1640
- `).filter(m=>!m.startsWith("__EXIT:")).join(`
1641
- `).trim();return{exitCode:Number.isFinite(u)?u:1,output:p}}async ship(e,t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;let o=await I.getProjectId(t);if(!o)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let i=e;i||(i=(await le.getCurrentTask(o))?.description||"current work");let a=await Nn(o,"before","ship",{projectPath:t,skipHooks:n.skipHooks});if(!a.success)return{success:!1,error:`Hook failed: ${a.failed}`};h.step(1,5,`Linting ${i}...`);let c=await this._runLint(t);h.step(2,5,"Running tests...");let u=await this._runTests(t);h.step(3,5,"Updating version...");let p=await this._bumpVersion(t);return await this._updateChangelog(i,p,t),h.step(4,5,"Committing..."),(await this._createShipCommit(i,t)).success&&(h.step(5,5,"Pushing..."),await this._gitPush(t)),await es.addShipped(o,{name:i,version:p}),await this.logToMemory(t,"feature_shipped",{feature:i,version:p,timestamp:U.getTimestamp()}),await Ce.learnDecision(o,"commit_footer","prjct","ship"),u.success&&await Ce.recordDecision(o,"test_before_ship","true","ship"),(!c.success||!u.success)&&await Ce.recordWorkflow(o,"quick_ship",{description:"Ship without full checks",feature_type:i.toLowerCase().includes("doc")?"docs":"other"}),await Nn(o,"after","ship",{projectPath:t,skipHooks:n.skipHooks}),h.done(`v${p} shipped`),wt("ship"),{success:!0,feature:i,version:p}}catch(s){return h.fail(w(s)),{success:!1,error:w(s)}}}async _runLint(e){try{let t=await lp(e);if(!t.lint)return{success:!0,message:"skipped (no lint detected)"};let{exitCode:n}=await this._runWithExitCode(t.lint.command);return{success:n===0,message:n===0?"passed":"failed"}}catch(t){return k(t)?{success:!0,message:"skipped (lint not found)"}:{success:!0,message:"skipped (lint detection failed)"}}}async _runTests(e){try{let t=await lp(e);if(!t.test)return{success:!0,message:"skipped (no tests detected)"};let{exitCode:n}=await this._runWithExitCode(t.test.command);return{success:n===0,message:n===0?"passed":"failed"}}catch(t){return k(t)?{success:!0,message:"skipped (tests not found)"}:{success:!0,message:"skipped (test detection failed)"}}}async _bumpVersion(e){try{let t=gy.join(e,"package.json"),n=await ae.readJson(t,{version:"0.0.0"}),s=n?.version||"0.0.0",[o,i,a]=s.split(".").map(Number),c=`${o}.${i}.${a+1}`;return n&&(n.version=c,await ae.writeJson(t,n)),c}catch(t){if(k(t)||t instanceof SyntaxError)return"0.0.1";throw t}}async _updateChangelog(e,t,n){try{let s=gy.join(n,"CHANGELOG.md"),o=await ae.readFile(s,`# Changelog
1642
-
1643
- `),i=`## [${t}] - ${U.formatDate(new Date)}
1644
-
1645
- ### Added
1646
- - ${e}
1647
-
1648
- `,a=o.replace(`# Changelog
1649
-
1650
- `,`# Changelog
1651
-
1652
- ${i}`);await ae.writeFile(s,a)}catch(s){k(s)?console.error(" Warning: CHANGELOG.md not found"):console.error(" Warning: Could not update CHANGELOG")}}async _createShipCommit(e,t){try{await ze.get("Bash")("git add .");let n=`feat: ${e}
1653
-
1654
- Generated with [p/](https://www.prjct.app/)`;return await ze.get("Bash")(`git commit -m "${n.replace(/"/g,'\\"')}"`),{success:!0,message:"Committed"}}catch(n){return k(n)?{success:!1,message:"Git not found"}:{success:!1,message:"No changes to commit"}}}async _gitPush(e){try{return await ze.get("Bash")("git push"),{success:!0,message:"Pushed to remote"}}catch(t){return k(t)?{success:!1,message:"Git not found"}:{success:!1,message:"Push failed (no remote or auth issue)"}}}}});import Te from"chalk";var lr,mp=y(()=>{"use strict";il();Bs();jl();M();ns();tt();lr=class extends ve{static{l(this,"VelocityCommands")}async velocity(e="0",t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await I.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=await this.loadVelocityConfig(t),i=await it.getAll(s);if(i.length===0)return console.log(`
1655
- ${Te.dim("No velocity data yet.")}`),console.log(`${Te.dim("Complete tasks with estimates to build velocity history.")}
1656
- `),{success:!0,message:"No data"};let a=wi(i,o);await El.saveMetrics(s,a),console.log(`
1657
- ${Te.cyan("Sprint Velocity")} ${Te.dim(`(last ${o.windowSize??6} sprints)`)}`),console.log("\u2550".repeat(60));let c=a.sprints.slice(-(o.windowSize??6));for(let m of c){let d=m.estimationAccuracy>=80?Te.green:m.estimationAccuracy>=60?Te.yellow:Te.red;console.log(` Sprint ${String(m.sprintNumber).padStart(2)}: ${Te.bold(`${m.pointsCompleted} pts`)} | ${m.tasksCompleted} tasks | accuracy: ${d(`${m.estimationAccuracy}%`)}`)}console.log("");let u=a.velocityTrend==="improving"?Te.green("\u2191"):a.velocityTrend==="declining"?Te.red("\u2193"):Te.dim("\u2192");if(console.log(` Average: ${Te.bold(`${a.averageVelocity} pts/sprint`)} | Trend: ${u} ${a.velocityTrend}`),console.log(` Estimation accuracy: ${Te.bold(`${a.estimationAccuracy}%`)} ${Te.dim(`(\xB1${o.accuracyTolerance??20}% tolerance)`)}`),a.underEstimated.length>0||a.overEstimated.length>0){console.log(`
1658
- ${Te.dim("Patterns:")}`);for(let m of a.underEstimated)console.log(` ${Te.yellow("\u26A0")} ${m.category} tasks underestimated by avg ${Te.bold(`${m.avgVariance}%`)}`);for(let m of a.overEstimated)console.log(` ${Te.green("\u2713")} ${m.category} tasks estimated within ${Te.bold(`${m.avgVariance}%`)}`)}let p=parseInt(e,10);if(p>0&&a.averageVelocity>0){let m=pg(p,a.averageVelocity,o),d=m.estimatedDate?new Date(m.estimatedDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"unknown";console.log(`
1659
- ${Te.dim("Projection:")}`),console.log(` Backlog: ${Te.bold(`${p} pts`)} remaining`),console.log(` At current velocity: ~${m.sprints} sprints (${m.sprints*(o.sprintLengthDays??7)} days)`),console.log(` Estimated completion: ${Te.bold(d)}`)}return console.log("\u2550".repeat(60)),console.log(""),{success:!0}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}async loadVelocityConfig(e){try{let n=await I.readConfig(e);if(n?.velocity&&typeof n.velocity=="object")return{...Dn,...n.velocity}}catch{}return Dn}}});var FE,OE,hy,ba,fy,yy,wy=y(()=>{"use strict";ns();FE=[1,2,3,5,8,13,21],OE={1:{min:5,max:15,typical:10},2:{min:15,max:30,typical:20},3:{min:30,max:60,typical:45},5:{min:60,max:120,typical:90},8:{min:120,max:240,typical:180},13:{min:240,max:480,typical:360},21:{min:480,max:960,typical:720}},hy=l(r=>FE.includes(r),"isValidPoint"),ba=l(r=>OE[r],"pointsToMinutes"),fy=l(r=>{if(r<60)return`${r}m`;let e=Math.floor(r/60),t=r%60;return t>0?`${e}h ${t}m`:`${e}h`},"formatMinutes"),yy=l(r=>{let e=ba(r);return`${fy(e.min)}\u2013${fy(e.max)}`},"pointsToTimeRange")});function gp(){Ke.clear(),Jt.clear(),ur.clear(),pr.clear()}function fp(){return{issues:Ke.stats(),assignedIssues:Jt.stats(),teams:ur.stats(),projects:pr.stats()}}var Pa,Ke,Jt,ur,pr,hp=y(()=>{"use strict";Zo();Pa=300*1e3,Ke=new Ot({ttl:Pa,maxSize:100}),Jt=new Ot({ttl:Pa,maxSize:10}),ur=new Ot({ttl:Pa,maxSize:5}),pr=new Ot({ttl:Pa,maxSize:5});l(gp,"clearLinearCache");l(fp,"getLinearCacheStats")});import{exec as _E}from"node:child_process";import{promisify as NE}from"node:util";async function Ca(r){if(process.platform!=="darwin")return ky(r);try{let{stdout:e}=await LE(`security find-generic-password -s "${UE}" -a "${r}" -w 2>/dev/null`);return e.trim()||null}catch{return ky(r)}}function ky(r){let t={"linear-api-key":"LINEAR_API_KEY","jira-api-token":"JIRA_API_TOKEN"}[r];return process.env[t]||null}var LE,UE,yp=y(()=>{"use strict";M();LE=NE(_E),UE="prjct-cli";l(Ca,"getCredential");l(ky,"getEnvFallback")});var HE,GE,Sy,va,pt,wp=y(()=>{"use strict";M();yp();HE={backlog:"backlog",unstarted:"todo",started:"in_progress",completed:"done",canceled:"cancelled",cancelled:"cancelled"},GE={0:"none",1:"urgent",2:"high",3:"medium",4:"low"},Sy={none:0,urgent:1,high:2,medium:3,low:4},va=class{static{l(this,"LinearProvider")}name="linear";displayName="Linear";sdk=null;config=null;isConfigured(){return this.sdk!==null&&this.config?.enabled===!0}async initialize(e){this.config=e;let t=e.apiKey||await Ca("linear-api-key");if(!t)throw new Error("LINEAR_API_KEY not configured. Run `p. linear setup` to configure.");let{LinearClient:n}=await import("@linear/sdk");this.sdk=new n({apiKey:t});try{await this.sdk.viewer}catch(s){throw this.sdk=null,new Error(`Linear connection failed: ${w(s)}`)}}async fetchAssignedIssues(e){if(!this.sdk)throw new Error("Linear not initialized");let t=await this.sdk.viewer,n={};e?.includeCompleted||(n.state={type:{nin:["completed","canceled"]}}),this.config?.defaultTeamId&&(n.team={id:{eq:this.config.defaultTeamId}});let s=await t.assignedIssues({first:e?.limit||50,filter:Object.keys(n).length>0?n:void 0});return Promise.all(s.nodes.map(o=>this.mapIssue(o)))}async fetchTeamIssues(e,t){if(!this.sdk)throw new Error("Linear not initialized");let s=await(await this.sdk.team(e)).issues({first:t?.limit||50,filter:t?.includeCompleted?void 0:{state:{type:{nin:["completed","canceled"]}}}});return Promise.all(s.nodes.map(o=>this.mapIssue(o)))}async fetchIssue(e){if(!this.sdk)throw new Error("Linear not initialized");try{if(e.includes("-")&&/^[A-Z]+-\d+$/.test(e)){let n=e.match(/^([A-Z]+)-(\d+)$/);if(!n)return null;let[,s,o]=n,i=parseInt(o,10),c=(await this.sdk.teams({first:50})).nodes.find(p=>p.key===s);if(!c)return null;let u=await c.issues({first:1,filter:{number:{eq:i}}});return u.nodes.length>0?this.mapIssue(u.nodes[0]):null}let t=await this.sdk.issue(e);return this.mapIssue(t)}catch{return null}}async createIssue(e){if(!this.sdk)throw new Error("Linear not initialized");let t=e.teamId||this.config?.defaultTeamId;if(!t)throw new Error("Team ID required for creating issues");let s=await(await this.sdk.createIssue({teamId:t,title:e.title,description:e.description,priority:e.priority?Sy[e.priority]:void 0,projectId:e.projectId||this.config?.defaultProjectId,assigneeId:e.assigneeId,labelIds:e.labels?await this.resolveLabelIds(t,e.labels):void 0})).issue;if(!s)throw new Error("Failed to create issue");return this.mapIssue(s)}async updateIssue(e,t){if(!this.sdk)throw new Error("Linear not initialized");let n=await this.fetchIssue(e);if(!n)throw new Error(`Issue ${e} not found`);let s={};t.title!==void 0&&(s.title=t.title),t.description!==void 0&&(s.description=t.description),t.priority!==void 0&&(s.priority=Sy[t.priority]),t.assigneeId!==void 0&&(s.assigneeId=t.assigneeId),t.stateId!==void 0&&(s.stateId=t.stateId),t.projectId!==void 0&&(s.projectId=t.projectId),t.labels!==void 0&&n.team&&(s.labelIds=await this.resolveLabelIds(n.team.id,t.labels)),await this.sdk.updateIssue(n.id,s);let o=await this.fetchIssue(n.id);if(!o)throw new Error("Failed to fetch updated issue");return o}async markInProgress(e){if(!this.sdk)throw new Error("Linear not initialized");let t=await this.fetchIssue(e);if(!t)throw new Error(`Issue ${e} not found`);let s=await(await this.sdk.issue(t.id)).team;if(!s)throw new Error("Issue has no team");let i=(await s.states()).nodes.find(a=>a.type==="started");i&&await this.sdk.updateIssue(t.id,{stateId:i.id})}async markDone(e){if(!this.sdk)throw new Error("Linear not initialized");let t=await this.fetchIssue(e);if(!t)throw new Error(`Issue ${e} not found`);let s=await(await this.sdk.issue(t.id)).team;if(!s)throw new Error("Issue has no team");let i=(await s.states()).nodes.find(a=>a.type==="completed");i&&await this.sdk.updateIssue(t.id,{stateId:i.id})}async addComment(e,t){if(!this.sdk)throw new Error("Linear not initialized");let n=await this.fetchIssue(e);if(!n)throw new Error(`Issue ${e} not found`);await this.sdk.createComment({issueId:n.id,body:t})}async getTeams(){if(!this.sdk)throw new Error("Linear not initialized");return(await this.sdk.teams({first:50})).nodes.map(t=>({id:t.id,name:t.name,key:t.key}))}async getProjects(){if(!this.sdk)throw new Error("Linear not initialized");return(await this.sdk.projects({first:50})).nodes.map(t=>({id:t.id,name:t.name}))}async mapIssue(e){let t=await e.state,n=await e.assignee,s=await e.team,o=await e.project,i=await e.labels();return{id:e.id,externalId:e.identifier,provider:"linear",title:e.title,description:e.description||void 0,status:HE[t?.type||"backlog"]||"backlog",priority:GE[e.priority]||"none",type:this.inferType(e.title,i.nodes.map(a=>a.name)),assignee:n?{id:n.id,name:n.name,email:n.email}:void 0,labels:i.nodes.map(a=>a.name),team:s?{id:s.id,name:s.name,key:s.key}:void 0,project:o?{id:o.id,name:o.name}:void 0,url:e.url,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),raw:e}}inferType(e,t){let n=e.toLowerCase(),s=t.map(o=>o.toLowerCase());return s.includes("bug")||n.includes("fix")||n.includes("bug")?"bug":s.includes("feature")||n.includes("add")||n.includes("implement")?"feature":s.includes("improvement")||n.includes("improve")||n.includes("enhance")?"improvement":s.includes("chore")||n.includes("chore")||n.includes("deps")?"chore":"task"}async resolveLabelIds(e,t){return this.sdk?(await(await this.sdk.team(e)).labels()).nodes.filter(o=>t.includes(o.name)).map(o=>o.id):[]}},pt=new va});var xa,At,kp=y(()=>{"use strict";hp();wp();xa=class{static{l(this,"LinearService")}initialized=!1;userId=null;isReady(){return this.initialized&&pt.isConfigured()}async initialize(e){this.initialized||(await pt.initialize(e),this.initialized=!0)}async initializeFromApiKey(e,t){let n={enabled:!0,provider:"linear",apiKey:e,defaultTeamId:t,syncOn:{task:!0,done:!0,ship:!0},enrichment:{enabled:!0,updateProvider:!0}};await this.initialize(n)}async fetchAssignedIssues(e){this.ensureInitialized();let t=`assigned:${this.userId||"me"}`,n=Jt.get(t);if(n)return n;let s=await pt.fetchAssignedIssues(e);Jt.set(t,s);for(let o of s)Ke.set(`issue:${o.id}`,o),Ke.set(`issue:${o.externalId}`,o);return s}async fetchTeamIssues(e,t){this.ensureInitialized();let n=`team:${e}`,s=Jt.get(n);if(s)return s;let o=await pt.fetchTeamIssues(e,t);Jt.set(n,o);for(let i of o)Ke.set(`issue:${i.id}`,i),Ke.set(`issue:${i.externalId}`,i);return o}async fetchIssue(e){this.ensureInitialized();let t=`issue:${e}`,n=Ke.get(t);if(n)return n;let s=await pt.fetchIssue(e);return s&&(Ke.set(`issue:${s.id}`,s),Ke.set(`issue:${s.externalId}`,s)),s}async createIssue(e){this.ensureInitialized();let t=await pt.createIssue(e);return Ke.set(`issue:${t.id}`,t),Ke.set(`issue:${t.externalId}`,t),Jt.clear(),t}async updateIssue(e,t){this.ensureInitialized();let n=await pt.updateIssue(e,t);return Ke.set(`issue:${n.id}`,n),Ke.set(`issue:${n.externalId}`,n),n}async markInProgress(e){this.ensureInitialized(),await pt.markInProgress(e),Ke.delete(`issue:${e}`),Jt.clear()}async markDone(e){this.ensureInitialized(),await pt.markDone(e),Ke.delete(`issue:${e}`),Jt.clear()}async addComment(e,t){this.ensureInitialized(),await pt.addComment(e,t)}async getTeams(){this.ensureInitialized();let e=ur.get("teams");if(e)return e;let t=await pt.getTeams();return ur.set("teams",t),t}async getProjects(){this.ensureInitialized();let e=pr.get("projects");if(e)return e;let t=await pt.getProjects();return pr.set("projects",t),t}clearCache(){gp()}getCacheStats(){return fp()}ensureInitialized(){if(!this.initialized)throw new Error("Linear service not initialized. Call linearService.initialize() first or run `p. linear setup`.")}},At=new xa});import{mkdir as by,readFile as zE,writeFile as Py}from"node:fs/promises";import{join as wo}from"node:path";var Cy,Ta,JE,vy=y(()=>{"use strict";qc();Qc();M();me();kp();Cy=1800*1e3,Ta=class{static{l(this,"LinearSync")}async pullAll(e){let t=wo(zr(e),"storage"),n=wo(t,"issues.json");await C(t)||await by(t,{recursive:!0});let s=new Date().toISOString(),o=[];try{let i=await At.fetchAssignedIssues({limit:100}),a={};for(let u of i)try{a[u.externalId]=this.toCachedIssue(u,s)}catch(p){o.push({issueId:u.externalId||u.id,error:w(p)})}return await Py(n,JSON.stringify({provider:"linear",lastSync:s,staleAfter:Cy,issues:a},null,2)),{provider:"linear",fetched:i.length,updated:Object.keys(a).length,errors:o,timestamp:s}}catch(i){return o.push({issueId:"all",error:w(i)}),{provider:"linear",fetched:0,updated:0,errors:o,timestamp:s}}}async getIssue(e,t){let n=await this.loadIssues(e);if(n?.issues[t]){let s=n.issues[t],o=new Date(s.fetchedAt).getTime(),i=Date.now(),a=600*1e3;if(i-o<a)return s}try{let s=await At.fetchIssue(t);if(!s)return null;let o=new Date().toISOString(),i=this.toCachedIssue(s,o);return await this.updateIssueInCache(e,t,i),i}catch{return n?.issues[t]?n.issues[t]:null}}async getIssueLocal(e,t){return(await this.loadIssues(e))?.issues[t]||null}async pushStatus(e,t,n){n==="in_progress"?await At.markInProgress(t):n==="done"&&await At.markDone(t);let s=await this.loadIssues(e);if(s?.issues[t]){let o=n==="done"?"done":"in_progress";s.issues[t].status=o,s.issues[t].fetchedAt=new Date().toISOString(),await this.saveIssues(e,s)}}async isStale(e){let t=await this.loadIssues(e);if(!t||!t.lastSync)return!0;let n=new Date(t.lastSync).getTime(),s=Date.now(),o=t.staleAfter||Cy;return s-n>o}async getSyncStatus(e){let t=await this.loadIssues(e);return t?{hasCache:!0,lastSync:t.lastSync||null,issueCount:Object.keys(t.issues).length,isStale:await this.isStale(e)}:{hasCache:!1,lastSync:null,issueCount:0,isStale:!0}}async listCachedIssues(e){let t=await this.loadIssues(e);return t?Object.values(t.issues):[]}async loadIssues(e){let t=wo(zr(e),"storage","issues.json");if(!await C(t))return null;try{let n=await zE(t,"utf-8");return Mm(JSON.parse(n))}catch{return null}}async saveIssues(e,t){let n=wo(zr(e),"storage"),s=wo(n,"issues.json");await C(n)||await by(n,{recursive:!0}),await Py(s,JSON.stringify(t,null,2))}async updateIssueInCache(e,t,n){let s=await this.loadIssues(e);s||(s=Fm("linear")),s.issues[t]=n,await this.saveIssues(e,s)}toCachedIssue(e,t){return{id:e.id,identifier:e.externalId,title:e.title,description:e.description,status:e.status,priority:e.priority,type:e.type,assignee:e.assignee,labels:e.labels,team:e.team,project:e.project,url:e.url,createdAt:e.createdAt,updatedAt:e.updatedAt,fetchedAt:t}}},JE=new Ta});var xy=y(()=>{"use strict";hp();wp();kp();vy()});import WE from"node:fs/promises";import BE from"node:os";import VE from"node:path";function qE(r){return VE.join(BE.homedir(),".prjct-cli","projects",r,"config","credentials.json")}async function Ea(r){let e=qE(r);if(!await C(e))return{};try{return JSON.parse(await WE.readFile(e,"utf-8"))}catch(t){return console.error("[project-credentials] Failed to read credentials:",w(t)),{}}}async function Sp(r){let e=await Ea(r);return e.linear?.apiKey?e.linear.apiKey:Ca("linear-api-key")}var Ty=y(()=>{"use strict";M();me();yp();l(qE,"getCredentialsPath");l(Ea,"getProjectCredentials");l(Sp,"getLinearApiKey")});function Ey(r){if(r<60)return`${r}m`;let e=Math.floor(r/60),t=r%60;return t>0?`${e}h ${t}m`:`${e}h`}function KE(r){let e=r>=0?"+":"-",t=Math.abs(r);if(t>=60){let n=Math.floor(t/60),s=t%60;return s>0?`${e}${n}h ${s}m`:`${e}${n}h`}return`${e}${t}m`}var dr,bp=y(()=>{"use strict";Zl();ql();wy();xy();_t();sn();M();no();Ty();pp();ns();tt();dr=class extends ve{static{l(this,"WorkflowCommands")}async now(e=null,t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;let o=await I.getProjectId(t);if(!o)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(e){let i=await Nn(o,"before","task",{projectPath:t,skipHooks:n.skipHooks});if(!i.success)return{success:!1,error:`Hook failed: ${i.failed}`};let a=await Oi.execute("task",{task:e},t);if(!a.success)return h.fail(a.error||"Failed to execute task"),{success:!1,error:a.error};let c,u=e;if(/^[A-Z]+-\d+$/.test(e))try{let f=await Ea(o),S=await Sp(o);if(S&&f.linear?.teamId){await At.initializeFromApiKey(S,f.linear.teamId);let E=await At.fetchIssue(e);E&&(c=e,u=`${e}: ${E.title}`,await At.markInProgress(e))}}catch{}await le.startTask(o,{id:ye(),description:u,sessionId:ye(),linearId:c});let m=await Vl.getAvailableAgents(t),d=m.length>0?m.join(", "):"none (run p. sync)",g=a.orchestratorContext?.agents?.length||m.length;return h.done(`${e}`,{agents:g>0?g:void 0}),to("working"),wt("task"),await this.logToMemory(t,"task_started",{task:e,agenticMode:!0,availableAgents:m,orchestratorContext:a.orchestratorContext,timestamp:U.getTimestamp()}),await Nn(o,"after","task",{projectPath:t,skipHooks:n.skipHooks}),{...a,success:!0,task:e,agenticMode:!0,availableAgents:m,fibonacci:{isValidPoint:hy,pointsToMinutes:ba,pointsToTimeRange:yy,storeEstimate:l(async f=>{let S=ba(f);return await le.updateCurrentTask(o,{estimatedPoints:f,estimatedMinutes:S.typical}),S},"storeEstimate")}}}else{let i=await le.getCurrentTask(o);return i?(h.done(`working on: ${i.description}`),{success:!0,task:i.description,currentTask:i}):(h.warn("no active task"),{success:!0,message:"No active task"})}}catch(s){return h.fail(w(s)),{success:!1,error:w(s)}}}async done(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await I.getProjectId(e);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=await le.getCurrentTask(s);if(!o)return h.warn("no active task"),{success:!0,message:"No active task to complete"};let i=await Nn(s,"before","done",{projectPath:e,skipHooks:t.skipHooks});if(!i.success)return{success:!1,error:`Hook failed: ${i.failed}`};let a=o.description,c="",u=0;if(o.startedAt){let f=new Date(o.startedAt);c=U.calculateDuration(f),u=Math.round((Date.now()-f.getTime())/6e4)}let p=o.estimatedMinutes,m=o.estimatedPoints;try{await it.record(s,{sessionId:o.sessionId,command:"done",task:a,startedAt:o.startedAt,completedAt:U.getTimestamp(),estimatedDuration:p?Ey(p):"0m",actualDuration:c||"0m",variance:p?KE(u-p):"+0m",completedAsPlanned:!0,qualityScore:3,tags:[o.linearId].filter(Boolean)})}catch{}let d="";if(m&&p){let f=u-p,S=p>0?Math.round((u-p)/p*100):0,E=f>=0?"+":"";d=` | est: ${m}pt (${Ey(p)}) \u2192 ${E}${S}%`}await le.completeTask(s,t.feedback);let g=o.linearId;if(g)try{let f=await Ea(s),S=await Sp(s);S&&f.linear?.teamId?(await At.initializeFromApiKey(S,f.linear.teamId),await At.markDone(g),h.done(`${a}${c?` (${c}${d})`:""} \u2192 Linear \u2713`)):h.done(`${a}${c?` (${c}${d})`:""}`)}catch{h.done(`${a}${c?` (${c}${d})`:""}`)}else h.done(`${a}${c?` (${c}${d})`:""}`);return to("completed"),wt("done"),await this.logToMemory(e,"task_completed",{task:a,duration:c,estimatedPoints:m,estimatedMinutes:p,actualMinutes:u,timestamp:U.getTimestamp()}),await Nn(s,"after","done",{projectPath:e,skipHooks:t.skipHooks}),{success:!0,task:a,duration:c}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}async next(e=process.cwd()){try{let t=await this.ensureProjectInit(e);if(!t.success)return t;let n=await I.getProjectId(e);if(!n)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let s=await ot.getActiveTasks(n);return s.length===0?(h.warn("queue empty"),{success:!0,message:"Queue is empty"}):(h.done(`${s.length} task${s.length!==1?"s":""} queued`),wt("next"),{success:!0,tasks:s,count:s.length})}catch(t){return h.fail(w(t)),{success:!1,error:w(t)}}}async pause(e="",t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await I.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=await le.getCurrentTask(s);if(!o)return h.warn("no active task to pause"),{success:!1,message:"No active task to pause"};await le.pauseTask(s,e);let i=o.description.slice(0,40);return h.done(`paused: ${i}${e?` (${e})`:""}`),to("paused"),wt("pause"),await this.logToMemory(t,"task_paused",{task:o.description,reason:e,timestamp:U.getTimestamp()}),{success:!0,task:o.description,reason:e}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}async resume(e=null,t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await I.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=await le.getCurrentTask(s);if(o)return h.warn("already working on a task"),{success:!1,message:`Already working on: ${o.description}`};let i=await le.resumeTask(s);return i?(h.done(`resumed: ${i.description.slice(0,40)}`),to("working"),wt("resume"),await this.logToMemory(t,"task_resumed",{task:i.description,timestamp:U.getTimestamp()}),{success:!0,task:i.description}):(h.warn("no paused task to resume"),{success:!1,message:"No paused task found"})}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}async workflow(e=null,t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await I.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(!e){let o=await up(s);return console.log(my(o)),{success:!0,preferences:o}}return{success:!0,projectId:s,input:e,setWorkflowPreference:l(async o=>{await py(s,{...o,createdAt:U.getTimestamp()})},"setWorkflowPreference"),removeWorkflowPreference:l(async(o,i)=>{await dy(s,o,i)},"removeWorkflowPreference"),listWorkflowPreferences:l(async()=>up(s),"listWorkflowPreferences")}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}};l(Ey,"formatMinutesToDuration");l(KE,"formatVariance")});var mr,p2,jy=y(()=>{"use strict";Qi();qu();Ku();op();ip();Zi();cp();dp();mp();bp();mr=class{static{l(this,"PrjctCommands")}workflow;planning;shipping;analytics;performanceCmds;maintenance;analysis;setupCmds;velocityCmds;contextCmds;agent;agentInfo;currentAuthor;prjctDir;constructor(){this.workflow=new dr,this.planning=new ps,this.shipping=new cr,this.analytics=new nr,this.performanceCmds=new or,this.maintenance=new rr,this.analysis=new ls,this.setupCmds=new ir,this.velocityCmds=new lr,this.contextCmds=new hs,this.agent=null,this.agentInfo=null,this.currentAuthor=null,this.prjctDir=".prjct"}async done(e=process.cwd()){return this.workflow.done(e)}async next(e=process.cwd()){return this.workflow.next(e)}async pause(e="",t=process.cwd()){return this.workflow.pause(e,t)}async resume(e=null,t=process.cwd()){return this.workflow.resume(e,t)}async workflowPrefs(e=null,t=process.cwd()){return this.workflow.workflow(e,t)}async init(e=null,t=process.cwd()){return this.planning.init(e,t)}async bug(e,t=process.cwd()){return this.planning.bug(e,t)}async idea(e,t=process.cwd()){return this.planning.idea(e,t)}async spec(e=null,t=process.cwd()){return this.planning.spec(e,t)}async ship(e,t=process.cwd()){return this.shipping.ship(e,t)}async dash(e="default",t=process.cwd()){return this.analytics.dash(e,t)}async help(e="",t=process.cwd()){return this.analytics.help(e,t)}async perf(e="7",t=process.cwd()){return this.performanceCmds.perf(e,t)}async velocity(e="0",t=process.cwd()){return this.velocityCmds.velocity(e,t)}async cleanup(e={},t=process.cwd()){return this.maintenance.cleanup(e,t)}async design(e=null,t={},n=process.cwd()){return this.maintenance.design(e,t,n)}async recover(e=process.cwd()){return this.maintenance.recover(e)}async undo(e=process.cwd()){return this.maintenance.undo(e)}async redo(e=process.cwd()){return this.maintenance.redo(e)}async history(e=process.cwd()){return this.maintenance.history(e)}async analyze(e={},t=process.cwd()){return this.analysis.analyze(e,t)}async sync(e=process.cwd(),t={}){return this.analysis.sync(e,t)}async stats(e=process.cwd(),t={}){return this.analysis.stats(e,t)}async status(e=process.cwd(),t={}){return this.analysis.status(e,t)}async seal(e=process.cwd(),t={}){return this.analysis.seal(e,t)}async verify(e=process.cwd(),t={}){return this.analysis.verify(e,t)}async context(e=null,t=process.cwd()){return this.contextCmds.context(e,t)}async start(){return this.setupCmds.start()}async setup(e={}){return this.setupCmds.setup(e)}async installStatusLine(){return this.setupCmds.installStatusLine()}showAsciiArt(){this.setupCmds.showAsciiArt()}async initializeAgent(){return this.workflow.initializeAgent()}async ensureProjectInit(e){return this.workflow.ensureProjectInit(e)}async ensureAuthor(){return this.workflow.ensureAuthor()}async getGlobalProjectPath(e){return this.workflow.getGlobalProjectPath(e)}async logToMemory(e,t,n){return this.workflow.logToMemory(e,t,n)}},p2=new mr});function tj(){for(let[r,e]of Object.entries(fo))G.registerCategory(r,e)}function Dy(){if(G.has("work"))return;tj();let r=l(e=>tr.find(t=>t.name===e),"getMeta");G.registerMethod("done",ko,"done",r("done")),G.registerMethod("next",ko,"next",r("next")),G.registerMethod("pause",ko,"pause",r("pause")),G.registerMethod("resume",ko,"resume",r("resume")),G.registerMethod("workflow",ko,"workflow",r("workflow")),G.registerMethod("init",ja,"init",r("init")),G.registerMethod("bug",ja,"bug",r("bug")),G.registerMethod("idea",ja,"idea",r("idea")),G.registerMethod("spec",ja,"spec",r("spec")),G.registerMethod("ship",XE,"ship",r("ship")),G.registerMethod("dash",Ay,"dash",r("dash")),G.registerMethod("help",Ay,"help",r("help")),G.registerMethod("perf",YE,"perf",r("perf")),G.registerMethod("velocity",ZE,"velocity",r("velocity")),G.registerMethod("cleanup",gr,"cleanup",r("cleanup")),G.registerMethod("design",gr,"design",r("design")),G.registerMethod("recover",gr,"recover",r("recover")),G.registerMethod("undo",gr,"undo",r("undo")),G.registerMethod("redo",gr,"redo",r("redo")),G.registerMethod("history",gr,"history",r("history")),G.registerMethod("analyze",fr,"analyze",r("analyze")),G.registerMethod("sync",fr,"sync",r("sync")),G.registerMethod("stats",fr,"stats",r("stats")),G.registerMethod("status",fr,"status",r("status")),G.registerMethod("seal",fr,"seal",r("seal")),G.registerMethod("verify",fr,"verify",r("verify")),G.registerMethod("start",Iy,"start",r("start")),G.registerMethod("setup",Iy,"setup",r("setup")),G.registerMethod("uninstall",ej,"uninstall",r("uninstall")),G.registerMethod("context",QE,"context",r("context"))}var ko,ja,XE,Ay,YE,gr,fr,Iy,QE,ZE,ej,Pp=y(()=>{"use strict";Qi();qu();Vu();Ku();op();ip();Zi();ho();cp();dp();Bu();mp();bp();ko=new dr,ja=new ps,XE=new cr,Ay=new nr,YE=new or,gr=new rr,fr=new ls,Iy=new ir,QE=new hs,ZE=new lr,ej=new go;l(tj,"registerCategories");l(Dy,"registerAllCommands");Dy()});var Ry=y(()=>{"use strict";pc();jy();Pp();ho()});var $y=qy((F2,nj)=>{nj.exports={name:"prjct-cli",version:"1.23.0",description:"Context layer for AI agents. Project context for Claude Code, Gemini CLI, and more.",main:"dist/bin/prjct.mjs",bin:{prjct:"bin/prjct"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"},scripts:{build:"node scripts/build.js","build:node":"node scripts/build.js",release:"node scripts/release.js","release:patch":"node scripts/release.js patch","release:minor":"node scripts/release.js minor","release:major":"node scripts/release.js major",postinstall:"node scripts/postinstall.js",prepare:"lefthook install","update-commands":`bun -e "const installer = require('./core/infrastructure/command-installer'); installer.syncCommands().then(r => console.log('Commands updated:', r)).catch(e => console.error('Error:', e.message))"`,"install-global":"./scripts/install.sh",update:"./scripts/update.sh",test:"bun test","test:watch":"bun test --watch","test:coverage":"bun test --coverage",typecheck:"tsc --noEmit -p core/tsconfig.json","typecheck:watch":"tsc --noEmit -p core/tsconfig.json --watch",validate:"bun scripts/validate-commands.js",lint:"biome lint .","lint:fix":"biome lint --write .","lint:meta":"bun core/cli/lint-meta-commentary.ts",format:"biome format --write .","format:check":"biome format .",check:"biome check .","check:fix":"biome check --write ."},keywords:["claude-code","gemini-cli","ai-agents","context-layer","developer-tools","ai-assistant","productivity","mcp","llm","coding-agents"],author:"prjct.app",license:"MIT",dependencies:{"@hono/node-server":"^1.13.7","@linear/sdk":"^29.0.0",chalk:"^4.1.2",chokidar:"^5.0.0","date-fns":"^4.1.0",glob:"^13.0.1",hono:"^4.11.3","jsonc-parser":"^3.3.1",prompts:"^2.4.2",zod:"^3.24.1"},devDependencies:{"@biomejs/biome":"^2.3.13","@types/bun":"latest","@types/chokidar":"^2.1.7","@types/prompts":"^2.4.9",esbuild:"^0.25.0",lefthook:"^2.1.0",typescript:"^5.9.3"},repository:{type:"git",url:"git+https://github.com/jlopezlira/prjct-cli.git"},bugs:{url:"https://github.com/jlopezlira/prjct-cli/issues"},homepage:"https://prjct.app",packageManager:"bun@1.2.23",engines:{node:">=18.0.0",bun:">=1.0.0"},files:["assets/","bin/prjct","dist/","scripts/postinstall.js","scripts/install.sh","LICENSE","README.md","CHANGELOG.md"],prepublishOnly:"node scripts/build.js",trustedDependencies:["chalk","prompts"]}});var uj={};import My from"node:os";import Aa from"node:path";import Ee from"chalk";async function sj(){let[r,...e]=process.argv.slice(2);if(["-v","--version","version"].includes(r)){let t=await Promise.resolve().then(()=>Ky($y()));await cj(t.version),process.exit(0)}["-h","--help",void 0].includes(r)&&(lj(),process.exit(0)),h.start();try{let t=G.getByName(r);if(!t){let p=oj(r),m=p?`Did you mean 'prjct ${p}'? Run 'prjct --help' for all commands`:"Run 'prjct --help' to see available commands";h.failWithHint(Wn("UNKNOWN_COMMAND",{message:`Unknown command: ${r}`,hint:m})),h.end(),process.exit(1)}if(t.deprecated){let p=t.replacedBy?`Use 'prjct ${t.replacedBy}' instead`:"Run 'prjct --help' to see available commands";h.failWithHint({message:`Command '${r}' is deprecated`,hint:p}),h.end(),process.exit(1)}t.implemented||(h.failWithHint({message:`Command '${r}' is not yet implemented`,hint:"Run 'prjct --help' to see available commands",docs:"https://github.com/jlopezlira/prjct-cli"}),h.end(),process.exit(1));let{parsedArgs:n,options:s}=aj(t,e),o=rj(t,n);o&&(h.failWithHint(o),h.end(),process.exit(1));let i=null,a=Date.now();try{i=await I.getProjectId(process.cwd()),i&&(await Cn.expireIfStale(i),await Cn.touch(i))}catch{}let c=new mr,u;if(r==="design"){let p=n.join(" ");u=await c.design(p,s)}else if(r==="analyze")u=await c.analyze(s);else if(r==="cleanup")u=await c.cleanup(s);else if(r==="setup")u=await c.setup(s);else{let p=n.join(" ")||null,d={done:l(()=>c.done(),"done"),next:l(()=>c.next(),"next"),pause:l(g=>c.pause(g||""),"pause"),resume:l(g=>c.resume(g),"resume"),init:l(g=>c.init(g),"init"),bug:l(g=>c.bug(g||""),"bug"),idea:l(g=>c.idea(g||""),"idea"),spec:l(g=>c.spec(g),"spec"),ship:l(g=>c.ship(g),"ship"),dash:l(g=>c.dash(g||"default"),"dash"),stats:l(()=>c.stats(process.cwd(),{json:s.json===!0,export:s.export===!0}),"stats"),status:l(()=>c.status(process.cwd(),{json:s.json===!0}),"status"),help:l(g=>c.help(g||""),"help"),perf:l(g=>c.perf(g||"7"),"perf"),velocity:l(g=>c.velocity(g||"0"),"velocity"),recover:l(()=>c.recover(),"recover"),undo:l(()=>c.undo(),"undo"),redo:l(()=>c.redo(),"redo"),history:l(()=>c.history(),"history"),sync:l(()=>c.sync(process.cwd(),{aiTools:s.agents?String(s.agents).split(","):void 0,preview:s.preview===!0||s["dry-run"]===!0,yes:s.yes===!0,json:s.json===!0,package:s.package?String(s.package):void 0,full:s.full===!0}),"sync"),seal:l(()=>c.seal(process.cwd(),{json:s.json===!0}),"seal"),verify:l(()=>c.verify(process.cwd(),{json:s.json===!0,semantic:s.semantic===!0}),"verify"),start:l(()=>c.start(),"start"),context:l(g=>c.context(g),"context")}[r];if(d)u=await d(p);else throw new Error(`Command '${r}' has no handler`)}if(i){let p=Date.now()-a;try{await Cn.trackCommand(i,r,p)}catch{}try{await qn.recordTiming(i,"command_duration",p,{command:r});let m=globalThis.__perfStartNs;if(m){let d=Number(process.hrtime.bigint()-m)/1e6;await qn.recordTiming(i,"startup_time",d)}await qn.recordMemory(i,{command:r})}catch{}}u?.message&&console.log(u.message),h.end(),process.exit(u?.success?0:1)}catch(t){console.error("Error:",w(t)),process.env.DEBUG&&console.error(So(t)),h.end(),process.exit(1)}}function rj(r,e){if(!r.params)return null;let t=r.params.match(/<[^>]+>/g);if(!t||t.length===0)return null;if(e.length<t.length){let n=t.map(o=>o.slice(1,-1)).join(", "),s=r.usage.terminal||`prjct ${r.name} ${r.params}`;return Wn("MISSING_PARAM",{message:`Missing required parameter: ${n}`,hint:`Usage: ${s}`})}return null}function oj(r){let e=G.getAll().map(s=>s.name),t=null,n=1/0;for(let s of e){let o=ij(r.toLowerCase(),s.toLowerCase());o<n&&(n=o,t=s)}return n<=2?t:null}function ij(r,e){let t=r.length,n=e.length,s=Array.from({length:t+1},()=>Array(n+1).fill(0));for(let o=0;o<=t;o++)s[o][0]=o;for(let o=0;o<=n;o++)s[0][o]=o;for(let o=1;o<=t;o++)for(let i=1;i<=n;i++)s[o][i]=r[o-1]===e[i-1]?s[o-1][i-1]:1+Math.min(s[o-1][i],s[o][i-1],s[o-1][i-1]);return s[t][n]}function aj(r,e){let t=[],n={};for(let s=0;s<e.length;s++){let o=e[s];if(o.startsWith("--")){let i=o.slice(2);s+1<e.length&&!e[s+1].startsWith("--")?n[i]=e[++s]:n[i]=!0}else t.push(o)}return{parsedArgs:t,options:n}}async function cj(r){let e=await Pt(),t=Aa.join(My.homedir(),".claude","commands","p.md"),n=Aa.join(My.homedir(),".gemini","commands","p.toml"),[s,o,i,a]=await Promise.all([C(t),C(n),C(Aa.join(process.cwd(),".cursor","commands","sync.md")),C(Aa.join(process.cwd(),".cursor"))]),c=await bs();if(console.log(`
1660
- ${Ee.cyan("p/")} prjct v${r}
1661
- ${Ee.dim("Context layer for AI coding agents")}
1662
-
1663
- ${Ee.dim("Providers:")}`),e.claude.installed){let u=s?Ee.green("\u2713 ready"):Ee.yellow("\u25CF installed"),p=e.claude.version?` (v${e.claude.version})`:"";console.log(` Claude Code ${u}${Ee.dim(p)}`)}else console.log(` Claude Code ${Ee.dim("\u25CB not installed")}`);if(e.gemini.installed){let u=o?Ee.green("\u2713 ready"):Ee.yellow("\u25CF installed"),p=e.gemini.version?` (v${e.gemini.version})`:"";console.log(` Gemini CLI ${u}${Ee.dim(p)}`)}else console.log(` Gemini CLI ${Ee.dim("\u25CB not installed")}`);if(c.installed){let u=c.skillInstalled?Ee.green("\u2713 ready"):Ee.yellow("\u25CF detected"),p=c.skillInstalled?"":` ${Ee.dim("(run prjct start)")}`;console.log(` Antigravity ${u}${p}`)}else console.log(` Antigravity ${Ee.dim("\u25CB not installed")}`);console.log(i?` Cursor IDE ${Ee.green("\u2713 ready")} ${Ee.dim("(use /sync, /task)")}`:a?` Cursor IDE ${Ee.yellow("\u25CF detected")} ${Ee.dim("(run prjct init)")}`:` Cursor IDE ${Ee.dim("\u25CB no .cursor/ folder")}`),console.log(`
1664
- ${Ee.dim("Run 'prjct start' for Claude/Gemini, 'prjct init' for Cursor")}
1665
- ${Ee.cyan("https://prjct.app")}
1666
- `)}function lj(){console.log(`
1667
- prjct - Context layer for AI coding agents
1668
- Works with Claude Code, Gemini CLI, Antigravity, Cursor IDE, and more.
1669
-
1670
- QUICK START
1671
- -----------
1672
- Claude/Gemini:
1673
- 1. prjct start Configure your AI provider
1674
- 2. cd my-project && prjct init
1675
- 3. Open in Claude Code or Gemini CLI
1676
- 4. Type: p. sync Analyze project
1677
-
1678
- Cursor IDE:
1679
- 1. cd my-project && prjct init
1680
- 2. Open in Cursor
1681
- 3. Type: /sync Analyze project
1682
-
1683
- COMMANDS (inside your AI agent)
1684
- -------------------------------
1685
- Claude/Gemini Cursor Description
1686
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1687
- p. sync /sync Analyze project
1688
- p. task "desc" /task "desc" Start a task
1689
- p. done /done Complete subtask
1690
- p. ship "name" /ship "name" Ship with PR
1691
-
1692
- TERMINAL COMMANDS (this CLI)
1693
- ----------------------------
1694
- prjct start First-time setup (Claude/Gemini global config)
1695
- prjct init Initialize project (required for Cursor)
1696
- prjct setup Reconfigure installations
1697
- prjct sync Sync project state
1698
- prjct watch Auto-sync on file changes (Ctrl+C to stop)
1699
- prjct hooks Manage git hooks for auto-sync
1700
- prjct doctor Check system health and dependencies
1701
-
1702
- EXAMPLES
1703
- --------
1704
- # Claude Code / Gemini CLI (global setup, then per-project)
1705
- $ prjct start
1706
- $ cd my-project && prjct init
1707
- > p. sync
1708
- > p. task "add user authentication"
1709
-
1710
- # Cursor IDE (per-project only)
1711
- $ cd my-project && prjct init
1712
- > /sync
1713
- > /task "add user authentication"
1714
-
1715
- FLAGS
1716
- -----
1717
- --quiet, -q Suppress all output (only errors to stderr)
1718
- --version, -v Show version
1719
- --help, -h Show this help
1720
-
1721
- MORE INFO
1722
- ---------
1723
- Documentation: https://prjct.app
1724
- GitHub: https://github.com/jlopezlira/prjct-cli
1725
- `)}var Fy=y(()=>{"use strict";Ry();ho();Pp();He();Ye();Bo();zo();M();jr();me();Xt();l(sj,"main");l(rj,"validateCommandParams");l(oj,"findClosestCommand");l(ij,"editDistance");l(aj,"parseCommandArgs");l(cj,"displayVersion");l(lj,"displayHelp");sj().catch(r=>{console.error("Fatal error:",w(r)),process.env.DEBUG&&console.error(So(r)),process.exit(1)})});He();Ye();Va();import vp from"node:os";import It from"node:path";import pe from"chalk";import{Hono as gk}from"hono";import{cors as fk}from"hono/cors";import{logger as hk}from"hono/logger";function Zw(){return typeof globalThis<"u"&&"Bun"in globalThis?"bun":"node"}l(Zw,"detectRuntime");function qa(){return Zw()==="bun"}l(qa,"isBun");ee();M();Gn();import _o from"node:fs/promises";import ft from"node:path";import{Hono as ok}from"hono";import*as Zp from"jsonc-parser";var Rt={state:"storage/state.json",queue:"storage/queue.json",ideas:"storage/ideas.json",shipped:"storage/shipped.json",roadmap:"planning/roadmap.json"};async function Vt(r){try{let e=await _o.readFile(r,"utf-8"),t=[],n=Zp.parse(e,t);return t.length>0?null:n}catch(e){return!k(e)&&!(e instanceof SyntaxError)&&F.error(`JSON read error: ${w(e)}`),null}}l(Vt,"readJsonFile");async function ik(r,e){try{return await _o.mkdir(ft.dirname(r),{recursive:!0}),await _o.writeFile(r,`${JSON.stringify(e,null,2)}
1726
- `,"utf-8"),!0}catch(t){return F.error(`JSON write error: ${w(t)}`),!1}}l(ik,"writeJsonFile");function ak(r){return P.getGlobalProjectPath(r)}l(ak,"getProjectDataPath");function ed(r,e){let t=new ok,n=ak(r);return t.get("/state",async s=>{let o=await Vt(ft.join(n,Rt.state));return o?s.json(o):s.json({currentTask:null,lastUpdated:""})}),t.get("/queue",async s=>{let o=await Vt(ft.join(n,Rt.queue));return o?s.json(o):s.json({tasks:[],lastUpdated:""})}),t.get("/ideas",async s=>{let o=await Vt(ft.join(n,Rt.ideas));return o?s.json(o):s.json({ideas:[],lastUpdated:""})}),t.get("/roadmap",async s=>{let o=await Vt(ft.join(n,Rt.roadmap));return o?s.json(o):s.json({features:[],backlog:[],lastUpdated:""})}),t.get("/shipped",async s=>{let o=await Vt(ft.join(n,Rt.shipped));return o?s.json(o):s.json({items:[],lastUpdated:""})}),t.get("/dashboard",async s=>{let[o,i,a,c,u]=await Promise.all([Vt(ft.join(n,Rt.state)),Vt(ft.join(n,Rt.queue)),Vt(ft.join(n,Rt.ideas)),Vt(ft.join(n,Rt.roadmap)),Vt(ft.join(n,Rt.shipped))]);return s.json({projectId:r,state:o||{currentTask:null,lastUpdated:""},queue:i||{tasks:[],lastUpdated:""},ideas:a||{ideas:[],lastUpdated:""},roadmap:c||{features:[],backlog:[],lastUpdated:""},shipped:u||{items:[],lastUpdated:""},timestamp:new Date().toISOString()})}),t.post("/state",async s=>{try{let o=await s.req.json(),i=ft.join(n,Rt.state);return await ik(i,o)?s.json({success:!0}):s.json({success:!1,error:"Failed to write"},500)}catch(o){return s.json({success:!1,error:String(o)},400)}}),t.get("/context/:name",async s=>{let o=s.req.param("name");if(!["now","next","ideas","shipped"].includes(o))return s.json({error:"Invalid context file"},400);try{let a=ft.join(n,"context",`${o}.md`),c=await _o.readFile(a,"utf-8");return s.text(c,200,{"Content-Type":"text/markdown"})}catch(a){return k(a)||F.error(`Context read error: ${w(a)}`),s.text("",200,{"Content-Type":"text/markdown"})}}),t}l(ed,"createRoutes");ee();M();import cn from"node:fs/promises";import fe from"node:path";import{Hono as ck}from"hono";import*as td from"jsonc-parser";var lk=P.getGlobalBasePath(),zn=fe.join(lk,"projects");async function je(r){try{let e=await cn.readFile(r,"utf-8"),t=[],n=td.parse(e,t);return t.length>0?null:n}catch(e){if(k(e))return null;throw e}}l(je,"readJsonFile");async function vr(r,e){try{return await cn.mkdir(fe.dirname(r),{recursive:!0}),await cn.writeFile(r,`${JSON.stringify(e,null,2)}
1727
- `,"utf-8"),!0}catch(t){if(k(t))return!1;throw t}}l(vr,"writeJsonFile");function qt(r){return fe.join(zn,r)}l(qt,"getProjectPath");async function No(r){let e=fe.join(qt(r),"project.json");return await je(e)}l(No,"getProjectConfig");async function Ka(r){if(!r)return"";let e=new Date(r),n=new Date().getTime()-e.getTime(),s=Math.floor(n/(1e3*60*60)),o=Math.floor(n%(1e3*60*60)/(1e3*60));return s>0?`${s}h ${o}m`:`${o}m`}l(Ka,"calculateDuration");function nd(){let r=new ck;return r.get("/projects",async e=>{try{await cn.mkdir(zn,{recursive:!0});let n=(await cn.readdir(zn,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name),s=await Promise.all(n.map(async o=>{let i=qt(o),a=await No(o),c=await je(fe.join(i,"storage/state.json")),u=await je(fe.join(i,"storage/queue.json")),p=await je(fe.join(i,"storage/ideas.json")),m=await je(fe.join(i,"storage/shipped.json")),d=c?.currentTask,g=await Ka(d?.startedAt);return{id:o,name:a?.name||o.slice(0,8),path:a?.path||null,currentTask:d?{...d,duration:g}:null,pausedTask:c?.previousTask||null,stats:{queueCount:u?.tasks?.filter(f=>!f.completed)?.length||0,ideasCount:p?.ideas?.filter(f=>f.status==="pending")?.length||0,shippedCount:m?.shipped?.length||0}}}));return s.sort((o,i)=>o.currentTask&&!i.currentTask?-1:!o.currentTask&&i.currentTask?1:(o.name||"").localeCompare(i.name||"")),e.json({projects:s})}catch(t){return e.json({projects:[],error:String(t)},500)}}),r.get("/projects/:id/full",async e=>{let t=e.req.param("id"),n=qt(t);try{let[s,o,i,a,c,u]=await Promise.all([No(t),je(fe.join(n,"storage/state.json")),je(fe.join(n,"storage/queue.json")),je(fe.join(n,"storage/ideas.json")),je(fe.join(n,"storage/shipped.json")),je(fe.join(n,"planning/roadmap.json"))]);o?.currentTask?.startedAt&&(o.currentTask.duration=await Ka(o.currentTask.startedAt));let p=new Date,m=new Date(p.getFullYear(),p.getMonth(),p.getDate()),d=new Date(m);d.setDate(d.getDate()-d.getDay());let g=i?.tasks?.filter(S=>!S.completed||!S.completedAt?!1:new Date(S.completedAt)>=m)?.length||0,f=i?.tasks?.filter(S=>!S.completed||!S.completedAt?!1:new Date(S.completedAt)>=d)?.length||0;return e.json({id:t,name:s?.name||t,path:s?.path,state:o||{currentTask:null,previousTask:null,lastUpdated:""},queue:i||{tasks:[],lastUpdated:""},ideas:a||{ideas:[],lastUpdated:""},shipped:c||{shipped:[],lastUpdated:""},roadmap:u||{features:[],backlog:[],lastUpdated:""},stats:{tasksToday:g,tasksThisWeek:f,queueCount:i?.tasks?.filter(S=>!S.completed)?.length||0,ideasCount:a?.ideas?.filter(S=>S.status==="pending")?.length||0,shippedCount:c?.shipped?.length||0},timestamp:new Date().toISOString()})}catch(s){return e.json({error:String(s)},500)}}),r.post("/projects/:id/task/complete",async e=>{let t=e.req.param("id"),n=qt(t),s=fe.join(n,"storage/state.json");try{let o=await je(s);if(!o?.currentTask)return e.json({success:!1,error:"No active task"},400);let i=o.currentTask,a={currentTask:null,previousTask:null,lastUpdated:new Date().toISOString()};return await vr(s,a),e.json({success:!0,completedTask:i,message:`Completed: ${i.description}`})}catch(o){return e.json({success:!1,error:String(o)},500)}}),r.post("/projects/:id/task/pause",async e=>{let t=e.req.param("id"),n=qt(t),s=fe.join(n,"storage/state.json");try{let i=(await e.req.json().catch(()=>({}))).reason,a=await je(s);if(!a?.currentTask)return e.json({success:!1,error:"No active task"},400);let c={id:a.currentTask.id,description:a.currentTask.description,status:"paused",startedAt:a.currentTask.startedAt,pausedAt:new Date().toISOString(),pauseReason:i},u={currentTask:null,previousTask:c,lastUpdated:new Date().toISOString()};return await vr(s,u),e.json({success:!0,pausedTask:c,message:`Paused: ${c.description}`})}catch(o){return e.json({success:!1,error:String(o)},500)}}),r.post("/projects/:id/task/resume",async e=>{let t=e.req.param("id"),n=qt(t),s=fe.join(n,"storage/state.json");try{let o=await je(s);if(!o?.previousTask)return e.json({success:!1,error:"No paused task"},400);let i={id:o.previousTask.id,description:o.previousTask.description,status:"active",startedAt:new Date().toISOString(),sessionId:`sess_${Date.now().toString(36)}`},a={currentTask:i,previousTask:null,lastUpdated:new Date().toISOString()};return await vr(s,a),e.json({success:!0,resumedTask:i,message:`Resumed: ${i.description}`})}catch(o){return e.json({success:!1,error:String(o)},500)}}),r.post("/projects/:id/queue/start",async e=>{let t=e.req.param("id"),n=qt(t),s=fe.join(n,"storage/state.json"),o=fe.join(n,"storage/queue.json");try{let i=await e.req.json(),{taskId:a}=i;if(!a)return e.json({success:!1,error:"taskId required"},400);let c=await je(s),u=await je(o);if(c?.currentTask)return e.json({success:!1,error:"Complete or pause current task first"},400);let p=u?.tasks?.find(g=>g.id===a);if(!p)return e.json({success:!1,error:"Task not found in queue"},404);let m={id:p.id,description:p.description,status:"active",startedAt:new Date().toISOString(),sessionId:`sess_${Date.now().toString(36)}`,featureId:p.featureId},d={currentTask:m,previousTask:null,lastUpdated:new Date().toISOString()};return await vr(s,d),e.json({success:!0,task:m,message:`Started: ${m.description}`})}catch(i){return e.json({success:!1,error:String(i)},500)}}),r.post("/projects/:id/ideas",async e=>{let t=e.req.param("id"),n=qt(t),s=fe.join(n,"storage/ideas.json");try{let o=await e.req.json(),{text:i,priority:a="medium",tags:c=[]}=o;if(!i)return e.json({success:!1,error:"text required"},400);let u=await je(s)||{ideas:[],lastUpdated:""},p={id:`idea_${Date.now().toString(36)}`,text:i,status:"pending",priority:a||"medium",tags:c,addedAt:new Date().toISOString()};return u.ideas.unshift(p),u.lastUpdated=new Date().toISOString(),await vr(s,u),e.json({success:!0,idea:p,message:`Captured: ${i.slice(0,50)}...`})}catch(o){return e.json({success:!1,error:String(o)},500)}}),r.get("/stats/global",async e=>{try{await cn.mkdir(zn,{recursive:!0});let n=(await cn.readdir(zn,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name),s=0,o=0,i=0,a=0;for(let c of n){let u=qt(c),p=await je(fe.join(u,"storage/state.json")),m=await je(fe.join(u,"storage/queue.json")),d=await je(fe.join(u,"storage/ideas.json")),g=await je(fe.join(u,"storage/shipped.json"));p?.currentTask&&a++,s+=m?.tasks?.filter(f=>!f.completed)?.length||0,o+=d?.ideas?.filter(f=>f.status==="pending")?.length||0,i+=g?.shipped?.length||0}return e.json({totalProjects:n.length,activeProjects:a,totalTasks:s,totalIdeas:o,totalShipped:i,timestamp:new Date().toISOString()})}catch(t){return e.json({error:String(t)},500)}}),r.get("/status-bar/compact",async e=>{try{let t=e.req.query("cwd");await cn.mkdir(zn,{recursive:!0});let s=(await cn.readdir(zn,{withFileTypes:!0})).filter(p=>p.isDirectory()).map(p=>p.name),o=null;if(t)for(let p of s){let m=await No(p),d=m?.repoPath||m?.path;if(d&&t.startsWith(d)){o=p;break}}let i=null,a=null,c=null,u=o?[o]:s;for(let p of u){let m=qt(p),d=await je(fe.join(m,"storage/state.json")),g=await No(p);if(d?.currentTask){i={id:p,name:g?.name||p,path:g?.repoPath||g?.path},a={...d.currentTask,duration:await Ka(d.currentTask.startedAt)};break}d?.previousTask&&!c&&(i={id:p,name:g?.name||p,path:g?.repoPath||g?.path},c=d.previousTask)}return e.json({hasActiveTask:!!a,hasPausedTask:!!c,activeProject:i,activeTask:a,pausedTask:c,totalProjects:s.length,filtered:!!o,cwd:t||null,timestamp:new Date().toISOString()})}catch(t){return e.json({error:String(t)},500)}}),r}l(nd,"createExtendedRoutes");Xa();import{streamSSE as pk}from"hono/streaming";var sd=3600*1e3,dk=300*1e3,mk=3e4;function rd(){let r=new Map,e=null;function t(o){let i=r.get(o);i&&(clearInterval(i.heartbeatInterval),clearTimeout(i.ttlTimeout),i.abortController.abort(),r.delete(o))}l(t,"removeClient");function n(){e||(e=setInterval(()=>{let o=Date.now();for(let[i,a]of r)o-new Date(a.client.connectedAt).getTime()>sd&&t(i)},dk),e&&typeof e=="object"&&"unref"in e&&e.unref())}l(n,"startReaper");function s(){e&&(clearInterval(e),e=null)}return l(s,"stopReaper"),n(),{handleConnection(o){return pk(o,async i=>{let a=crypto.randomUUID(),c=new Date().toISOString(),u=new AbortController,p={id:a,connectedAt:c,send:l((g,f)=>{i.writeSSE({event:g,data:JSON.stringify(f)})},"send"),close:l(()=>{t(a)},"close")},m=setInterval(async()=>{try{await i.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})})}catch{t(a)}},mk),d=setTimeout(()=>{t(a)},sd);typeof m=="object"&&"unref"in m&&m.unref(),typeof d=="object"&&"unref"in d&&d.unref(),r.set(a,{client:p,heartbeatInterval:m,ttlTimeout:d,abortController:u}),await i.writeSSE({event:"connected",data:JSON.stringify({clientId:a,timestamp:c,message:"Connected to prjct-cli server"})}),i.onAbort(()=>{t(a)}),await new Promise(g=>{u.signal.addEventListener("abort",()=>g(),{once:!0})})})},broadcast(o,i){let a={event:o,data:i,timestamp:new Date().toISOString()};for(let[c,u]of r)try{u.client.send(o,a)}catch{t(c)}},getClientCount(){return r.size},shutdown(){s();for(let o of[...r.keys()])t(o)}}}l(rd,"createSSEManager");function yk(r){let e=new gk,t=rd();r.enableCors!==!1&&e.use("*",fk({origin:"*",allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization"]})),r.enableLogging!==!1&&e.use("*",hk()),e.get("/health",i=>i.json({status:"ok",timestamp:new Date().toISOString()})),e.get("/",i=>i.json({name:"prjct-cli",version:"0.20.0",projectId:r.projectId,endpoints:{health:"/health",state:"/api/state",queue:"/api/queue",ideas:"/api/ideas",roadmap:"/api/roadmap",shipped:"/api/shipped",events:"/api/events",projects:"/api/projects",projectFull:"/api/projects/:id/full",statusBarCompact:"/api/status-bar/compact",globalStats:"/api/stats/global"}}));let n=ed(r.projectId,r.projectPath);e.route("/api",n);let s=nd();e.route("/api",s),e.get("/api/events",i=>t.handleConnection(i));let o=null;return{app:e,async start(){let i=r.port,a=r.host||"0.0.0.0";if(qa())o=Bun.serve({port:i,hostname:a,fetch:e.fetch});else{let{serve:c}=await import("@hono/node-server"),u=c({fetch:e.fetch,port:i,hostname:a});o={stop:l(()=>u.close(),"stop")}}console.log(`\u{1F680} prjct server running at http://${a}:${i}`),console.log(` Project: ${r.projectId}`),console.log(` Runtime: ${qa()?"Bun":"Node.js"}`),console.log(` Dashboard: http://localhost:${i}`)},stop(){t.shutdown(),o&&(o.stop(),o=null,console.log("Server stopped"))},broadcast(i,a){t.broadcast(i,a)}}}l(yk,"createServer");var Ya=3478;async function od(r,e,t=Ya){let n=yk({port:t,projectId:r,projectPath:e});return await n.start(),n}l(od,"startServer");me();$a();st();globalThis.__perfStartNs=process.hrtime.bigint();async function pj(){let r=vp.homedir(),e=await Pt();if(e.claude.installed){let t=It.join(r,".claude","commands","p.md");if(!await C(t))return!1}if(e.gemini.installed){let t=It.join(r,".gemini","commands","p.toml");if(!await C(t))return!1}return!e.claude.installed&&!e.gemini.installed,!0}l(pj,"checkRoutersInstalled");var K=process.argv.slice(2),Oy=K.findIndex(r=>r==="--quiet"||r==="-q"),_y=Oy!==-1;if(_y){K.splice(Oy,1);let{setQuietMode:r}=await Promise.resolve().then(()=>(Xt(),ud));r(!0)}var Ny=K.indexOf("--refresh"),Ly=Ny!==-1;Ly&&(K.splice(Ny,1),await Hp());async function Cp(r){let e=Date.now();try{let t=await I.getProjectId(process.cwd());if(t){let{sessionTracker:n}=await Promise.resolve().then(()=>(zo(),md));return await n.expireIfStale(t),await n.touch(t),()=>{let s=Date.now()-e;n.trackCommand(t,r,s).catch(()=>{}),Promise.resolve().then(()=>(Bo(),wd)).then(({performanceTracker:o})=>{o.recordTiming(t,"command_duration",s,{command:r}).catch(()=>{}),o.recordMemory(t,{command:r}).catch(()=>{})}).catch(()=>{})}}}catch{}return()=>{}}l(Cp,"trackSession");if(K[0]==="start"||K[0]==="setup"){let{runStart:r}=await Promise.resolve().then(()=>(bd(),Sd));await r()}else if(K[0]==="dev")console.log("Dev mode is not yet implemented."),console.log('Use "prjct serve" to start the web server.'),process.exitCode=0;else if(K[0]==="web"||K[0]==="serve")try{let r=process.cwd(),e=await I.getProjectId(r);if(!e)console.error('No prjct project found. Run "prjct init" first.'),process.exitCode=1;else{let t=parseInt(K[1],10)||Ya;await od(e,r,t)}}catch(r){console.error("Server error:",r.message),process.exitCode=1}else if(K[0]==="context"){let r=process.cwd(),e=await I.getProjectId(r);if(!e)console.error('No prjct project found. Run "prjct init" first.'),process.exitCode=1;else{let t=await Cp("context"),{runContextTool:n}=await Promise.resolve().then(()=>(Xd(),Kd)),s=await n(K.slice(1),e,r);console.log(JSON.stringify(s,null,2)),process.exitCode=s.tool==="error"?1:0,t()}}else if(K[0]==="hooks"){let r=await Cp("hooks"),{hooksService:e}=await Promise.resolve().then(()=>(tm(),em)),t=K[1]||"status",n=await e.run(process.cwd(),t);process.exitCode=n,r()}else if(K[0]==="doctor"){let r=await Cp("doctor"),{doctorService:e}=await Promise.resolve().then(()=>(sm(),nm)),t=await e.run(process.cwd());process.exitCode=t,r()}else if(K[0]==="uninstall"){let{uninstall:r}=await Promise.resolve().then(()=>(Bu(),Wh)),e=K.includes("--force")||K.includes("-f"),t=K.includes("--backup")||K.includes("-b"),n=K.includes("--dry-run")||K.includes("-n"),s=K.includes("--keep-package"),o=await r({force:e,backup:t,dryRun:n,keepPackage:s});process.exitCode=o.success?0:1}else if(K[0]==="watch"){let r=process.cwd();if(!await I.getProjectId(r))console.error('No prjct project found. Run "prjct init" first.'),process.exitCode=1;else{let{watchService:t}=await Promise.resolve().then(()=>(Vh(),Bh)),n=K.includes("--verbose")||K.includes("-v"),s=K.find(u=>u.startsWith("--debounce=")),o=s?parseInt(s.split("=")[1],10):void 0,i=K.find(u=>u.startsWith("--interval=")),a=i?parseInt(i.split("=")[1],10)*1e3:void 0,c=await t.start(r,{verbose:n,quiet:_y,debounceMs:o,minIntervalMs:a});c.success||(console.error(c.error),process.exitCode=1)}}else if(K[0]==="linear"){let{spawn:r}=await import("node:child_process"),e=await import("node:fs"),t=process.cwd(),n=await I.getProjectId(t);if(!n)console.error('No prjct project found. Run "prjct init" first.'),process.exitCode=1;else{let s=It.join(__dirname,"..","core","cli","linear.ts"),o=It.join(__dirname,"..","dist","cli","linear.mjs"),i=It.join(__dirname,"..","cli","linear.mjs"),a,c;if(e.existsSync(s)?(a=s,c="bun"):e.existsSync(i)?(a=i,c="node"):e.existsSync(o)?(a=o,c="node"):(console.error('Linear CLI not found. Run "npm run build" first.'),process.exitCode=1,a="",c=""),a){let u=["--project",n,...K.slice(1)];r(c,[a,...u],{stdio:"inherit",cwd:t}).on("close",m=>{process.exitCode=m||0})}}}else if(K[0]==="help"||K[0]==="-h"||K[0]==="--help"){let{getHelp:r}=await Promise.resolve().then(()=>(ty(),ey)),e=K[1];console.log(r(e)),process.exitCode=0}else if(K[0]==="version"||K[0]==="-v"||K[0]==="--version"){let r=await Pt(Ly),e=vp.homedir(),t=process.cwd(),[n,s,o,i,a,c]=await Promise.all([C(It.join(e,".claude","commands","p.md")),C(It.join(e,".gemini","commands","p.toml")),C(It.join(t,".cursor")),C(It.join(t,".cursor","rules","prjct.mdc")),C(It.join(t,".windsurf")),C(It.join(t,".windsurf","rules","prjct.md"))]);if(console.log(`
1728
- ${pe.cyan("p/")} prjct v${se}
1729
- ${pe.dim("Context layer for AI coding agents")}
1730
-
1731
- ${pe.dim("Providers:")}`),r.claude.installed){let u=n?pe.green("\u2713 ready"):pe.yellow("\u25CF installed"),p=r.claude.version?` (v${r.claude.version})`:"";console.log(` Claude Code ${u}${pe.dim(p)}`)}else console.log(` Claude Code ${pe.dim("\u25CB not installed")}`);if(r.gemini.installed){let u=s?pe.green("\u2713 ready"):pe.yellow("\u25CF installed"),p=r.gemini.version?` (v${r.gemini.version})`:"";console.log(` Gemini CLI ${u}${pe.dim(p)}`)}else console.log(` Gemini CLI ${pe.dim("\u25CB not installed")}`);if(o){let u=i?pe.green("\u2713 ready"):pe.yellow("\u25CF detected");console.log(` Cursor IDE ${u}${pe.dim(" (project)")}`)}else console.log(` Cursor IDE ${pe.dim("\u25CB not detected")}`);if(a){let u=c?pe.green("\u2713 ready"):pe.yellow("\u25CF detected");console.log(` Windsurf IDE ${u}${pe.dim(" (project)")}`)}else console.log(` Windsurf IDE ${pe.dim("\u25CB not detected")}`);console.log(`
1732
- ${pe.dim("Run 'prjct start' to configure (CLI providers)")}
1733
- ${pe.dim("Run 'prjct init' to configure (Cursor/Windsurf IDE)")}
1734
- ${pe.cyan("https://prjct.app")}
1735
- `)}else{let r=It.join(vp.homedir(),".prjct-cli","config","installed-editors.json"),e=await pj();if(!await C(r)||!e)console.log(`
1736
- ${pe.cyan.bold(" Welcome to prjct!")}
1737
-
1738
- Run ${pe.bold("prjct start")} to configure your AI providers.
1739
-
1740
- ${pe.dim(`This is a one-time setup that lets you choose between
1741
- Claude Code, Gemini CLI, or both.`)}
1742
- `),process.exitCode=0;else{try{let t=await Fo.getLastVersion();if(t&&t!==se){console.log(`
1743
- ${pe.yellow("\u2139")} Updating prjct v${t} \u2192 v${se}...
1744
- `);let{default:n}=await Promise.resolve().then(()=>(ay(),iy));await n.run()}}catch{}await Promise.resolve().then(()=>(Fy(),uj))}}
1745
- //# sourceMappingURL=prjct.mjs.map
2
+ import{connect}from"node:net";import{existsSync}from"node:fs";import{randomUUID}from"node:crypto";import{homedir}from"node:os";
3
+ const sockPath=homedir()+"/.prjct-cli/run/daemon.sock";
4
+ const args=process.argv.slice(2);
5
+ const cmd=args.find(a=>!a.startsWith("-"));
6
+ const skip=new Set(["daemon","start","setup","dev","web","serve","context","hooks","doctor","uninstall","watch","linear","help","-h","--help","version","-v","--version"]);
7
+ if(cmd&&!skip.has(cmd)&&process.env.PRJCT_NO_DAEMON!=="1"&&existsSync(sockPath)){
8
+ const cArgs=[],cOpts={};
9
+ for(let i=0;i<args.length;i++){const a=args[i];if(a.startsWith("--")){const r=a.slice(2);if(r.includes("=")){const e=r.indexOf("=");cOpts[r.slice(0,e)]=r.slice(e+1)}else if(i+1<args.length&&!args[i+1].startsWith("--")){cOpts[r]=args[++i]}else{cOpts[r]=true}}else if(a.startsWith("-")&&a.length===2){cOpts[a.slice(1)]=true}else if(i>0){cArgs.push(a)}}
10
+ const msg=JSON.stringify({id:randomUUID(),command:cmd,args:cArgs,options:cOpts,cwd:process.cwd()})+"\n";
11
+ const sock=connect(sockPath);let buf="",done=false;
12
+ const t=setTimeout(()=>{if(!done){done=true;sock.destroy();fallback()}},5000);
13
+ sock.on("connect",()=>sock.write(msg));
14
+ sock.on("data",c=>{buf+=c.toString();const n=buf.indexOf("\n");if(n!==-1){const r=JSON.parse(buf.slice(0,n));done=true;clearTimeout(t);sock.end();if(r.stdout)console.log(r.stdout);if(r.stderr)console.error(r.stderr);process.exit(r.exitCode)}});
15
+ sock.on("error",()=>{if(!done){done=true;clearTimeout(t);fallback()}});
16
+ sock.on("close",()=>{if(!done){done=true;clearTimeout(t);fallback()}});
17
+ }else{fallback()}
18
+ async function fallback(){await import("./prjct-core.mjs")}