prjct-cli 1.26.0 → 1.27.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.
- package/CHANGELOG.md +26 -1
- package/dist/bin/prjct-core.mjs +305 -592
- package/dist/cli/linear.mjs +10 -10
- package/dist/daemon/entry.mjs +242 -529
- package/package.json +3 -1
package/dist/daemon/entry.mjs
CHANGED
|
@@ -3,11 +3,11 @@ import { fileURLToPath as __fileURLToPath } from 'url';
|
|
|
3
3
|
import { dirname as __pathDirname } from 'path';
|
|
4
4
|
const __filename = __fileURLToPath(import.meta.url);
|
|
5
5
|
const __dirname = __pathDirname(__filename);
|
|
6
|
-
var
|
|
7
|
-
`,"utf-8")}async function
|
|
8
|
-
`)}async function
|
|
9
|
-
`);await Vl(r,t)}function $f(r){return Hn.extname(r)}function Mf(r){return Hn.basename(r,Hn.extname(r))}var Fe=y(()=>{"use strict";Bl();F();l(pn,"readJson");l(_s,"writeJson");l(Gn,"readFile");l(Vl,"writeFile");l(Pf,"atomicWrite");l(Cf,"appendToFile");l(Ii,"appendLine");l(vf,"prependToFile");l($,"fileExists");l(Ir,"dirExists");l(yt,"ensureDir");l(xf,"deleteFile");l(Tf,"deleteDir");l(zn,"listFiles");l(Ef,"getFileSize");l(Af,"getFileModifiedTime");l(If,"copyFile");l(Df,"moveFile");l(jf,"readLines");l(Rf,"writeLines");l($f,"getFileExtension");l(Mf,"getFileNameWithoutExtension")});import{z as Rt}from"zod";function Jl(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 Uv,Hv,Gv,Ns,zv,Ls=y(()=>{"use strict";Uv=Rt.enum(["opus","sonnet","haiku"]),Hv=Rt.enum(["2.5-pro","2.5-flash","2.0-flash"]),Gv=Rt.string().min(1),Ns=Rt.object({provider:Rt.string(),model:Rt.string(),cliVersion:Rt.string().optional(),recordedAt:Rt.string()}),zv=Rt.object({preferredModel:Rt.string().optional(),lastAnalysisModel:Ns.optional()});l(Jl,"compareSemver")});import Di from"node:fs/promises";import Ff from"node:os";import ql from"node:path";async function Xl(){try{let r=await Di.readFile(Yl,"utf-8"),e=JSON.parse(r);return!e.timestamp||!e.detection||Date.now()-new Date(e.timestamp).getTime()>Of?null:e.detection}catch{return null}}async function Ql(r){let e={timestamp:new Date().toISOString(),detection:r};await Di.mkdir(Kl,{recursive:!0}),await Di.writeFile(Yl,JSON.stringify(e,null,2))}var Kl,Yl,Of,Zl=y(()=>{"use strict";Kl=ql.join(Ff.homedir(),".prjct-cli","cache"),Yl=ql.join(Kl,"providers.json"),Of=600*1e3;l(Xl,"readProviderCache");l(Ql,"writeProviderCache")});var st={};Ln(st,{AntigravityProvider:()=>$i,ClaudeProvider:()=>Dr,CursorProvider:()=>nu,GeminiProvider:()=>Ri,Providers:()=>wt,WindsurfProvider:()=>su,detectAllProviders:()=>Mi,detectAntigravity:()=>Bf,detectCursorProject:()=>ou,detectProvider:()=>ji,detectWindsurfProject:()=>iu,getActiveProvider:()=>Hf,getCommandsDir:()=>Kf,getGlobalContextPath:()=>Vf,getGlobalSettingsPath:()=>Jf,getProjectCommandsPath:()=>Yf,getProviderBranding:()=>jr,getSkillsPath:()=>qf,hasProviderConfig:()=>Gf,needsCursorRouterRegeneration:()=>zf,needsWindsurfRouterRegeneration:()=>Wf,selectProvider:()=>Xf,validateCliVersion:()=>ru});import{exec as _f}from"node:child_process";import Wn from"node:os";import Ue from"node:path";import{promisify as Nf}from"node:util";async function Lf(r){try{let{stdout:e}=await eu(`which ${r}`,{timeout:tu});return e.trim()}catch{return null}}async function Uf(r){try{let{stdout:e}=await eu(`${r} --version`,{timeout:tu}),t=e.match(/\d+\.\d+\.\d+/);return t?t[0]:e.trim()}catch{return null}}async function ji(r){let e=wt[r];if(!e.cliCommand)return{installed:!1};let t=await Lf(e.cliCommand);if(!t)return{installed:!1};let n=await Uf(e.cliCommand),s=ru(r,n||void 0);return{installed:!0,version:n||void 0,path:t,versionWarning:s||void 0}}function ru(r,e){let t=wt[r];return!t.minCliVersion||!e?null:Jl(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 Mi(r=!1){if(!r){let s=await Xl();if(s)return s}let[e,t]=await Promise.all([ji("claude"),ji("gemini")]),n={claude:e,gemini:t};return await Ql(n).catch(()=>{}),n}async function Hf(r){if(r&&wt[r])return wt[r];let e=await Mi();return e.claude.installed&&!e.gemini.installed?Dr:e.gemini.installed&&!e.claude.installed?Ri:Dr}async function Gf(r){let e=wt[r];return e.configDir?$(e.configDir):!1}function jr(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 ou(r){let e=Ue.join(r,".cursor"),t=Ue.join(e,"rules"),n=Ue.join(t,"prjct.mdc"),[s,o]=await Promise.all([$(e),$(n)]);return{detected:s,routerInstalled:o,projectRoot:s?r:void 0}}async function zf(r){let e=await ou(r);return e.detected&&!e.routerInstalled}async function iu(r){let e=Ue.join(r,".windsurf"),t=Ue.join(e,"rules"),n=Ue.join(t,"prjct.md"),[s,o]=await Promise.all([$(e),$(n)]);return{detected:s,routerInstalled:o,projectRoot:s?r:void 0}}async function Wf(r){let e=await iu(r);return e.detected&&!e.routerInstalled}async function Bf(){let r=$i.configDir;if(!r)return{installed:!1,skillInstalled:!1};let e=Ue.join(r,"skills","prjct","SKILL.md"),[t,n]=await Promise.all([$(r),$(e)]);return{installed:t,skillInstalled:n,configPath:t?r:void 0}}function Vf(r){let e=wt[r];return e.configDir?Ue.join(e.configDir,e.contextFile):null}function Jf(r){let e=wt[r];return!e.configDir||!e.settingsFile?null:Ue.join(e.configDir,e.settingsFile)}function qf(r){return wt[r].skillsDir}function Kf(r){return wt[r].commandsDir}function Yf(r,e){let t=wt[r];return Ue.join(e,t.commandsDir)}async function Xf(){let r=await Mi(),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 eu,tu,Dr,Ri,$i,nu,su,wt,Ke=y(()=>{"use strict";Ls();Fe();Zl();eu=Nf(_f),tu=2e3,Dr={name:"claude",displayName:"Claude Code",cliCommand:"claude",configDir:Ue.join(Wn.homedir(),".claude"),contextFile:"CLAUDE.md",skillsDir:Ue.join(Wn.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"},Ri={name:"gemini",displayName:"Gemini CLI",cliCommand:"gemini",configDir:Ue.join(Wn.homedir(),".gemini"),contextFile:"GEMINI.md",skillsDir:Ue.join(Wn.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"},$i={name:"antigravity",displayName:"Google Antigravity",cliCommand:null,configDir:Ue.join(Wn.homedir(),".gemini","antigravity"),contextFile:"ANTIGRAVITY.md",skillsDir:Ue.join(Wn.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},nu={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},su={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},wt={claude:Dr,gemini:Ri,cursor:nu,antigravity:$i,windsurf:su};l(Lf,"whichCommand");l(Uf,"getCliVersion");l(ji,"detectProvider");l(ru,"validateCliVersion");l(Mi,"detectAllProviders");l(Hf,"getActiveProvider");l(Gf,"hasProviderConfig");l(jr,"getProviderBranding");l(ou,"detectCursorProject");l(zf,"needsCursorRouterRegeneration");l(iu,"detectWindsurfProject");l(Wf,"needsWindsurfRouterRegeneration");l(Bf,"detectAntigravity");l(Vf,"getGlobalContextPath");l(Jf,"getGlobalSettingsPath");l(qf,"getSkillsPath");l(Kf,"getCommandsDir");l(Yf,"getProjectCommandsPath");l(Xf,"selectProvider")});import Qf from"node:crypto";import $t from"node:fs/promises";import Fi from"node:os";import _ from"node:path";import{globSync as Zf}from"glob";var Oi,eh,T,re=y(()=>{"use strict";te();Fe();Oi=class{static{l(this,"PathManager")}globalBaseDir;globalProjectsDir;globalConfigDir;constructor(){let e=process.env.PRJCT_CLI_HOME?.trim();this.globalBaseDir=e?_.resolve(e):_.join(Fi.homedir(),".prjct-cli"),this.globalProjectsDir=_.join(this.globalBaseDir,"projects"),this.globalConfigDir=_.join(this.globalBaseDir,"config")}setGlobalBaseDir(e){this.globalBaseDir=_.resolve(e),this.globalProjectsDir=_.join(this.globalBaseDir,"projects"),this.globalConfigDir=_.join(this.globalBaseDir,"config")}generateProjectId(e){return Qf.randomUUID()}getGlobalBasePath(){return this.globalBaseDir}getGlobalProjectPath(e){return _.join(this.globalProjectsDir,e)}getLocalConfigPath(e){return _.join(e,".prjct","prjct.config.json")}getGlobalProjectConfigPath(e){return _.join(this.getGlobalProjectPath(e),"project.json")}getLegacyPrjctPath(e){return _.join(e,".prjct")}async hasLegacyStructure(e){let t=this.getLegacyPrjctPath(e);return await Ir(t)}async hasConfig(e){let t=this.getLocalConfigPath(e);return await $(t)}async ensureGlobalStructure(){await yt(this.globalBaseDir),await yt(this.globalProjectsDir),await yt(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 yt(_.join(t,s));return await yt(_.join(t,"planning","tasks")),await yt(_.join(t,"sessions")),t}getSessionPath(e,t=new Date){let{year:n,month:s,day:o}=Ai(t);return _.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 yt(n),n}async listSessions(e,t=null,n=null){let s=_.join(this.getGlobalProjectPath(e),"sessions"),o=[];try{let i=await $t.readdir(s,{withFileTypes:!0});for(let a of i){if(!a.isDirectory()||t&&a.name!==t.toString())continue;let c=_.join(s,a.name),u=await $t.readdir(c,{withFileTypes:!0});for(let d of u){if(!d.isDirectory()||n&&d.name!==n.toString().padStart(2,"0"))continue;let m=_.join(c,d.name),p=await $t.readdir(m,{withFileTypes:!0});for(let g of p)g.isDirectory()&&o.push({year:a.name,month:d.name,day:g.name,path:_.join(m,g.name),date:new Date(`${a.name}-${d.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 _.join(this.getGlobalProjectPath(e),t,n)}async listProjects(){try{return await this.ensureGlobalStructure(),(await $t.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 Ir(t)}getDisplayPath(e){let t=Fi.homedir();return e.startsWith(t)?e.replace(t,"~"):e}getAuthConfigPath(){return _.join(this.globalConfigDir,"auth.json")}getSyncPendingPath(e){return _.join(this.getGlobalProjectPath(e),"sync","pending.json")}getLastSyncPath(e){return _.join(this.getGlobalProjectPath(e),"sync","last-sync.json")}getRunningStatusPath(){return _.join(this.globalBaseDir,".running")}getDocsPath(){return _.join(this.globalBaseDir,"docs")}async getAgentDir(){return(await(Ke(),ut(st)).getActiveProvider()).configDir}async getAgentSettingsPath(){let e=await(Ke(),ut(st)).getActiveProvider();return(Ke(),ut(st)).getGlobalSettingsPath(e.name)}getClaudeDir(){return _.join(Fi.homedir(),".claude")}getClaudeSettingsPath(){return _.join(this.getClaudeDir(),"settings.json")}getAgentsPath(e){return e?_.join(this.getGlobalProjectPath(e),"agents"):_.join(this.globalBaseDir,"agents")}getStoragePath(e,t){return _.join(this.getGlobalProjectPath(e),"storage",t)}getContextPath(e){return _.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=_.join(e,s.file);if(await $(o)){t.isMonorepo=!0,t.type=s.type;break}}if(!t.isMonorepo){let s=_.join(e,"package.json");if(await $(s))try{let o=await $t.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 $t.readFile(_.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=_.join(e,"package.json"),i=await $t.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=_.join(e,"lerna.json");if(await $(c)){let u=await $t.readFile(c,"utf-8"),d=JSON.parse(u);d.packages&&(s=d.packages)}}}else if(t==="nx")s=["apps/*","libs/*","packages/*"];else if(t==="turborepo"){let o=_.join(e,"package.json"),i=await $t.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=Zf(o,{cwd:e,absolute:!1});for(let a of i){let c=_.join(e,a),u=_.join(c,"package.json");if(await $(u))try{let d=await $t.readFile(u,"utf-8"),m=JSON.parse(d),p=_.join(c,"PRJCT.md");n.push({name:m.name||_.basename(a),path:c,relativePath:a,hasPrjctMd:await $(p)})}catch{}}}}catch{}return n}async findContainingPackage(e,t){if(!t.isMonorepo)return null;let n=_.resolve(e);for(let s of t.packages){let o=_.resolve(s.path);if(n.startsWith(o))return s}return null}async findMonorepoRoot(e){let t=_.resolve(e),n=_.parse(t).root;for(;t!==n;){if((await this.detectMonorepo(t)).isMonorepo)return t;t=_.dirname(t)}return null}},eh=new Oi,T=eh});import Us from"node:fs/promises";import Xt from"node:path";import{z as ee}from"zod";async function oh(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=Xt.join(e,"package.json"),s=await Us.readFile(n,"utf-8"),o=JSON.parse(s),i={...o.dependencies,...o.devDependencies},a=[],c=[];for(let u of r.frameworks){let d=u.toLowerCase();Object.keys(i).some(p=>p.toLowerCase().includes(d))?c.push(u):a.push(u)}return a.length===0?{name:"Framework verification",passed:!0,output:`${c.length} framework(s) verified in dependencies`,durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Frameworks not found in dependencies: ${a.join(", ")}`,durationMs:Date.now()-t}}catch(n){return C(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 ih(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 uh(e),s=new Set(n),o=[],i=[];for(let a of r.languages){let c=rh[a];if(!c)continue;c.some(d=>s.has(d))?o.push(a):i.push(a)}return i.length===0?{name:"Language verification",passed:!0,output:`${o.length} language(s) verified with matching files`,durationMs:Date.now()-t}:{name:"Language verification",passed:!1,error:`Languages without matching files: ${i.join(", ")}`,durationMs:Date.now()-t}}catch(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 ah(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=Xt.join(e,a);try{await Us.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 ch(r,e){let t=Date.now();try{let n=await dh(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 lh(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=Xt.join(e,o.file);try{await Us.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 au(r,e){let t=Date.now(),n=await Promise.all([oh(r,e),ih(r,e),ah(r,e),ch(r,e),lh(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 uh(r){let e=new Set,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function n(s){try{let o=await Us.readdir(s,{withFileTypes:!0});for(let i of o){let a=Xt.join(s,i.name),c=Xt.relative(r,a);if(!t.some(u=>u.test(c))){if(i.isDirectory())await n(a);else if(i.isFile()){let u=Xt.extname(i.name);u&&e.add(u)}}}}catch{}}return l(n,"scanDir"),await n(r),Array.from(e)}async function dh(r){let e=0,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function n(s){try{let o=await Us.readdir(s,{withFileTypes:!0});for(let i of o){let a=Xt.join(s,i.name),c=Xt.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 th,nh,sh,_i,yx,rh,Ni=y(()=>{"use strict";F();Ls();th=ee.enum(["draft","verified","sealed"]),nh=ee.object({name:ee.string(),description:ee.string(),location:ee.string().optional()}),sh=ee.object({issue:ee.string(),file:ee.string(),suggestion:ee.string()}),_i=ee.object({projectId:ee.string(),languages:ee.array(ee.string()),frameworks:ee.array(ee.string()),packageManager:ee.string().optional(),sourceDir:ee.string().optional(),testDir:ee.string().optional(),configFiles:ee.array(ee.string()),fileCount:ee.number(),patterns:ee.array(nh),antiPatterns:ee.array(sh),analyzedAt:ee.string(),modelMetadata:Ns.optional(),status:th.default("draft"),commitHash:ee.string().optional(),signature:ee.string().optional(),sealedAt:ee.string().optional(),verifiedAt:ee.string().optional()}),yx={languages:[],frameworks:[],configFiles:[],fileCount:0,patterns:[],antiPatterns:[],analyzedAt:new Date().toISOString(),status:"draft"},rh={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(oh,"verifyFrameworks");l(ih,"verifyLanguages");l(ah,"verifyPatternLocations");l(ch,"verifyFileCount");l(lh,"verifyAntiPatternFiles");l(au,"semanticVerify");l(uh,"getProjectExtensions");l(dh,"countProjectFiles")});import{z as ie}from"zod";function ph(r){return r instanceof Bn}function K(r){return ph(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var Vn,bx,Px,Cx,vx,xx,Tx,Bn,Rr,$r,Hs,zt=y(()=>{"use strict";Vn={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}},bx=Vn.create("FileError",ie.object({path:ie.string(),operation:ie.enum(["read","write","delete","create","copy"]),reason:ie.string().optional()})),Px=Vn.create("ValidationError",ie.object({field:ie.string(),expected:ie.string(),received:ie.string().optional(),message:ie.string().optional()})),Cx=Vn.create("PermissionError",ie.object({action:ie.string(),resource:ie.string(),reason:ie.string().optional()})),vx=Vn.create("TaskError",ie.object({taskId:ie.string().optional(),operation:ie.enum(["create","update","complete","pause","resume","delete"]),reason:ie.string()})),xx=Vn.create("SessionError",ie.object({sessionId:ie.string().optional(),reason:ie.string()})),Tx=Vn.create("SyncError",ie.object({projectId:ie.string().optional(),operation:ie.enum(["push","pull","auth","connect"]),reason:ie.string()})),Bn=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)}},Rr=class r extends Bn{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")}},$r=class r extends Bn{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")}},Hs=class r extends Bn{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(ph,"isPrjctError");l(K,"getErrorMessage")});import{Database as mh}from"bun:sqlite";import Li from"node:fs";import cu from"node:path";var gh,Mr,M,G,de=y(()=>{"use strict";re();gh=[{version:1,name:"initial-schema",up:l(r=>{r.run(`
|
|
6
|
+
var mr=Object.defineProperty;var Og=Object.getOwnPropertyDescriptor;var Fg=Object.getOwnPropertyNames;var _g=Object.prototype.hasOwnProperty;var l=(r,e)=>mr(r,"name",{value:e,configurable:!0}),Ps=(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')}),hl=r=>e=>{var t=r[e];if(t)return t();throw new Error("Module not found in bundle: "+e)};var w=(r,e)=>()=>(r&&(e=r(r=0)),e);var Mn=(r,e)=>{for(var t in e)mr(r,t,{get:e[t],enumerable:!0})},Ng=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fg(e))!_g.call(r,s)&&s!==t&&mr(r,s,{get:()=>e[s],enumerable:!(n=Og(e,s))||n.enumerable});return r};var at=r=>Ng(mr({},"__esModule",{value:!0}),r);var yl=w(()=>{"use strict"});var gr,wl=w(()=>{"use strict";gr={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 Cs,fr=w(()=>{"use strict";Cs={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 Sl(r){return r instanceof Error&&"code"in r}function C(r){return Sl(r)&&r.code==="ENOENT"}function y(r){return r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var O=w(()=>{"use strict";l(Sl,"isNodeError");l(C,"isNotFoundError");l(y,"getErrorMessage")});var kl=w(()=>{"use strict"});var bl=w(()=>{"use strict";kl()});function hr(r,e=!1){return e||r>=6?"high":r>=3?"medium":"low"}var I,Pl,On=w(()=>{"use strict";I={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"},Pl=["frontend","backend","devops","docs","testing","database","general"];l(hr,"calculateConfidence")});var di=w(()=>{"use strict"});var pi=w(()=>{"use strict";yl();wl();fr();O();bl();On();di()});var H={};Mn(H,{calculateDuration:()=>Yg,formatDate:()=>yr,formatDuration:()=>xs,formatMonth:()=>Gg,getDateKey:()=>Wg,getDateRange:()=>Jg,getDaysAgo:()=>Bt,getDaysFromNow:()=>Vg,getEndOfDay:()=>Qg,getStartOfDay:()=>Xg,getTimestamp:()=>k,getTodayKey:()=>Cl,getYearMonthDay:()=>mi,isToday:()=>qg,isWithinLastDays:()=>Kg,parseDate:()=>Bg,toRelative:()=>Zg});import{formatDistanceToNowStrict as zg}from"date-fns";function yr(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 Gg(r){let e=r.getFullYear(),t=(r.getMonth()+1).toString().padStart(2,"0");return`${e}-${t}`}function Cl(){return yr(new Date)}function Wg(r){return yr(r)}function mi(r){return{year:r.getFullYear().toString(),month:(r.getMonth()+1).toString().padStart(2,"0"),day:r.getDate().toString().padStart(2,"0")}}function Bg(r){return new Date(r)}function k(){return new Date().toISOString()}function Bt(r){let e=new Date;return e.setDate(e.getDate()-r),e}function Vg(r){let e=new Date;return e.setDate(e.getDate()+r),e}function Jg(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 qg(r){return yr(r)===Cl()}function Kg(r,e){let t=Bt(e);return r>=t}function xs(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 Yg(r,e=new Date){let t=e.getTime()-r.getTime();return xs(t)}function Xg(r){let e=new Date(r);return e.setHours(0,0,0,0),e}function Qg(r){let e=new Date(r);return e.setHours(23,59,59,999),e}function Zg(r){let e=typeof r=="string"?new Date(r):r;return zg(e,{addSuffix:!0})}var se=w(()=>{"use strict";l(yr,"formatDate");l(Gg,"formatMonth");l(Cl,"getTodayKey");l(Wg,"getDateKey");l(mi,"getYearMonthDay");l(Bg,"parseDate");l(k,"getTimestamp");l(Bt,"getDaysAgo");l(Vg,"getDaysFromNow");l(Jg,"getDateRange");l(qg,"isToday");l(Kg,"isWithinLastDays");l(xs,"formatDuration");l(Yg,"calculateDuration");l(Xg,"getStartOfDay");l(Qg,"getEndOfDay");l(Zg,"toRelative")});import Tl from"node:fs/promises";async function El(r,e){let t;try{t=await Tl.readFile(r,"utf-8")}catch(o){if(C(o))return null;throw o}let n;try{n=JSON.parse(t)}catch{return await xl(r,t),vl(r,"Malformed JSON"),null}let s=e.safeParse(n);return s.success?n:(await xl(r,t),vl(r,ef(s.error)),null)}async function xl(r,e){let t=`${r}.backup`;try{await Tl.writeFile(t,e,"utf-8")}catch{}}function vl(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 ef(r){return r.issues.slice(0,3).map(e=>`${e.path.join(".")}: ${e.message}`).join("; ")}var Al=w(()=>{"use strict";O();l(El,"safeRead");l(xl,"createBackup");l(vl,"logCorruption");l(ef,"formatZodError")});var te={};Mn(te,{appendLine:()=>gi,appendToFile:()=>nf,atomicWrite:()=>tf,copyFile:()=>lf,deleteDir:()=>of,deleteFile:()=>rf,dirExists:()=>wr,ensureDir:()=>ft,fileExists:()=>M,getFileExtension:()=>mf,getFileModifiedTime:()=>cf,getFileNameWithoutExtension:()=>gf,getFileSize:()=>af,listFiles:()=>Nn,moveFile:()=>uf,prependToFile:()=>sf,readFile:()=>_n,readJson:()=>an,readLines:()=>df,writeFile:()=>Il,writeJson:()=>vs,writeLines:()=>pf});import re from"node:fs/promises";import Fn from"node:path";async function an(r,e=null,t){if(t)return await El(r,t)??e;try{let n=await re.readFile(r,"utf-8");return JSON.parse(n)}catch(n){if(C(n))return e;throw n}}async function vs(r,e,t=2){let n=JSON.stringify(e,null,t);await re.writeFile(r,n,"utf-8")}async function _n(r,e=""){try{return await re.readFile(r,"utf-8")}catch(t){if(C(t))return e;throw t}}async function Il(r,e){let t=Fn.dirname(r);await re.mkdir(t,{recursive:!0}),await re.writeFile(r,e,"utf-8")}async function tf(r,e){let t=Fn.dirname(r);await re.mkdir(t,{recursive:!0});let n=`${r}.${Date.now()}.tmp`;await re.writeFile(n,e,"utf-8"),await re.rename(n,r)}async function nf(r,e){await re.appendFile(r,e,"utf-8")}async function gi(r,e){let t=Fn.dirname(r);await re.mkdir(t,{recursive:!0}),await re.appendFile(r,`${e}
|
|
7
|
+
`,"utf-8")}async function sf(r,e){try{let t=await re.readFile(r,"utf-8");await re.writeFile(r,e+t,"utf-8")}catch(t){if(C(t))await re.writeFile(r,e,"utf-8");else throw t}}async function M(r){try{return await re.access(r),!0}catch(e){if(C(e))return!1;throw e}}async function wr(r){try{return(await re.stat(r)).isDirectory()}catch(e){if(C(e))return!1;throw e}}async function ft(r){await re.mkdir(r,{recursive:!0})}async function rf(r){try{return await re.unlink(r),!0}catch(e){if(C(e))return!1;throw e}}async function of(r){try{return await re.rm(r,{recursive:!0,force:!0}),!0}catch(e){if(C(e))return!1;throw e}}async function Nn(r,e={}){try{let n=await re.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(C(t))return[];throw t}}async function af(r){return(await re.stat(r)).size}async function cf(r){return(await re.stat(r)).mtime}async function lf(r,e){await re.copyFile(r,e)}async function uf(r,e){await re.rename(r,e)}async function df(r){return(await _n(r,"")).split(`
|
|
8
|
+
`)}async function pf(r,e){let t=e.join(`
|
|
9
|
+
`);await Il(r,t)}function mf(r){return Fn.extname(r)}function gf(r){return Fn.basename(r,Fn.extname(r))}var je=w(()=>{"use strict";Al();O();l(an,"readJson");l(vs,"writeJson");l(_n,"readFile");l(Il,"writeFile");l(tf,"atomicWrite");l(nf,"appendToFile");l(gi,"appendLine");l(sf,"prependToFile");l(M,"fileExists");l(wr,"dirExists");l(ft,"ensureDir");l(rf,"deleteFile");l(of,"deleteDir");l(Nn,"listFiles");l(af,"getFileSize");l(cf,"getFileModifiedTime");l(lf,"copyFile");l(uf,"moveFile");l(df,"readLines");l(pf,"writeLines");l(mf,"getFileExtension");l(gf,"getFileNameWithoutExtension")});import{z as It}from"zod";function Dl(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 ux,dx,px,Ts,mx,Es=w(()=>{"use strict";ux=It.enum(["opus","sonnet","haiku"]),dx=It.enum(["2.5-pro","2.5-flash","2.0-flash"]),px=It.string().min(1),Ts=It.object({provider:It.string(),model:It.string(),cliVersion:It.string().optional(),recordedAt:It.string()}),mx=It.object({preferredModel:It.string().optional(),lastAnalysisModel:Ts.optional()});l(Dl,"compareSemver")});import fi from"node:fs/promises";import ff from"node:os";import Rl from"node:path";async function Ml(){try{let r=await fi.readFile($l,"utf-8"),e=JSON.parse(r);return!e.timestamp||!e.detection||Date.now()-new Date(e.timestamp).getTime()>hf?null:e.detection}catch{return null}}async function Ol(r){let e={timestamp:new Date().toISOString(),detection:r};await fi.mkdir(jl,{recursive:!0}),await fi.writeFile($l,JSON.stringify(e,null,2))}var jl,$l,hf,Fl=w(()=>{"use strict";jl=Rl.join(ff.homedir(),".prjct-cli","cache"),$l=Rl.join(jl,"providers.json"),hf=600*1e3;l(Ml,"readProviderCache");l(Ol,"writeProviderCache")});var et={};Mn(et,{AntigravityProvider:()=>wi,ClaudeProvider:()=>Sr,CursorProvider:()=>Ll,GeminiProvider:()=>yi,Providers:()=>ht,WindsurfProvider:()=>Ul,detectAllProviders:()=>Si,detectAntigravity:()=>vf,detectCursorProject:()=>zl,detectProvider:()=>hi,detectWindsurfProject:()=>Gl,getActiveProvider:()=>bf,getCommandsDir:()=>If,getGlobalContextPath:()=>Tf,getGlobalSettingsPath:()=>Ef,getProjectCommandsPath:()=>Df,getProviderBranding:()=>kr,getSkillsPath:()=>Af,hasProviderConfig:()=>Pf,needsCursorRouterRegeneration:()=>Cf,needsWindsurfRouterRegeneration:()=>xf,selectProvider:()=>Rf,validateCliVersion:()=>Hl});import{exec as yf}from"node:child_process";import Ln from"node:os";import Ne from"node:path";import{promisify as wf}from"node:util";async function Sf(r){try{let{stdout:e}=await _l(`which ${r}`,{timeout:Nl});return e.trim()}catch{return null}}async function kf(r){try{let{stdout:e}=await _l(`${r} --version`,{timeout:Nl}),t=e.match(/\d+\.\d+\.\d+/);return t?t[0]:e.trim()}catch{return null}}async function hi(r){let e=ht[r];if(!e.cliCommand)return{installed:!1};let t=await Sf(e.cliCommand);if(!t)return{installed:!1};let n=await kf(e.cliCommand),s=Hl(r,n||void 0);return{installed:!0,version:n||void 0,path:t,versionWarning:s||void 0}}function Hl(r,e){let t=ht[r];return!t.minCliVersion||!e?null:Dl(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 Si(r=!1){if(!r){let s=await Ml();if(s)return s}let[e,t]=await Promise.all([hi("claude"),hi("gemini")]),n={claude:e,gemini:t};return await Ol(n).catch(()=>{}),n}async function bf(r){if(r&&ht[r])return ht[r];let e=await Si();return e.claude.installed&&!e.gemini.installed?Sr:e.gemini.installed&&!e.claude.installed?yi:Sr}async function Pf(r){let e=ht[r];return e.configDir?M(e.configDir):!1}function kr(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 zl(r){let e=Ne.join(r,".cursor"),t=Ne.join(e,"rules"),n=Ne.join(t,"prjct.mdc"),[s,o]=await Promise.all([M(e),M(n)]);return{detected:s,routerInstalled:o,projectRoot:s?r:void 0}}async function Cf(r){let e=await zl(r);return e.detected&&!e.routerInstalled}async function Gl(r){let e=Ne.join(r,".windsurf"),t=Ne.join(e,"rules"),n=Ne.join(t,"prjct.md"),[s,o]=await Promise.all([M(e),M(n)]);return{detected:s,routerInstalled:o,projectRoot:s?r:void 0}}async function xf(r){let e=await Gl(r);return e.detected&&!e.routerInstalled}async function vf(){let r=wi.configDir;if(!r)return{installed:!1,skillInstalled:!1};let e=Ne.join(r,"skills","prjct","SKILL.md"),[t,n]=await Promise.all([M(r),M(e)]);return{installed:t,skillInstalled:n,configPath:t?r:void 0}}function Tf(r){let e=ht[r];return e.configDir?Ne.join(e.configDir,e.contextFile):null}function Ef(r){let e=ht[r];return!e.configDir||!e.settingsFile?null:Ne.join(e.configDir,e.settingsFile)}function Af(r){return ht[r].skillsDir}function If(r){return ht[r].commandsDir}function Df(r,e){let t=ht[r];return Ne.join(e,t.commandsDir)}async function Rf(){let r=await Si(),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 _l,Nl,Sr,yi,wi,Ll,Ul,ht,Ve=w(()=>{"use strict";Es();je();Fl();_l=wf(yf),Nl=2e3,Sr={name:"claude",displayName:"Claude Code",cliCommand:"claude",configDir:Ne.join(Ln.homedir(),".claude"),contextFile:"CLAUDE.md",skillsDir:Ne.join(Ln.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"},yi={name:"gemini",displayName:"Gemini CLI",cliCommand:"gemini",configDir:Ne.join(Ln.homedir(),".gemini"),contextFile:"GEMINI.md",skillsDir:Ne.join(Ln.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"},wi={name:"antigravity",displayName:"Google Antigravity",cliCommand:null,configDir:Ne.join(Ln.homedir(),".gemini","antigravity"),contextFile:"ANTIGRAVITY.md",skillsDir:Ne.join(Ln.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},Ll={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},Ul={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},ht={claude:Sr,gemini:yi,cursor:Ll,antigravity:wi,windsurf:Ul};l(Sf,"whichCommand");l(kf,"getCliVersion");l(hi,"detectProvider");l(Hl,"validateCliVersion");l(Si,"detectAllProviders");l(bf,"getActiveProvider");l(Pf,"hasProviderConfig");l(kr,"getProviderBranding");l(zl,"detectCursorProject");l(Cf,"needsCursorRouterRegeneration");l(Gl,"detectWindsurfProject");l(xf,"needsWindsurfRouterRegeneration");l(vf,"detectAntigravity");l(Tf,"getGlobalContextPath");l(Ef,"getGlobalSettingsPath");l(Af,"getSkillsPath");l(If,"getCommandsDir");l(Df,"getProjectCommandsPath");l(Rf,"selectProvider")});import jf from"node:crypto";import Dt from"node:fs/promises";import ki from"node:os";import _ from"node:path";import{globSync as $f}from"glob";var bi,Mf,E,ue=w(()=>{"use strict";se();je();bi=class{static{l(this,"PathManager")}globalBaseDir;globalProjectsDir;globalConfigDir;constructor(){let e=process.env.PRJCT_CLI_HOME?.trim();this.globalBaseDir=e?_.resolve(e):_.join(ki.homedir(),".prjct-cli"),this.globalProjectsDir=_.join(this.globalBaseDir,"projects"),this.globalConfigDir=_.join(this.globalBaseDir,"config")}setGlobalBaseDir(e){this.globalBaseDir=_.resolve(e),this.globalProjectsDir=_.join(this.globalBaseDir,"projects"),this.globalConfigDir=_.join(this.globalBaseDir,"config")}generateProjectId(e){return jf.randomUUID()}getGlobalBasePath(){return this.globalBaseDir}getGlobalProjectPath(e){return _.join(this.globalProjectsDir,e)}getLocalConfigPath(e){return _.join(e,".prjct","prjct.config.json")}getGlobalProjectConfigPath(e){return _.join(this.getGlobalProjectPath(e),"project.json")}getLegacyPrjctPath(e){return _.join(e,".prjct")}async hasLegacyStructure(e){let t=this.getLegacyPrjctPath(e);return await wr(t)}async hasConfig(e){let t=this.getLocalConfigPath(e);return await M(t)}async ensureGlobalStructure(){await ft(this.globalBaseDir),await ft(this.globalProjectsDir),await ft(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 ft(_.join(t,s));return await ft(_.join(t,"planning","tasks")),await ft(_.join(t,"sessions")),t}getSessionPath(e,t=new Date){let{year:n,month:s,day:o}=mi(t);return _.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 ft(n),n}async listSessions(e,t=null,n=null){let s=_.join(this.getGlobalProjectPath(e),"sessions"),o=[];try{let i=await Dt.readdir(s,{withFileTypes:!0});for(let a of i){if(!a.isDirectory()||t&&a.name!==t.toString())continue;let c=_.join(s,a.name),u=await Dt.readdir(c,{withFileTypes:!0});for(let d of u){if(!d.isDirectory()||n&&d.name!==n.toString().padStart(2,"0"))continue;let m=_.join(c,d.name),p=await Dt.readdir(m,{withFileTypes:!0});for(let g of p)g.isDirectory()&&o.push({year:a.name,month:d.name,day:g.name,path:_.join(m,g.name),date:new Date(`${a.name}-${d.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 _.join(this.getGlobalProjectPath(e),t,n)}async listProjects(){try{return await this.ensureGlobalStructure(),(await Dt.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 wr(t)}getDisplayPath(e){let t=ki.homedir();return e.startsWith(t)?e.replace(t,"~"):e}getAuthConfigPath(){return _.join(this.globalConfigDir,"auth.json")}getSyncPendingPath(e){return _.join(this.getGlobalProjectPath(e),"sync","pending.json")}getLastSyncPath(e){return _.join(this.getGlobalProjectPath(e),"sync","last-sync.json")}getRunningStatusPath(){return _.join(this.globalBaseDir,".running")}getDocsPath(){return _.join(this.globalBaseDir,"docs")}async getAgentDir(){return(await(Ve(),at(et)).getActiveProvider()).configDir}async getAgentSettingsPath(){let e=await(Ve(),at(et)).getActiveProvider();return(Ve(),at(et)).getGlobalSettingsPath(e.name)}getClaudeDir(){return _.join(ki.homedir(),".claude")}getClaudeSettingsPath(){return _.join(this.getClaudeDir(),"settings.json")}getAgentsPath(e){return e?_.join(this.getGlobalProjectPath(e),"agents"):_.join(this.globalBaseDir,"agents")}getStoragePath(e,t){return _.join(this.getGlobalProjectPath(e),"storage",t)}getContextPath(e){return _.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=_.join(e,s.file);if(await M(o)){t.isMonorepo=!0,t.type=s.type;break}}if(!t.isMonorepo){let s=_.join(e,"package.json");if(await M(s))try{let o=await Dt.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 Dt.readFile(_.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=_.join(e,"package.json"),i=await Dt.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=_.join(e,"lerna.json");if(await M(c)){let u=await Dt.readFile(c,"utf-8"),d=JSON.parse(u);d.packages&&(s=d.packages)}}}else if(t==="nx")s=["apps/*","libs/*","packages/*"];else if(t==="turborepo"){let o=_.join(e,"package.json"),i=await Dt.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=$f(o,{cwd:e,absolute:!1});for(let a of i){let c=_.join(e,a),u=_.join(c,"package.json");if(await M(u))try{let d=await Dt.readFile(u,"utf-8"),m=JSON.parse(d),p=_.join(c,"PRJCT.md");n.push({name:m.name||_.basename(a),path:c,relativePath:a,hasPrjctMd:await M(p)})}catch{}}}}catch{}return n}async findContainingPackage(e,t){if(!t.isMonorepo)return null;let n=_.resolve(e);for(let s of t.packages){let o=_.resolve(s.path);if(n.startsWith(o))return s}return null}async findMonorepoRoot(e){let t=_.resolve(e),n=_.parse(t).root;for(;t!==n;){if((await this.detectMonorepo(t)).isMonorepo)return t;t=_.dirname(t)}return null}},Mf=new bi,E=Mf});function Of(){return typeof globalThis<"u"&&"Bun"in globalThis?"bun":"node"}function As(){return Of()==="bun"}var Pi=w(()=>{"use strict";l(Of,"detectRuntime");l(As,"isBun")});import Ci from"node:fs";import Wl from"node:path";function Ff(r){if(As()){let{Database:s}=Ps("bun:sqlite");return new s(r,{create:!0})}let e=Ps("better-sqlite3"),t=new e(r),n=t.exec.bind(t);return t.run=s=>n(s),t}var _f,br,$,z,le=w(()=>{"use strict";ue();Pi();l(Ff,"openDatabase");_f=[{version:1,name:"initial-schema",up:l(r=>{r.run(`
|
|
11
11
|
-- =======================================================================
|
|
12
12
|
-- Document storage (backward-compatible with JSON file pattern)
|
|
13
13
|
-- =======================================================================
|
|
@@ -238,14 +238,13 @@ var vr=Object.defineProperty;var nf=Object.getOwnPropertyDescriptor;var sf=Objec
|
|
|
238
238
|
CREATE INDEX idx_archives_entity_type ON archives(entity_type);
|
|
239
239
|
CREATE INDEX idx_archives_archived_at ON archives(archived_at);
|
|
240
240
|
CREATE INDEX idx_archives_entity_id ON archives(entity_id);
|
|
241
|
-
`)},"up")}],
|
|
241
|
+
`)},"up")}],br=class{static{l(this,"PrjctDatabase")}connections=new Map;getDbPath(e){return Wl.join(E.getGlobalProjectPath(e),"prjct.db")}getDb(e){let t=this.connections.get(e);if(t)return t;let n=this.getDbPath(e),s=Wl.dirname(n);Ci.existsSync(s)||Ci.mkdirSync(s,{recursive:!0});let o=Ff(n);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 Ci.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(`
|
|
242
242
|
CREATE TABLE IF NOT EXISTS _migrations (
|
|
243
243
|
version INTEGER PRIMARY KEY,
|
|
244
244
|
name TEXT NOT NULL,
|
|
245
245
|
applied_at TEXT NOT NULL
|
|
246
246
|
)
|
|
247
|
-
`);let t=new Set(e.prepare("SELECT version FROM _migrations").all().map(n=>n.version));for(let n of gh)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}},M=new Mr,G=M});function Or(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 fh[r]}var Y,Ui,Hi,Fr,fh,St,lu,Gs,Qt=y(()=>{"use strict";Y={GATHERING:"gathering",ANALYZING:"analyzing",PROPOSING:"proposing",PENDING_APPROVAL:"awaiting_approval",APPROVED:"approved",REJECTED:"rejected",EXECUTING:"executing",COMPLETED:"completed",ABORTED:"aborted"},Ui=["feature","spec","design","refactor","migrate"],Hi=["ship","cleanup","git","migrate"],Fr=["Read","Glob","Grep","GetTimestamp","GetDate","GetDateTime"],fh={TOOL_CHECK:5e3,GIT_OPERATION:1e4,GIT_CLONE:6e4,API_REQUEST:3e4,NPM_INSTALL:12e4,WORKFLOW_HOOK:6e4};l(Or,"getTimeout");St={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},lu={HISTORY_MAX:100},Gs={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"}});function yh(){let r=process.env.PRJCT_DEBUG||process.env.DEBUG||"";if(!r)return{level:-1,name:"disabled"};if(hh.has(r)||r.includes("prjct"))return{level:Jn.debug,name:"debug"};let e=Jn[r]??-1,t=e>=0?r:"disabled";return{level:e,name:t}}function _r(r,e,t){return uu>=r?(...n)=>console[t](e,...n):Sh}var Jn,hh,uu,wh,Sh,kh,B,qn=y(()=>{"use strict";Jn={error:0,warn:1,info:2,debug:3},hh=new Set(["1","true","*"]);l(yh,"getLogLevel");({level:uu,name:wh}=yh()),Sh=l(()=>{},"noop");l(_r,"createLogMethod");kh={error:_r(Jn.error,"[prjct:error]","error"),warn:_r(Jn.warn,"[prjct:warn]","warn"),info:_r(Jn.info,"[prjct:info]","log"),debug:_r(Jn.debug,"[prjct:debug]","log"),isEnabled:l(()=>uu>=0,"isEnabled"),level:l(()=>wh,"level")},B=kh});var Nr,bh,du=y(()=>{"use strict";zt();de();Ei();Qt();qn();Nr=class{static{l(this,"EventBus")}listeners;onceListeners;history;historyLimit;projectId;constructor(){this.listeners=new Map,this.onceListeners=new Map,this.history=[],this.historyLimit=lu.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"&&B.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(xr.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(xr.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 B.error("Event callback error:",n),n}}async logEvent(e){try{M.appendEvent(this.projectId,e.type,e)}catch(t){B.debug("Failed to log event:",K(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())}},bh=new Nr});function Ur(r,e){let t=r[0];return e==="delete"?`${t}.deleted`:`${t}.updated`}var Lr,Kn,pu=y(()=>{"use strict";re();te();Fe();l(Ur,"inferEventType");Lr=class{static{l(this,"SyncEventBus")}async publish(e){let t=T.getSyncPendingPath(e.projectId),n=await pn(t,[])??[];n.push(e),await _s(t,n)}async getPending(e){let t=T.getSyncPendingPath(e);return await pn(t,[])??[]}async clearPending(e){let t=T.getSyncPendingPath(e);await _s(t,[])}async updateLastSync(e){let t=T.getLastSyncPath(e),n={timestamp:b(),success:!0};await _s(t,n)}async getLastSync(e){let t=T.getLastSyncPath(e);return await pn(t,null)}},Kn=new Lr});var Gi=y(()=>{"use strict";du();pu()});var kt,Hr=y(()=>{"use strict";kt=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 mu from"node:fs/promises";import Ph from"node:path";var xe,Mt=y(()=>{"use strict";Gi();re();Hr();te();de();xe=class{static{l(this,"StorageManager")}filename;cache;constructor(e,t){this.filename=e,this.cache=new kt({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}getContextPath(e,t){let n=this.getLayer();return T.getFilePath(e,n,t)}async read(e){let t=this.cache.get(e);if(t!==null)return t;try{let n=M.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 mu.mkdir(Ph.dirname(n),{recursive:!0}),M.setDoc(e,this.getStoreKey(),t);let s=this.toMarkdown(t);await mu.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 Kn.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 M.hasDoc(e,this.getStoreKey())}catch{return!1}}clearCache(e){e?this.cache.delete(e):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});import{createHash as Ch}from"node:crypto";var zi,Ft,Gr=y(()=>{"use strict";Ni();te();Mt();zi=class extends xe{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(`
|
|
248
|
-
`)}async saveDraft(e,t){let n={...t,status:"draft"};_i.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 _i.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 au(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 Ch("sha256").update(JSON.stringify(t)).digest("hex")}},Ft=new zi});var gu=y(()=>{"use strict"});import{z as ye}from"zod";var zr,Zt,vh,ST,Wi,fu,zs=y(()=>{"use strict";zr=ye.enum(["frontend","backend","database","devops","testing","docs","uxui","general"]),Zt=ye.object({primaryDomain:zr,secondaryDomains:ye.array(zr),confidence:ye.number().min(0).max(1),filePatterns:ye.array(ye.string()),relevantAgents:ye.array(ye.string())}),vh=ye.object({classification:Zt,classifiedAt:ye.string(),source:ye.enum(["cache","history","llm","heuristic"]),descriptionHash:ye.string(),projectId:ye.string()}),ST=ye.object({entries:ye.record(ye.string(),vh),confirmedPatterns:ye.array(ye.object({descriptionHash:ye.string(),classification:Zt,confirmedAt:ye.string(),taskDescription:ye.string()}))}),Wi={entries:{},confirmedPatterns:[]},fu={primaryDomain:"general",secondaryDomains:[],confidence:.3,filePatterns:["**/*.ts","**/*.js"],relevantAgents:[]}});import{z as N}from"zod";var xh,Th,hu,Eh,Ah,Ih,Dh,jh,yu,PT,Bi=y(()=>{"use strict";xh=N.enum(["low","medium","high"]),Th=N.enum(["pending","converted","completed","archived","dormant"]),hu=N.enum(["high","medium","low"]),Eh=N.object({impact:hu,effort:hu}),Ah=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()}),Ih=N.object({name:N.string(),description:N.string()}),Dh=N.object({name:N.string(),description:N.string().optional()}),jh=N.object({id:N.string(),text:N.string(),details:N.string().optional(),priority:xh,status:Th,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:Eh.optional(),implementationNotes:N.string().optional(),stack:Ah.optional(),modules:N.array(Ih).optional(),roles:N.array(Dh).optional(),risks:N.array(N.string()).optional(),risksCount:N.number().optional()}),yu=N.object({ideas:N.array(jh),lastUpdated:N.string()}),PT={priority:"medium",status:"pending",tags:[],addedAt:new Date().toISOString()}});import{z}from"zod";function Su(r){return{provider:r,lastSync:"",staleAfter:18e5,issues:{}}}var wu,Rh,$h,Mh,Fh,TT,ET,Vi=y(()=>{"use strict";wu=z.enum(["linear","jira","github","monday","asana","none"]),Rh=z.enum(["backlog","todo","in_progress","in_review","done","cancelled"]),$h=z.enum(["none","urgent","high","medium","low"]),Mh=z.enum(["feature","bug","improvement","task","chore","epic"]),Fh=z.object({id:z.string(),identifier:z.string(),title:z.string(),description:z.string().optional(),status:Rh,priority:$h,type:Mh.optional(),assignee:z.object({id:z.string(),name:z.string(),email:z.string().optional()}).optional(),labels:z.array(z.string()).default([]),team:z.object({id:z.string(),name:z.string(),key:z.string().optional()}).optional(),project:z.object({id:z.string(),name:z.string()}).optional(),url:z.string(),createdAt:z.string(),updatedAt:z.string(),fetchedAt:z.string()}),TT=z.object({provider:wu,lastSync:z.string(),staleAfter:z.number().default(18e5),issues:z.record(z.string(),Fh)}),ET=z.object({provider:wu,fetched:z.number(),updated:z.number(),errors:z.array(z.object({issueId:z.string(),error:z.string()})),timestamp:z.string()});l(Su,"createEmptyIssues")});var vu={};Ln(vu,{AgentAssignmentSchema:()=>ku,OUTPUT_SCHEMAS:()=>Pu,SubtaskBreakdownSchema:()=>bu,TaskClassificationSchema:()=>Zt,renderSchemaForPrompt:()=>Ji});import{z as De}from"zod";function Ji(r){let e=Pu[r];return e?`## OUTPUT FORMAT
|
|
247
|
+
`);let t=new Set(e.prepare("SELECT version FROM _migrations").all().map(n=>n.version));for(let n of _f)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}},$=new br,z=$});function vi(r){if(Pl.includes(r))return[r];let e=r.toLowerCase().replace(/[-_\s]/g,""),t=[];for(let[n,s]of Object.entries(Pr))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 xi,Pr,cn,Is,Ds,Rs=w(()=>{"use strict";le();On();se();xi={frontend:[I.CODE_STYLE,I.FILE_STRUCTURE,I.ARCHITECTURE,I.TECH_STACK],backend:[I.CODE_STYLE,I.ARCHITECTURE,I.DEPENDENCIES,I.TECH_STACK],devops:[I.SHIP_WORKFLOW,I.TEST_BEHAVIOR,I.DEPENDENCIES,I.ARCHITECTURE],docs:[I.CODE_STYLE,I.NAMING_CONVENTION,I.FILE_STRUCTURE],testing:[I.TEST_BEHAVIOR,I.CODE_STYLE,I.DEPENDENCIES],database:[I.ARCHITECTURE,I.NAMING_CONVENTION,I.TECH_STACK,I.DEPENDENCIES],general:Object.values(I)},Pr={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(vi,"resolveCanonicalDomains");cn=class{static{l(this,"CachedStore")}_data=null;_loaded=!1;_projectId=null;getSubdirectory(){return null}getStoreKey(){let e=this.getFilename().replace(".json",""),t=this.getSubdirectory();return t?`memory:${t}:${e}`:`memory:${e}`}async load(e){if(this._loaded&&this._data&&this._projectId===e)return this._data;let t=this.getStoreKey(),n=z.getDoc(e,t);return n!==null?(this._data=n,this.afterLoad(this._data)):this._data=this.getDefault(),this._loaded=!0,this._projectId=e,this._data}afterLoad(e){}async save(e){if(!this._data)return;let t=this.getStoreKey();z.setDoc(e,t,this._data)}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}},Is=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()}},Ds=class{static{l(this,"HistoryStore")}async appendHistory(e,t){let n={ts:k(),...t,type:t.type};z.appendEvent(e,`history.${t.type}`,n)}async getRecentHistory(e,t=20){return z.query(e,"SELECT data, timestamp FROM events WHERE type LIKE 'history.%' ORDER BY id DESC LIMIT ?",t).reverse().map(s=>JSON.parse(s.data))}}});var js,Ti=w(()=>{"use strict";le();On();se();Rs();js=class r extends cn{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=k();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=hr(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=k(),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=k();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=hr(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=k(),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:k(),confidence:hr(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=k(),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}}async archiveStaleDecisions(e){let t=await this.load(e),n=Date.now(),s=r.ARCHIVE_AGE_DAYS*24*60*60*1e3,o=[];for(let[a,c]of Object.entries(t.decisions)){let u=new Date(c.lastSeen).getTime();n-u>s&&o.push(a)}if(o.length===0)return 0;let i=z.getDoc(e,"memory:patterns-archive")??{};for(let a of o)i[a]=t.decisions[a],delete t.decisions[a];return z.setDoc(e,"memory:patterns-archive",i),await this.save(e),o.length}}});var Bl=w(()=>{"use strict"});import $s from"node:fs/promises";import Vt from"node:path";import{z as ee}from"zod";async function zf(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=Vt.join(e,"package.json"),s=await $s.readFile(n,"utf-8"),o=JSON.parse(s),i={...o.dependencies,...o.devDependencies},a=[],c=[];for(let u of r.frameworks){let d=u.toLowerCase();Object.keys(i).some(p=>p.toLowerCase().includes(d))?c.push(u):a.push(u)}return a.length===0?{name:"Framework verification",passed:!0,output:`${c.length} framework(s) verified in dependencies`,durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Frameworks not found in dependencies: ${a.join(", ")}`,durationMs:Date.now()-t}}catch(n){return C(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 Gf(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 Jf(e),s=new Set(n),o=[],i=[];for(let a of r.languages){let c=Hf[a];if(!c)continue;c.some(d=>s.has(d))?o.push(a):i.push(a)}return i.length===0?{name:"Language verification",passed:!0,output:`${o.length} language(s) verified with matching files`,durationMs:Date.now()-t}:{name:"Language verification",passed:!1,error:`Languages without matching files: ${i.join(", ")}`,durationMs:Date.now()-t}}catch(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 Wf(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=Vt.join(e,a);try{await $s.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 Bf(r,e){let t=Date.now();try{let n=await qf(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 Vf(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=Vt.join(e,o.file);try{await $s.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 Vl(r,e){let t=Date.now(),n=await Promise.all([zf(r,e),Gf(r,e),Wf(r,e),Bf(r,e),Vf(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 Jf(r){let e=new Set,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function n(s){try{let o=await $s.readdir(s,{withFileTypes:!0});for(let i of o){let a=Vt.join(s,i.name),c=Vt.relative(r,a);if(!t.some(u=>u.test(c))){if(i.isDirectory())await n(a);else if(i.isFile()){let u=Vt.extname(i.name);u&&e.add(u)}}}}catch{}}return l(n,"scanDir"),await n(r),Array.from(e)}async function qf(r){let e=0,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function n(s){try{let o=await $s.readdir(s,{withFileTypes:!0});for(let i of o){let a=Vt.join(s,i.name),c=Vt.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 Nf,Lf,Uf,Ei,av,Hf,Ai=w(()=>{"use strict";O();Es();Nf=ee.enum(["draft","verified","sealed"]),Lf=ee.object({name:ee.string(),description:ee.string(),location:ee.string().optional()}),Uf=ee.object({issue:ee.string(),file:ee.string(),suggestion:ee.string()}),Ei=ee.object({projectId:ee.string(),languages:ee.array(ee.string()),frameworks:ee.array(ee.string()),packageManager:ee.string().optional(),sourceDir:ee.string().optional(),testDir:ee.string().optional(),configFiles:ee.array(ee.string()),fileCount:ee.number(),patterns:ee.array(Lf),antiPatterns:ee.array(Uf),analyzedAt:ee.string(),modelMetadata:Ts.optional(),status:Nf.default("draft"),commitHash:ee.string().optional(),signature:ee.string().optional(),sealedAt:ee.string().optional(),verifiedAt:ee.string().optional()}),av={languages:[],frameworks:[],configFiles:[],fileCount:0,patterns:[],antiPatterns:[],analyzedAt:new Date().toISOString(),status:"draft"},Hf={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(zf,"verifyFrameworks");l(Gf,"verifyLanguages");l(Wf,"verifyPatternLocations");l(Bf,"verifyFileCount");l(Vf,"verifyAntiPatternFiles");l(Vl,"semanticVerify");l(Jf,"getProjectExtensions");l(qf,"countProjectFiles")});import{z as ye}from"zod";var Cr,Jt,Kf,dv,Ii,Jl,Ms=w(()=>{"use strict";Cr=ye.enum(["frontend","backend","database","devops","testing","docs","uxui","general"]),Jt=ye.object({primaryDomain:Cr,secondaryDomains:ye.array(Cr),confidence:ye.number().min(0).max(1),filePatterns:ye.array(ye.string()),relevantAgents:ye.array(ye.string())}),Kf=ye.object({classification:Jt,classifiedAt:ye.string(),source:ye.enum(["cache","history","llm","heuristic"]),descriptionHash:ye.string(),projectId:ye.string()}),dv=ye.object({entries:ye.record(ye.string(),Kf),confirmedPatterns:ye.array(ye.object({descriptionHash:ye.string(),classification:Jt,confirmedAt:ye.string(),taskDescription:ye.string()}))}),Ii={entries:{},confirmedPatterns:[]},Jl={primaryDomain:"general",secondaryDomains:[],confidence:.3,filePatterns:["**/*.ts","**/*.js"],relevantAgents:[]}});import{z as N}from"zod";var Yf,Xf,ql,Qf,Zf,eh,th,nh,Kl,gv,Di=w(()=>{"use strict";Yf=N.enum(["low","medium","high"]),Xf=N.enum(["pending","converted","completed","archived","dormant"]),ql=N.enum(["high","medium","low"]),Qf=N.object({impact:ql,effort:ql}),Zf=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()}),eh=N.object({name:N.string(),description:N.string()}),th=N.object({name:N.string(),description:N.string().optional()}),nh=N.object({id:N.string(),text:N.string(),details:N.string().optional(),priority:Yf,status:Xf,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:Qf.optional(),implementationNotes:N.string().optional(),stack:Zf.optional(),modules:N.array(eh).optional(),roles:N.array(th).optional(),risks:N.array(N.string()).optional(),risksCount:N.number().optional()}),Kl=N.object({ideas:N.array(nh),lastUpdated:N.string()}),gv={priority:"medium",status:"pending",tags:[],addedAt:new Date().toISOString()}});import{z as G}from"zod";function Xl(r){return{provider:r,lastSync:"",staleAfter:18e5,issues:{}}}var Yl,sh,rh,oh,ih,wv,Sv,Ri=w(()=>{"use strict";Yl=G.enum(["linear","jira","github","monday","asana","none"]),sh=G.enum(["backlog","todo","in_progress","in_review","done","cancelled"]),rh=G.enum(["none","urgent","high","medium","low"]),oh=G.enum(["feature","bug","improvement","task","chore","epic"]),ih=G.object({id:G.string(),identifier:G.string(),title:G.string(),description:G.string().optional(),status:sh,priority:rh,type:oh.optional(),assignee:G.object({id:G.string(),name:G.string(),email:G.string().optional()}).optional(),labels:G.array(G.string()).default([]),team:G.object({id:G.string(),name:G.string(),key:G.string().optional()}).optional(),project:G.object({id:G.string(),name:G.string()}).optional(),url:G.string(),createdAt:G.string(),updatedAt:G.string(),fetchedAt:G.string()}),wv=G.object({provider:Yl,lastSync:G.string(),staleAfter:G.number().default(18e5),issues:G.record(G.string(),ih)}),Sv=G.object({provider:Yl,fetched:G.number(),updated:G.number(),errors:G.array(G.object({issueId:G.string(),error:G.string()})),timestamp:G.string()});l(Xl,"createEmptyIssues")});var nu={};Mn(nu,{AgentAssignmentSchema:()=>Ql,OUTPUT_SCHEMAS:()=>eu,SubtaskBreakdownSchema:()=>Zl,TaskClassificationSchema:()=>Jt,renderSchemaForPrompt:()=>ji});import{z as Ae}from"zod";function ji(r){let e=eu[r];return e?`## OUTPUT FORMAT
|
|
249
248
|
|
|
250
249
|
Return ONLY valid JSON matching this schema (no markdown, no explanation):
|
|
251
250
|
|
|
@@ -254,11 +253,45 @@ ${e.example}
|
|
|
254
253
|
\`\`\`
|
|
255
254
|
|
|
256
255
|
Fields:
|
|
257
|
-
${
|
|
258
|
-
`)}return"(see example above)"}function Cu(r){return r instanceof De.ZodString?"string":r instanceof De.ZodNumber?"number":r instanceof De.ZodEnum?`one of: ${r.options.join(", ")}`:r instanceof De.ZodArray?`array of ${Cu(r.element)}`:r instanceof De.ZodObject?"object":"any"}var ku,bu,Pu,Wr=y(()=>{"use strict";zs();zs();ku=De.object({agentName:De.string(),reasoning:De.string(),confidence:De.number().min(0).max(1)}),bu=De.object({subtasks:De.array(De.object({description:De.string(),domain:zr,agent:De.string(),dependsOn:De.array(De.number())})),effort:De.enum(["low","medium","high"])}),Pu={classification:{schema:Zt,example:JSON.stringify({primaryDomain:"backend",secondaryDomains:["database"],confidence:.9,filePatterns:["src/api/**"],relevantAgents:["backend.md"]},null,2)},agentAssignment:{schema:ku,example:JSON.stringify({agentName:"backend.md",reasoning:"Task involves API endpoint creation",confidence:.85},null,2)},subtaskBreakdown:{schema:bu,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(Ji,"renderSchemaForPrompt");l(Oh,"describeSchema");l(Cu,"describeField")});import{z as E}from"zod";var xu,_h,Nh,Tu,Lh,Uh,Hh,Gh,zh,Wh,Bh,Eu,Vh,Jh,FT,Au,Iu,Du,ju,qh,Br,qi=y(()=>{"use strict";xu=E.number().min(1).max(5),_h=E.enum(["exceeded","met","partial","failed"]),Nh=E.enum(["definitely","probably","maybe","no"]),Tu=E.enum(["scope_creep","underestimated_complexity","technical_debt","external_blockers","learning_curve","requirements_changed","optimistic_estimate","team_changes","other"]),Lh=E.object({estimated:E.object({hours:E.number(),confidence:E.enum(["low","medium","high"]).optional(),source:E.enum(["prd","manual","historical"]).optional()}),actual:E.object({hours:E.number(),commits:E.number().optional(),linesAdded:E.number().optional(),linesRemoved:E.number().optional(),sessions:E.number().optional()}),variance:E.object({hours:E.number(),percentage:E.number(),reason:Tu.optional(),explanation:E.string().optional()})}),Uh=E.object({name:E.string(),baseline:E.number().nullable(),target:E.number(),actual:E.number(),unit:E.string(),achieved:E.boolean(),percentOfTarget:E.number()}),Hh=E.object({criteria:E.string(),met:E.boolean(),notes:E.string().optional()}),Gh=E.object({metrics:E.array(Uh),acceptanceCriteria:E.array(Hh),overallSuccess:_h,successScore:E.number().min(0).max(100)}),zh=E.object({category:E.enum(["estimation","technical","process","communication","tooling","architecture","testing","other"]),insight:E.string(),actionable:E.boolean(),action:E.string().optional()}),Wh=E.object({whatWorked:E.array(E.string()),whatDidnt:E.array(E.string()),surprises:E.array(E.string()),recommendations:E.array(zh)}),Bh=E.object({valueDelivered:E.number().min(1).max(10),userImpact:E.enum(["none","low","medium","high","critical"]),businessImpact:E.enum(["none","low","medium","high","critical"]),roiScore:E.number(),worthIt:Nh,worthItReason:E.string().optional(),alternativeConsidered:E.string().optional(),betterAlternativeExists:E.boolean().optional()}),Eu=E.object({id:E.string(),taskId:E.string(),description:E.string(),estimatedMinutes:E.number().optional(),actualMinutes:E.number(),completedAsPlanned:E.boolean(),qualityScore:xu,blockers:E.array(E.string()),agentUsed:E.string().optional(),skillsUsed:E.array(E.string()).optional(),startedAt:E.string(),completedAt:E.string()}),Vh=E.object({id:E.string(),featureId:E.string(),featureName:E.string(),prdId:E.string().nullable(),version:E.string().optional(),branch:E.string().optional(),prUrl:E.string().optional(),effort:Lh,success:Gh.optional(),learnings:Wh,roi:Bh,rating:xu,taskOutcomes:E.array(Eu).optional(),startedAt:E.string(),shippedAt:E.string(),reviewedAt:E.string().optional(),reviewedBy:E.string().optional(),legacy:E.boolean().optional()}),Jh=E.object({totalFeatures:E.number(),averageEstimationAccuracy:E.number(),averageSuccessRate:E.number(),averageROI:E.number(),bySuccessLevel:E.object({exceeded:E.number(),met:E.number(),partial:E.number(),failed:E.number()}),variancePatterns:E.array(E.object({reason:Tu,count:E.number(),averageVariance:E.number()})),topLearnings:E.array(E.object({insight:E.string(),frequency:E.number()}))}),FT=E.object({outcomes:E.array(Vh),taskOutcomes:E.array(Eu).optional(),aggregates:Jh.optional(),lastUpdated:E.string(),lastAggregated:E.string().optional()}),Au={outcomes:[],taskOutcomes:[],lastUpdated:""},Iu=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"),Du=l((r,e)=>e<=0?r*10:Math.round(r*10/e*100)/100,"calculateROIScore"),ju=l(r=>r>=100?"exceeded":r>=80?"met":r>=50?"partial":"failed","determineSuccessLevel"),qh=l(r=>Math.max(0,100-Math.abs(r)),"calculateEstimationAccuracy"),Br=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(d=>qh(d.effort.variance.percentage)),t=r.filter(d=>d.success).map(d=>d.success.successScore),n=r.map(d=>d.roi.roiScore),s={exceeded:r.filter(d=>d.success?.overallSuccess==="exceeded").length,met:r.filter(d=>d.success?.overallSuccess==="met").length,partial:r.filter(d=>d.success?.overallSuccess==="partial").length,failed:r.filter(d=>d.success?.overallSuccess==="failed").length},o=r.filter(d=>d.effort.variance.reason).reduce((d,m)=>{let p=m.effort.variance.reason;return d[p]||(d[p]={count:0,totalVariance:0}),d[p].count++,d[p].totalVariance+=m.effort.variance.percentage,d},{}),i=Object.entries(o).map(([d,m])=>({reason:d,count:m.count,averageVariance:Math.round(m.totalVariance/m.count)})),c=r.flatMap(d=>[...d.learnings.whatWorked,...d.learnings.whatDidnt]).reduce((d,m)=>(d[m]=(d[m]||0)+1,d),{}),u=Object.entries(c).sort((d,m)=>m[1]-d[1]).slice(0,10).map(([d,m])=>({insight:d,frequency:m}));return{totalFeatures:r.length,averageEstimationAccuracy:Math.round(e.reduce((d,m)=>d+m,0)/e.length),averageSuccessRate:t.length>0?Math.round(t.reduce((d,m)=>d+m,0)/t.length):0,averageROI:Math.round(n.reduce((d,m)=>d+m,0)/n.length*100)/100,bySuccessLevel:s,variancePatterns:i,topLearnings:u}},"aggregateOutcomes")});import{z as Te}from"zod";function ey(){let r={};for(let e of Xh)r[e]="allow";for(let e of Qh)r[e]="ask";for(let e of Zh)r[e]="deny";return{bash:r,files:{read:{"**/*":"allow"},write:{"**/*":"allow"},delete:{"**/*":"ask"}},web:{enabled:!0},doomLoop:{enabled:!0,maxRetries:3},externalDirectories:"ask"}}var Vr,LT,Kh,Ki,Yh,UT,Xh,Qh,Zh,HT,Ru=y(()=>{"use strict";Vr=Te.enum(["allow","deny","ask"]),LT=Te.enum(["read","write","delete","create"]),Kh=Te.record(Te.string(),Vr),Ki=Te.record(Te.string(),Vr),Yh=Te.object({enabled:Te.boolean().default(!0),allowedDomains:Te.array(Te.string()).optional(),blockedDomains:Te.array(Te.string()).optional()}),UT=Te.object({bash:Kh.optional(),files:Te.object({read:Ki.optional(),write:Ki.optional(),delete:Ki.optional()}).optional(),web:Yh.optional(),skills:Te.record(Te.string(),Vr).optional(),doomLoop:Te.object({enabled:Te.boolean().default(!0),maxRetries:Te.number().default(3)}).optional(),externalDirectories:Vr.default("ask")}),Xh=["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*"],Qh=["rm -rf*","rm -r*","git push*","git reset --hard*","git clean*","npm publish*","chmod*","chown*","sudo*","curl*|*sh","wget*|*sh"],Zh=["rm -rf /*","rm -rf ~/*",":(){ :|:& };:*","mkfs*","dd if=*of=/dev/*"];l(ey,"buildDefaultPermissions");HT=ey()});import{z as Ve}from"zod";var BT,VT,$u=y(()=>{"use strict";BT=Ve.object({projectId:Ve.string(),name:Ve.string(),repoPath:Ve.string(),description:Ve.string().optional(),version:Ve.string().optional(),cliVersion:Ve.string().optional(),techStack:Ve.array(Ve.string()),fileCount:Ve.number(),commitCount:Ve.number(),createdAt:Ve.string(),lastSync:Ve.string(),lastSyncCommit:Ve.string().optional(),lastSyncBranch:Ve.string().optional()}),VT={techStack:[],fileCount:0,commitCount:0,createdAt:new Date().toISOString(),lastSync:new Date().toISOString()}});import{z as A}from"zod";var ty,ny,sy,ry,oy,iy,ay,cy,ly,uy,dy,py,my,gy,fy,hy,yy,wy,YT,XT,Mu=y(()=>{"use strict";ty=A.enum(["planned","active","completed","shipped"]),ny=A.enum(["low","medium","high"]),sy=A.enum(["feature","breaking_change","refactor","infrastructure"]),ry=A.enum(["completed","active","planned"]),oy=A.enum(["planned","active","completed"]),iy=A.enum(["git","git-branch","manual","prd"]),ay=A.object({id:A.string(),description:A.string(),completed:A.boolean(),completedAt:A.string().optional()}),cy=A.object({id:A.string(),name:A.string(),status:ry,completedAt:A.string().optional()}),ly=A.object({goal:A.string(),phases:A.array(cy),successMetrics:A.array(A.string()).optional()}),uy=A.object({hours:A.number(),minutes:A.number(),totalMinutes:A.number(),display:A.string().optional()}),dy=A.object({hash:A.string(),message:A.string(),date:A.string(),author:A.string().optional()}),py=A.object({hours:A.number(),confidence:A.enum(["low","medium","high"]).optional(),breakdown:A.array(A.object({area:A.string(),hours:A.number()})).optional()}),my=A.object({hours:A.number().optional(),commits:A.number().optional(),linesAdded:A.number().optional(),linesRemoved:A.number().optional()}),gy=A.object({estimated:py.nullable(),actual:my.nullable()}),fy=A.object({totalHours:A.number(),allocatedHours:A.number(),bufferPercent:A.number().optional()}),hy=A.object({id:A.string(),name:A.string(),theme:A.string().optional(),goals:A.array(A.string()).optional(),features:A.array(A.string()),capacity:fy.optional(),status:oy,startDate:A.string().optional(),endDate:A.string().optional()}),yy=A.object({id:A.string(),name:A.string(),description:A.string().optional(),date:A.string(),status:ty,impact:ny,effort:A.string().optional(),progress:A.number(),type:sy.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(ay),createdAt:A.string(),shippedAt:A.string().optional(),version:A.string().optional(),duration:uy.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:iy.optional(),quarter:A.string().nullable().optional(),dependencies:A.array(A.string()).optional(),blockedBy:A.array(A.string()).optional(),effortTracking:gy.optional(),valueScore:A.number().optional(),commits:A.array(dy).optional(),branch:A.string().optional(),commitsAhead:A.number().optional()}),wy=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()}),YT=A.object({strategy:ly.nullable().optional(),features:A.array(yy),backlog:A.array(A.union([A.string(),wy])),lastUpdated:A.string(),quarters:A.array(hy).optional(),generatedFrom:A.enum(["git-history","manual","prd"]).optional(),generatedAt:A.string().optional()}),XT={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 Sy from"node:crypto";import{homedir as ky}from"node:os";import{join as by}from"node:path";function ae(){return Sy.randomUUID()}var Py,Fu=y(()=>{"use strict";l(ae,"generateUUID");Py=by(ky(),".prjct-cli","projects")});import{z as V}from"zod";var Cy,Ou,vy,xy,Ty,Ey,Ay,Iy,Dy,_u,Yi=y(()=>{"use strict";Cy=V.enum(["feature","fix","improvement","refactor"]),Ou=V.enum(["pass","warning","fail","skipped"]),vy=V.enum(["added","changed","fixed","removed"]),xy=V.object({hours:V.number(),minutes:V.number(),totalMinutes:V.number()}),Ty=V.object({filesChanged:V.number().nullable().optional(),linesAdded:V.number().nullable().optional(),linesRemoved:V.number().nullable().optional(),commits:V.number().nullable().optional()}),Ey=V.object({description:V.string(),type:vy.optional()}),Ay=V.object({lintStatus:Ou.nullable().optional(),lintDetails:V.string().optional(),testStatus:Ou.nullable().optional(),testDetails:V.string().optional()}),Iy=V.object({hash:V.string().optional(),message:V.string().optional(),branch:V.string().optional()}),Dy=V.object({id:V.string(),name:V.string(),version:V.string().nullable().optional(),type:Cy,agent:V.string().optional(),description:V.string().optional(),changes:V.array(Ey).optional(),codeSnippets:V.array(V.string()).optional(),commit:Iy.optional(),codeMetrics:Ty.optional(),qualityMetrics:Ay.optional(),quantitativeImpact:V.string().optional(),duration:xy.optional(),tasksCompleted:V.number().nullable().optional(),shippedAt:V.string(),featureId:V.string().optional()}),_u=V.object({shipped:V.array(Dy),lastUpdated:V.string()})});import{z as x}from"zod";var jy,Lu,Ry,$y,My,Xi,Uu,Fy,Oy,Hu,Nu,_y,Ny,Gu,zu,Wu,Ly,Uy,uE,Jr=y(()=>{"use strict";Ls();jy=x.enum(["low","medium","high","critical"]),Lu=x.enum(["feature","bug","improvement","chore"]),Ry=x.enum(["active","backlog","previously_active"]),$y=x.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),My=x.enum(["task_completed","feature_shipped","idea_captured","session_started"]),Xi=x.object({title:x.string(),description:x.string(),filesChanged:x.array(x.object({path:x.string(),action:x.enum(["created","modified","deleted"])})),whatWasDone:x.array(x.string()).min(1),outputForNextAgent:x.string().min(1),notes:x.string().optional()}),Uu=x.object({output:x.string().min(1,"Subtask output is required"),summary:Xi}),Fy=x.object({id:x.string(),description:x.string(),domain:x.string(),agent:x.string(),status:$y,dependsOn:x.array(x.string()),startedAt:x.string().optional(),completedAt:x.string().optional(),output:x.string().optional(),summary:Xi.optional(),skipReason:x.string().optional(),blockReason:x.string().optional(),estimatedPoints:x.number().optional(),estimatedMinutes:x.number().optional()}),Oy=x.object({completed:x.number(),total:x.number(),percentage:x.number()}),Hu=x.object({id:x.string(),description:x.string(),startedAt:x.string(),sessionId:x.string(),featureId:x.string().optional(),subtasks:x.array(Fy).optional(),currentSubtaskIndex:x.number().optional(),subtaskProgress:Oy.optional(),linearId:x.string().optional(),linearUuid:x.string().optional(),estimatedPoints:x.number().optional(),estimatedMinutes:x.number().optional(),modelMetadata:Ns.optional()}),Nu=x.object({id:x.string(),description:x.string(),status:x.literal("paused"),startedAt:x.string(),pausedAt:x.string(),pauseReason:x.string().optional()}),_y=x.object({stackConfirmed:x.array(x.string()).optional(),patternsDiscovered:x.array(x.string()).optional(),agentAccuracy:x.array(x.object({agent:x.string(),rating:x.enum(["helpful","neutral","inaccurate"]),note:x.string().optional()})).optional(),issuesEncountered:x.array(x.string()).optional()}),Ny=x.object({taskId:x.string(),title:x.string(),classification:Lu,startedAt:x.string(),completedAt:x.string(),subtaskCount:x.number(),subtaskSummaries:x.array(Xi),outcome:x.string(),branchName:x.string(),linearId:x.string().optional(),linearUuid:x.string().optional(),prUrl:x.string().optional(),feedback:_y.optional()}),Gu=x.object({currentTask:Hu.nullable(),previousTask:Nu.nullable().optional(),pausedTasks:x.array(Nu).optional(),taskHistory:x.array(Ny).optional(),lastUpdated:x.string()}),zu=x.object({id:x.string(),description:x.string(),priority:jy,type:Lu,featureId:x.string().optional(),originFeature:x.string().optional(),completed:x.boolean(),completedAt:x.string().optional(),createdAt:x.string(),section:Ry,agent:x.string().optional(),groupName:x.string().optional(),groupId:x.string().optional()}),Wu=x.object({tasks:x.array(zu),lastUpdated:x.string()}),Ly=x.object({tasksToday:x.number(),tasksThisWeek:x.number(),streak:x.number(),velocity:x.string(),avgDuration:x.string()}),Uy=x.object({type:My,description:x.string(),timestamp:x.string(),duration:x.string().optional()}),uE=x.object({projectId:x.string(),currentTask:Hu.nullable(),queue:x.array(zu),stats:Ly,recentActivity:x.array(Uy),lastSync:x.string()})});import{z as Q}from"zod";var Hy,Gy,Bu,gE,fE,hE,en,Vu,Yn=y(()=>{"use strict";Hy=Q.enum(["improving","stable","declining"]),Gy=Q.object({sprintNumber:Q.number(),startDate:Q.string(),endDate:Q.string(),pointsCompleted:Q.number(),tasksCompleted:Q.number(),avgVariance:Q.number(),estimationAccuracy:Q.number()}),Bu=Q.object({category:Q.string(),avgVariance:Q.number(),taskCount:Q.number()}),gE=Q.object({totalPoints:Q.number(),sprints:Q.number(),estimatedDate:Q.string()}),fE=Q.object({sprints:Q.array(Gy),averageVelocity:Q.number(),velocityTrend:Hy,estimationAccuracy:Q.number(),overEstimated:Q.array(Bu),underEstimated:Q.array(Bu),lastUpdated:Q.string()}),hE=Q.object({sprintLengthDays:Q.number().min(1).max(90).default(7),startDay:Q.enum(["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]).default("monday"),windowSize:Q.number().min(1).max(52).default(6),accuracyTolerance:Q.number().min(0).max(100).default(20)}),en={sprintLengthDays:7,startDay:"monday",windowSize:6,accuracyTolerance:20},Vu={sprints:[],averageVelocity:0,velocityTrend:"stable",estimationAccuracy:0,overEstimated:[],underEstimated:[],lastUpdated:""}});var bt=y(()=>{"use strict";gu();Ni();zs();Bi();Vi();Wr();Ls();qi();Ru();$u();Mu();Fu();Yi();Jr();Yn()});var Ot,Qi,rt,tn=y(()=>{"use strict";bt();te();de();Ot={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Qi=class{static{l(this,"ArchiveStorage")}archive(e,t){let n=ae(),s=b();return M.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 M.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(ae(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,n,i.reason)}),t.length}getArchived(e,t,n=50){return t?M.query(e,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",t,n):M.query(e,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",n)}getStats(e){let t=M.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=M.get(e,"SELECT * FROM archives WHERE id = ?",t);return n?(M.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);M.run(e,"DELETE FROM archives WHERE archived_at < ?",n);let o=this.getTotalCount(e);return s-o}getTotalCount(e){return M.get(e,"SELECT COUNT(*) as count FROM archives")?.count??0}},rt=new Qi});var Zi,Ee,Xn=y(()=>{"use strict";bt();Bi();te();tn();Mt();Zi=class extends xe{static{l(this,"IdeasStorage")}constructor(){super("ideas.json",yu)}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=nt(a.addedAt),u=a.tags.length>0?` ${a.tags.map(m=>`#${m}`).join(" ")}`:"",d=a.priority!=="medium"?` [${a.priority.toUpperCase()}]`:"";t.push(`- ${a.text}${d} _(${c})_${u}`)}):t.push("_No pending ideas_"),t.push(""),s.length>0&&(t.push("## Converted"),s.forEach(a=>{let c=nt(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=nt(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(`
|
|
259
|
-
|
|
260
|
-
`)
|
|
261
|
-
`)}
|
|
256
|
+
${ah(e.schema)}`:null}function ah(r){if(r instanceof Ae.ZodObject){let e=r.shape;return Object.entries(e).map(([t,n])=>`- \`${t}\`: ${tu(n)}`).join(`
|
|
257
|
+
`)}return"(see example above)"}function tu(r){return r instanceof Ae.ZodString?"string":r instanceof Ae.ZodNumber?"number":r instanceof Ae.ZodEnum?`one of: ${r.options.join(", ")}`:r instanceof Ae.ZodArray?`array of ${tu(r.element)}`:r instanceof Ae.ZodObject?"object":"any"}var Ql,Zl,eu,xr=w(()=>{"use strict";Ms();Ms();Ql=Ae.object({agentName:Ae.string(),reasoning:Ae.string(),confidence:Ae.number().min(0).max(1)}),Zl=Ae.object({subtasks:Ae.array(Ae.object({description:Ae.string(),domain:Cr,agent:Ae.string(),dependsOn:Ae.array(Ae.number())})),effort:Ae.enum(["low","medium","high"])}),eu={classification:{schema:Jt,example:JSON.stringify({primaryDomain:"backend",secondaryDomains:["database"],confidence:.9,filePatterns:["src/api/**"],relevantAgents:["backend.md"]},null,2)},agentAssignment:{schema:Ql,example:JSON.stringify({agentName:"backend.md",reasoning:"Task involves API endpoint creation",confidence:.85},null,2)},subtaskBreakdown:{schema:Zl,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(ji,"renderSchemaForPrompt");l(ah,"describeSchema");l(tu,"describeField")});import{z as v}from"zod";var su,ch,lh,ru,uh,dh,ph,mh,gh,fh,hh,ou,yh,wh,Ev,iu,au,cu,lu,Sh,vr,$i=w(()=>{"use strict";su=v.number().min(1).max(5),ch=v.enum(["exceeded","met","partial","failed"]),lh=v.enum(["definitely","probably","maybe","no"]),ru=v.enum(["scope_creep","underestimated_complexity","technical_debt","external_blockers","learning_curve","requirements_changed","optimistic_estimate","team_changes","other"]),uh=v.object({estimated:v.object({hours:v.number(),confidence:v.enum(["low","medium","high"]).optional(),source:v.enum(["prd","manual","historical"]).optional()}),actual:v.object({hours:v.number(),commits:v.number().optional(),linesAdded:v.number().optional(),linesRemoved:v.number().optional(),sessions:v.number().optional()}),variance:v.object({hours:v.number(),percentage:v.number(),reason:ru.optional(),explanation:v.string().optional()})}),dh=v.object({name:v.string(),baseline:v.number().nullable(),target:v.number(),actual:v.number(),unit:v.string(),achieved:v.boolean(),percentOfTarget:v.number()}),ph=v.object({criteria:v.string(),met:v.boolean(),notes:v.string().optional()}),mh=v.object({metrics:v.array(dh),acceptanceCriteria:v.array(ph),overallSuccess:ch,successScore:v.number().min(0).max(100)}),gh=v.object({category:v.enum(["estimation","technical","process","communication","tooling","architecture","testing","other"]),insight:v.string(),actionable:v.boolean(),action:v.string().optional()}),fh=v.object({whatWorked:v.array(v.string()),whatDidnt:v.array(v.string()),surprises:v.array(v.string()),recommendations:v.array(gh)}),hh=v.object({valueDelivered:v.number().min(1).max(10),userImpact:v.enum(["none","low","medium","high","critical"]),businessImpact:v.enum(["none","low","medium","high","critical"]),roiScore:v.number(),worthIt:lh,worthItReason:v.string().optional(),alternativeConsidered:v.string().optional(),betterAlternativeExists:v.boolean().optional()}),ou=v.object({id:v.string(),taskId:v.string(),description:v.string(),estimatedMinutes:v.number().optional(),actualMinutes:v.number(),completedAsPlanned:v.boolean(),qualityScore:su,blockers:v.array(v.string()),agentUsed:v.string().optional(),skillsUsed:v.array(v.string()).optional(),startedAt:v.string(),completedAt:v.string()}),yh=v.object({id:v.string(),featureId:v.string(),featureName:v.string(),prdId:v.string().nullable(),version:v.string().optional(),branch:v.string().optional(),prUrl:v.string().optional(),effort:uh,success:mh.optional(),learnings:fh,roi:hh,rating:su,taskOutcomes:v.array(ou).optional(),startedAt:v.string(),shippedAt:v.string(),reviewedAt:v.string().optional(),reviewedBy:v.string().optional(),legacy:v.boolean().optional()}),wh=v.object({totalFeatures:v.number(),averageEstimationAccuracy:v.number(),averageSuccessRate:v.number(),averageROI:v.number(),bySuccessLevel:v.object({exceeded:v.number(),met:v.number(),partial:v.number(),failed:v.number()}),variancePatterns:v.array(v.object({reason:ru,count:v.number(),averageVariance:v.number()})),topLearnings:v.array(v.object({insight:v.string(),frequency:v.number()}))}),Ev=v.object({outcomes:v.array(yh),taskOutcomes:v.array(ou).optional(),aggregates:wh.optional(),lastUpdated:v.string(),lastAggregated:v.string().optional()}),iu={outcomes:[],taskOutcomes:[],lastUpdated:""},au=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"),cu=l((r,e)=>e<=0?r*10:Math.round(r*10/e*100)/100,"calculateROIScore"),lu=l(r=>r>=100?"exceeded":r>=80?"met":r>=50?"partial":"failed","determineSuccessLevel"),Sh=l(r=>Math.max(0,100-Math.abs(r)),"calculateEstimationAccuracy"),vr=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(d=>Sh(d.effort.variance.percentage)),t=r.filter(d=>d.success).map(d=>d.success.successScore),n=r.map(d=>d.roi.roiScore),s={exceeded:r.filter(d=>d.success?.overallSuccess==="exceeded").length,met:r.filter(d=>d.success?.overallSuccess==="met").length,partial:r.filter(d=>d.success?.overallSuccess==="partial").length,failed:r.filter(d=>d.success?.overallSuccess==="failed").length},o=r.filter(d=>d.effort.variance.reason).reduce((d,m)=>{let p=m.effort.variance.reason;return d[p]||(d[p]={count:0,totalVariance:0}),d[p].count++,d[p].totalVariance+=m.effort.variance.percentage,d},{}),i=Object.entries(o).map(([d,m])=>({reason:d,count:m.count,averageVariance:Math.round(m.totalVariance/m.count)})),c=r.flatMap(d=>[...d.learnings.whatWorked,...d.learnings.whatDidnt]).reduce((d,m)=>(d[m]=(d[m]||0)+1,d),{}),u=Object.entries(c).sort((d,m)=>m[1]-d[1]).slice(0,10).map(([d,m])=>({insight:d,frequency:m}));return{totalFeatures:r.length,averageEstimationAccuracy:Math.round(e.reduce((d,m)=>d+m,0)/e.length),averageSuccessRate:t.length>0?Math.round(t.reduce((d,m)=>d+m,0)/t.length):0,averageROI:Math.round(n.reduce((d,m)=>d+m,0)/n.length*100)/100,bySuccessLevel:s,variancePatterns:i,topLearnings:u}},"aggregateOutcomes")});import{z as xe}from"zod";function vh(){let r={};for(let e of Ph)r[e]="allow";for(let e of Ch)r[e]="ask";for(let e of xh)r[e]="deny";return{bash:r,files:{read:{"**/*":"allow"},write:{"**/*":"allow"},delete:{"**/*":"ask"}},web:{enabled:!0},doomLoop:{enabled:!0,maxRetries:3},externalDirectories:"ask"}}var Tr,Rv,kh,Mi,bh,jv,Ph,Ch,xh,$v,uu=w(()=>{"use strict";Tr=xe.enum(["allow","deny","ask"]),Rv=xe.enum(["read","write","delete","create"]),kh=xe.record(xe.string(),Tr),Mi=xe.record(xe.string(),Tr),bh=xe.object({enabled:xe.boolean().default(!0),allowedDomains:xe.array(xe.string()).optional(),blockedDomains:xe.array(xe.string()).optional()}),jv=xe.object({bash:kh.optional(),files:xe.object({read:Mi.optional(),write:Mi.optional(),delete:Mi.optional()}).optional(),web:bh.optional(),skills:xe.record(xe.string(),Tr).optional(),doomLoop:xe.object({enabled:xe.boolean().default(!0),maxRetries:xe.number().default(3)}).optional(),externalDirectories:Tr.default("ask")}),Ph=["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*"],Ch=["rm -rf*","rm -r*","git push*","git reset --hard*","git clean*","npm publish*","chmod*","chown*","sudo*","curl*|*sh","wget*|*sh"],xh=["rm -rf /*","rm -rf ~/*",":(){ :|:& };:*","mkfs*","dd if=*of=/dev/*"];l(vh,"buildDefaultPermissions");$v=vh()});import{z as Ge}from"zod";var _v,Nv,du=w(()=>{"use strict";_v=Ge.object({projectId:Ge.string(),name:Ge.string(),repoPath:Ge.string(),description:Ge.string().optional(),version:Ge.string().optional(),cliVersion:Ge.string().optional(),techStack:Ge.array(Ge.string()),fileCount:Ge.number(),commitCount:Ge.number(),createdAt:Ge.string(),lastSync:Ge.string(),lastSyncCommit:Ge.string().optional(),lastSyncBranch:Ge.string().optional()}),Nv={techStack:[],fileCount:0,commitCount:0,createdAt:new Date().toISOString(),lastSync:new Date().toISOString()}});import{z as T}from"zod";var Th,Eh,Ah,Ih,Dh,Rh,jh,$h,Mh,Oh,Fh,_h,Nh,Lh,Uh,Hh,zh,Gh,zv,Gv,pu=w(()=>{"use strict";Th=T.enum(["planned","active","completed","shipped"]),Eh=T.enum(["low","medium","high"]),Ah=T.enum(["feature","breaking_change","refactor","infrastructure"]),Ih=T.enum(["completed","active","planned"]),Dh=T.enum(["planned","active","completed"]),Rh=T.enum(["git","git-branch","manual","prd"]),jh=T.object({id:T.string(),description:T.string(),completed:T.boolean(),completedAt:T.string().optional()}),$h=T.object({id:T.string(),name:T.string(),status:Ih,completedAt:T.string().optional()}),Mh=T.object({goal:T.string(),phases:T.array($h),successMetrics:T.array(T.string()).optional()}),Oh=T.object({hours:T.number(),minutes:T.number(),totalMinutes:T.number(),display:T.string().optional()}),Fh=T.object({hash:T.string(),message:T.string(),date:T.string(),author:T.string().optional()}),_h=T.object({hours:T.number(),confidence:T.enum(["low","medium","high"]).optional(),breakdown:T.array(T.object({area:T.string(),hours:T.number()})).optional()}),Nh=T.object({hours:T.number().optional(),commits:T.number().optional(),linesAdded:T.number().optional(),linesRemoved:T.number().optional()}),Lh=T.object({estimated:_h.nullable(),actual:Nh.nullable()}),Uh=T.object({totalHours:T.number(),allocatedHours:T.number(),bufferPercent:T.number().optional()}),Hh=T.object({id:T.string(),name:T.string(),theme:T.string().optional(),goals:T.array(T.string()).optional(),features:T.array(T.string()),capacity:Uh.optional(),status:Dh,startDate:T.string().optional(),endDate:T.string().optional()}),zh=T.object({id:T.string(),name:T.string(),description:T.string().optional(),date:T.string(),status:Th,impact:Eh,effort:T.string().optional(),progress:T.number(),type:Ah.optional(),roi:T.number().optional(),why:T.array(T.string()).optional(),technicalNotes:T.array(T.string()).optional(),compatibility:T.string().optional(),phase:T.string().optional(),tasks:T.array(jh),createdAt:T.string(),shippedAt:T.string().optional(),version:T.string().optional(),duration:Oh.optional(),taskCount:T.number().optional(),agent:T.string().optional(),sprintName:T.string().optional(),completedDate:T.string().optional(),prdId:T.string().nullable().optional(),legacy:T.boolean().optional(),inferredFrom:Rh.optional(),quarter:T.string().nullable().optional(),dependencies:T.array(T.string()).optional(),blockedBy:T.array(T.string()).optional(),effortTracking:Lh.optional(),valueScore:T.number().optional(),commits:T.array(Fh).optional(),branch:T.string().optional(),commitsAhead:T.number().optional()}),Gh=T.object({id:T.string(),title:T.string(),prdId:T.string().nullable().optional(),valueScore:T.number().optional(),effortEstimate:T.number().optional(),reason:T.string().optional()}),zv=T.object({strategy:Mh.nullable().optional(),features:T.array(zh),backlog:T.array(T.union([T.string(),Gh])),lastUpdated:T.string(),quarters:T.array(Hh).optional(),generatedFrom:T.enum(["git-history","manual","prd"]).optional(),generatedAt:T.string().optional()}),Gv={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 Wh from"node:crypto";import{homedir as Bh}from"node:os";import{join as Vh}from"node:path";function oe(){return Wh.randomUUID()}var Jh,mu=w(()=>{"use strict";l(oe,"generateUUID");Jh=Vh(Bh(),".prjct-cli","projects")});import{z as V}from"zod";var qh,gu,Kh,Yh,Xh,Qh,Zh,ey,ty,fu,Oi=w(()=>{"use strict";qh=V.enum(["feature","fix","improvement","refactor"]),gu=V.enum(["pass","warning","fail","skipped"]),Kh=V.enum(["added","changed","fixed","removed"]),Yh=V.object({hours:V.number(),minutes:V.number(),totalMinutes:V.number()}),Xh=V.object({filesChanged:V.number().nullable().optional(),linesAdded:V.number().nullable().optional(),linesRemoved:V.number().nullable().optional(),commits:V.number().nullable().optional()}),Qh=V.object({description:V.string(),type:Kh.optional()}),Zh=V.object({lintStatus:gu.nullable().optional(),lintDetails:V.string().optional(),testStatus:gu.nullable().optional(),testDetails:V.string().optional()}),ey=V.object({hash:V.string().optional(),message:V.string().optional(),branch:V.string().optional()}),ty=V.object({id:V.string(),name:V.string(),version:V.string().nullable().optional(),type:qh,agent:V.string().optional(),description:V.string().optional(),changes:V.array(Qh).optional(),codeSnippets:V.array(V.string()).optional(),commit:ey.optional(),codeMetrics:Xh.optional(),qualityMetrics:Zh.optional(),quantitativeImpact:V.string().optional(),duration:Yh.optional(),tasksCompleted:V.number().nullable().optional(),shippedAt:V.string(),featureId:V.string().optional()}),fu=V.object({shipped:V.array(ty),lastUpdated:V.string()})});import{z as x}from"zod";var ny,yu,sy,ry,oy,Fi,wu,iy,ay,Su,hu,cy,ly,ku,bu,Pu,uy,dy,nT,Er=w(()=>{"use strict";Es();ny=x.enum(["low","medium","high","critical"]),yu=x.enum(["feature","bug","improvement","chore"]),sy=x.enum(["active","backlog","previously_active"]),ry=x.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),oy=x.enum(["task_completed","feature_shipped","idea_captured","session_started"]),Fi=x.object({title:x.string(),description:x.string(),filesChanged:x.array(x.object({path:x.string(),action:x.enum(["created","modified","deleted"])})),whatWasDone:x.array(x.string()).min(1),outputForNextAgent:x.string().min(1),notes:x.string().optional()}),wu=x.object({output:x.string().min(1,"Subtask output is required"),summary:Fi}),iy=x.object({id:x.string(),description:x.string(),domain:x.string(),agent:x.string(),status:ry,dependsOn:x.array(x.string()),startedAt:x.string().optional(),completedAt:x.string().optional(),output:x.string().optional(),summary:Fi.optional(),skipReason:x.string().optional(),blockReason:x.string().optional(),estimatedPoints:x.number().optional(),estimatedMinutes:x.number().optional()}),ay=x.object({completed:x.number(),total:x.number(),percentage:x.number()}),Su=x.object({id:x.string(),description:x.string(),startedAt:x.string(),sessionId:x.string(),featureId:x.string().optional(),subtasks:x.array(iy).optional(),currentSubtaskIndex:x.number().optional(),subtaskProgress:ay.optional(),linearId:x.string().optional(),linearUuid:x.string().optional(),estimatedPoints:x.number().optional(),estimatedMinutes:x.number().optional(),modelMetadata:Ts.optional()}),hu=x.object({id:x.string(),description:x.string(),status:x.literal("paused"),startedAt:x.string(),pausedAt:x.string(),pauseReason:x.string().optional()}),cy=x.object({stackConfirmed:x.array(x.string()).optional(),patternsDiscovered:x.array(x.string()).optional(),agentAccuracy:x.array(x.object({agent:x.string(),rating:x.enum(["helpful","neutral","inaccurate"]),note:x.string().optional()})).optional(),issuesEncountered:x.array(x.string()).optional()}),ly=x.object({taskId:x.string(),title:x.string(),classification:yu,startedAt:x.string(),completedAt:x.string(),subtaskCount:x.number(),subtaskSummaries:x.array(Fi),outcome:x.string(),branchName:x.string(),linearId:x.string().optional(),linearUuid:x.string().optional(),prUrl:x.string().optional(),feedback:cy.optional()}),ku=x.object({currentTask:Su.nullable(),previousTask:hu.nullable().optional(),pausedTasks:x.array(hu).optional(),taskHistory:x.array(ly).optional(),lastUpdated:x.string()}),bu=x.object({id:x.string(),description:x.string(),priority:ny,type:yu,featureId:x.string().optional(),originFeature:x.string().optional(),completed:x.boolean(),completedAt:x.string().optional(),createdAt:x.string(),section:sy,agent:x.string().optional(),groupName:x.string().optional(),groupId:x.string().optional()}),Pu=x.object({tasks:x.array(bu),lastUpdated:x.string()}),uy=x.object({tasksToday:x.number(),tasksThisWeek:x.number(),streak:x.number(),velocity:x.string(),avgDuration:x.string()}),dy=x.object({type:oy,description:x.string(),timestamp:x.string(),duration:x.string().optional()}),nT=x.object({projectId:x.string(),currentTask:Su.nullable(),queue:x.array(bu),stats:uy,recentActivity:x.array(dy),lastSync:x.string()})});import{z as Q}from"zod";var py,my,Cu,iT,aT,cT,qt,xu,Un=w(()=>{"use strict";py=Q.enum(["improving","stable","declining"]),my=Q.object({sprintNumber:Q.number(),startDate:Q.string(),endDate:Q.string(),pointsCompleted:Q.number(),tasksCompleted:Q.number(),avgVariance:Q.number(),estimationAccuracy:Q.number()}),Cu=Q.object({category:Q.string(),avgVariance:Q.number(),taskCount:Q.number()}),iT=Q.object({totalPoints:Q.number(),sprints:Q.number(),estimatedDate:Q.string()}),aT=Q.object({sprints:Q.array(my),averageVelocity:Q.number(),velocityTrend:py,estimationAccuracy:Q.number(),overEstimated:Q.array(Cu),underEstimated:Q.array(Cu),lastUpdated:Q.string()}),cT=Q.object({sprintLengthDays:Q.number().min(1).max(90).default(7),startDay:Q.enum(["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]).default("monday"),windowSize:Q.number().min(1).max(52).default(6),accuracyTolerance:Q.number().min(0).max(100).default(20)}),qt={sprintLengthDays:7,startDay:"monday",windowSize:6,accuracyTolerance:20},xu={sprints:[],averageVelocity:0,velocityTrend:"stable",estimationAccuracy:0,overEstimated:[],underEstimated:[],lastUpdated:""}});var yt=w(()=>{"use strict";Bl();Ai();Ms();Di();Ri();xr();Es();$i();uu();du();pu();mu();Oi();Er();Un()});var ln,_i=w(()=>{"use strict";yt();On();se();Rs();ln=class extends cn{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(I),t={};for(let n of e)t[n]=[];return t}_normalizeIndex(e){let t=Object.values(I);for(let n of t)e.index[n]||(e.index[n]=[])}_coerceTags(e){let t=new Set(Object.values(I));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=k(),u={id:oe(),title:t,content:n,tags:a,userTriggered:o,createdAt:c,updatedAt:c};i.memories.push(u);for(let d of a)i.index[d].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(d=>d!==t);for(let u of c)s.index[u].push(t);i.tags=c}return i.updatedAt=k(),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 p of i.tags||[])c.includes(p)&&(a+=10);let d=(Date.now()-new Date(i.updatedAt).getTime())/(1e3*60*60*24);a+=Math.max(0,5-d),i.userTriggered&&(a+=5);let m=this._extractKeywords(t);for(let p of m)i.content.toLowerCase().includes(p)&&(a+=2),i.title.toLowerCase().includes(p)&&(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(p=>{let g={domainMatch:0,tagMatch:0,recency:0,confidence:0,keywords:0,userTriggered:0};if(t.taskDomain&&(g.domainMatch=this._getSemanticDomainScore(t.taskDomain,p.tags||[])),t.commandName){let D=this._getCommandTags(t.commandName),j=(p.tags||[]).filter(q=>D.includes(q));g.tagMatch=Math.min(20,j.length*8)}let S=(Date.now()-new Date(p.updatedAt).getTime())/(1e3*60*60*24);if(g.recency=Math.max(0,Math.round(15-S*.5)),p.confidence?g.confidence=p.confidence==="high"?20:p.confidence==="medium"?12:5:p.observationCount&&(g.confidence=Math.min(20,p.observationCount*3)),t.taskDescription){let D=this._extractKeywordsFromText(t.taskDescription),j=0;for(let q of D)p.content.toLowerCase().includes(q)&&(j+=2),p.title.toLowerCase().includes(q)&&(j+=3);g.keywords=Math.min(15,j)}p.userTriggered&&(g.userTriggered=5);let b=g.domainMatch+g.tagMatch+g.recency+g.confidence+g.keywords+g.userTriggered;return{...p,relevanceScore:b,scoreBreakdown:g}}).filter(p=>p.relevanceScore>=i),d=c.sort((p,g)=>g.relevanceScore-p.relevanceScore).slice(0,o),m=d.length>0?Math.round(d.reduce((p,g)=>p+g.relevanceScore,0)/d.length):0;return{memories:d,metrics:{totalMemories:s,memoriesConsidered:c.length,memoriesReturned:d.length,filteringRatio:s>0?d.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=xi[a];if(c)for(let u of c)s.add(u)}let o=new Set;for(let a of n){let c=Pr[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 vi(e)}_getCommandTags(e){return{ship:[I.COMMIT_STYLE,I.SHIP_WORKFLOW,I.TEST_BEHAVIOR],feature:[I.ARCHITECTURE,I.CODE_STYLE],done:[I.SHIP_WORKFLOW],analyze:[I.TECH_STACK,I.ARCHITECTURE],spec:[I.ARCHITECTURE,I.CODE_STYLE],task:[I.BRANCH_NAMING,I.CODE_STYLE],sync:[I.TECH_STACK,I.ARCHITECTURE,I.DEPENDENCIES],test:[I.TEST_BEHAVIOR],bug:[I.CODE_STYLE,I.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:[I.COMMIT_STYLE,I.SHIP_WORKFLOW,I.TEST_BEHAVIOR],feature:[I.ARCHITECTURE,I.CODE_STYLE],done:[I.SHIP_WORKFLOW],analyze:[I.TECH_STACK,I.ARCHITECTURE],spec:[I.ARCHITECTURE,I.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:[I.COMMIT_STYLE],branch_naming:[I.BRANCH_NAMING],test_before_ship:[I.TEST_BEHAVIOR,I.SHIP_WORKFLOW],preferred_agent:[I.AGENT_PREFERENCE],code_style:[I.CODE_STYLE],verbosity:[I.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?`
|
|
258
|
+
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 Ni,gy,de,Hn=w(()=>{"use strict";Rs();Ti();_i();Rs();Ti();_i();Ni=class{static{l(this,"MemorySystem")}_semanticMemories;_patternStore;_historyStore;_sessionStore;constructor(){this._semanticMemories=new ln,this._patternStore=new js,this._historyStore=new Ds,this._sessionStore=new Is}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()}},gy=new Ni,de=gy});import{exec as fy}from"node:child_process";import tt from"node:fs/promises";import wt from"node:path";import{promisify as hy}from"node:util";var un,Li,yy,Ie,vu=w(()=>{"use strict";O();un=hy(fy),Li=class{static{l(this,"CodebaseAnalyzer")}projectPath=null;init(e=process.cwd()){this.projectPath=e}async readPackageJson(){try{let e=wt.join(this.projectPath,"package.json"),t=await tt.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(C(e)||e instanceof SyntaxError)return null;throw e}}async readCargoToml(){try{let e=wt.join(this.projectPath,"Cargo.toml");return await tt.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readRequirements(){try{let e=wt.join(this.projectPath,"requirements.txt");return await tt.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readGoMod(){try{let e=wt.join(this.projectPath,"go.mod");return await tt.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readGemfile(){try{let e=wt.join(this.projectPath,"Gemfile");return await tt.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readMixExs(){try{let e=wt.join(this.projectPath,"mix.exs");return await tt.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readPomXml(){try{let e=wt.join(this.projectPath,"pom.xml");return await tt.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readComposerJson(){try{let e=wt.join(this.projectPath,"composer.json"),t=await tt.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(C(e)||e instanceof SyntaxError)return null;throw e}}async readPyprojectToml(){try{let e=wt.join(this.projectPath,"pyproject.toml");return await tt.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async getFileExtensions(){try{let{stdout:e}=await un('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(`
|
|
259
|
+
`).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 tt.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(C(e))return[];throw e}}async listDirectories(){try{return(await tt.readdir(this.projectPath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).filter(t=>!t.startsWith(".")&&t!=="node_modules")}catch(e){if(C(e))return[];throw e}}async getGitLog(e=50){try{let{stdout:t}=await un(`git log -n ${e} --pretty=format:"%h|%an|%ar|%s"`,{cwd:this.projectPath});return t}catch{return""}}async getGitStats(){try{let{stdout:e}=await un("git rev-list --count HEAD",{cwd:this.projectPath}),{stdout:t}=await un('git log --format="%an" | sort -u | wc -l',{cwd:this.projectPath}),{stdout:n}=await un('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 un('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 tt.access(wt.join(this.projectPath,e)),!0}catch(t){if(C(t))return!1;throw t}}async readFile(e){try{let t=wt.join(this.projectPath,e);return await tt.readFile(t,"utf-8")}catch(t){if(C(t))return null;throw t}}async findFiles(e){try{let{stdout:t}=await un(`find . -type f -name "${e}" ! -path "*/node_modules/*" ! -path "*/.git/*"`,{cwd:this.projectPath});return t.trim().split(`
|
|
260
|
+
`).filter(Boolean)}catch{return[]}}},yy=new Li,Ie=yy});import{z as ie}from"zod";function wy(r){return r instanceof zn}function K(r){return wy(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var Gn,tE,nE,sE,rE,oE,iE,zn,Ar,Ir,Os,Ut=w(()=>{"use strict";Gn={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}},tE=Gn.create("FileError",ie.object({path:ie.string(),operation:ie.enum(["read","write","delete","create","copy"]),reason:ie.string().optional()})),nE=Gn.create("ValidationError",ie.object({field:ie.string(),expected:ie.string(),received:ie.string().optional(),message:ie.string().optional()})),sE=Gn.create("PermissionError",ie.object({action:ie.string(),resource:ie.string(),reason:ie.string().optional()})),rE=Gn.create("TaskError",ie.object({taskId:ie.string().optional(),operation:ie.enum(["create","update","complete","pause","resume","delete"]),reason:ie.string()})),oE=Gn.create("SessionError",ie.object({sessionId:ie.string().optional(),reason:ie.string()})),iE=Gn.create("SyncError",ie.object({projectId:ie.string().optional(),operation:ie.enum(["push","pull","auth","connect"]),reason:ie.string()})),zn=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)}},Ar=class r extends zn{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")}},Ir=class r extends zn{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")}},Os=class r extends zn{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(wy,"isPrjctError");l(K,"getErrorMessage")});import Ui from"node:fs";import Rr from"node:path";function Tu(){if(Fs)return Fs;let r=__dirname;for(let e=0;e<5;e++){let t=Rr.join(r,"package.json");if(Ui.existsSync(t))try{if(JSON.parse(Ui.readFileSync(t,"utf-8")).name==="prjct-cli")return Fs=r,r}catch{}r=Rr.dirname(r)}return Fs=Rr.join(__dirname,"..","..",".."),Fs}function ky(){if(Dr)return Dr;try{let r=Rr.join(Tu(),"package.json"),e=JSON.parse(Ui.readFileSync(r,"utf-8"));return Dr=e.version,Sy=e,Dr}catch(r){return console.error("Failed to read version from package.json:",y(r)),"0.0.0"}}var Dr,Sy,Fs,Wn,ke,dn=w(()=>{"use strict";O();Dr=null,Sy=null,Fs=null;l(Tu,"getPackageRoot");l(ky,"getVersion");Wn=ky(),ke=Tu()});import zi from"node:fs";import by from"node:fs/promises";import jr from"node:path";function Gi(){if(Eu)return Hi;Eu=!0;let r=jr.join(ke,"dist","templates.json");try{let e=zi.readFileSync(r,"utf-8");return Hi=JSON.parse(e),Hi}catch{return null}}function Cy(r){let e=pn.indexOf(r);e>-1&&pn.splice(e,1),pn.push(r)}function xy(){for(;Bn.size>=Py&&pn.length>0;){let r=pn.shift();r&&Bn.delete(r)}}function $r(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(`
|
|
261
|
+
`).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(d=>d.trim()):o[a.trim()]=u.replace(/^["']|["']$/g,"")}}),{frontmatter:o,content:s.trim()}}async function Au(r){if(Bn.has(r))return Cy(r),Bn.get(r);let e,t=Gi();if(t){let s=`commands/${r}.md`;e=t[s]}if(!e){let s=jr.join(ke,"templates","commands",`${r}.md`);try{e=await by.readFile(s,"utf-8")}catch{throw Ir.notFound(r)}}let n=$r(e);return xy(),Bn.set(r,n),pn.push(r),n}async function vy(r){return(await Au(r)).frontmatter["allowed-tools"]||[]}function Ty(){Bn.clear(),pn.length=0}function ve(r){let e=Gi();if(e?.[r])return e[r];let t=jr.join(ke,"templates",r);try{return zi.readFileSync(t,"utf-8")}catch{return null}}function Vn(r){let e=Gi();if(e)return Object.keys(e).filter(n=>n.startsWith(r));let t=jr.join(ke,"templates",r);try{return zi.readdirSync(t).map(s=>`${r}${s}`)}catch{return[]}}var Py,Bn,pn,Hi,Eu,Ey,Wi,Jn=w(()=>{"use strict";Ut();dn();Py=50,Bn=new Map,pn=[],Hi=null,Eu=!1;l(Gi,"loadBundle");l(Cy,"updateLruOrder");l(xy,"evictLru");l($r,"parseFrontmatter");l(Au,"load");l(vy,"getAllowedTools");l(Ty,"clearCache");l(ve,"getTemplateContent");l(Vn,"listTemplates");Ey={load:Au,parseFrontmatter:$r,getAllowedTools:vy,clearCache:Ty,getTemplateContent:ve,listTemplates:Vn},Wi=Ey});import W from"node:fs/promises";import Vi from"node:os";import J from"node:path";async function Ay(){try{let r=ve("global/modules/module-config.json");if(r)return JSON.parse(r);let e=J.join(ke,"templates/global/modules/module-config.json"),t=await W.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async function Iy(r){let e=await Ay();if(!e){let i=ve("global/CLAUDE.md");if(i)return i;let a=J.join(ke,"templates/global/CLAUDE.md");return W.readFile(a,"utf-8")}let t=r||e.default,n=e.profiles[t];if(!n&&!e.profiles[e.default]){let a=ve("global/CLAUDE.md");if(a)return a;let c=J.join(ke,"templates/global/CLAUDE.md");return W.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=ve(`global/modules/${i}`);if(a)o.push(""),o.push(a);else try{let c=J.join(ke,"templates/global/modules",i),u=await W.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(`
|
|
262
|
+
`)}async function Dy(){try{let r=J.join(Vi.homedir(),".prjct-cli","docs");await W.mkdir(r,{recursive:!0});let e=Vn("global/docs/");if(e.length>0){for(let s of e)if(s.endsWith(".md")){let o=ve(s);if(o){let i=J.basename(s);await W.writeFile(J.join(r,i),o,"utf-8")}}return{success:!0}}let t=J.join(ke,"templates/global/docs"),n=await W.readdir(t);for(let s of n)if(s.endsWith(".md")){let o=J.join(t,s),i=J.join(r,s),a=await W.readFile(o,"utf-8");await W.writeFile(i,a,"utf-8")}return{success:!0}}catch(r){return{success:!1,error:y(r)}}}async function Ry(){let r=(Ve(),at(et)),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 W.mkdir(e.configDir,{recursive:!0});let s=J.join(e.configDir,e.contextFile),o=J.join(ke,"templates","global",e.contextFile),i="";try{let u=ve(`global/${e.contextFile}`);u?i=u:i=await W.readFile(o,"utf-8")}catch{if(t==="claude")try{i=await Iy()}catch{let d=ve("global/CLAUDE.md");if(d)i=d;else{let m=J.join(ke,"templates/global/CLAUDE.md");i=await W.readFile(m,"utf-8")}}else{let d=ve("global/CLAUDE.md");if(d)i=d;else{let m=J.join(ke,"templates/global/CLAUDE.md");i=await W.readFile(m,"utf-8")}t==="gemini"&&(i=i.replace(/Claude/g,"Gemini"))}}let a="",c=!1;try{a=await W.readFile(s,"utf-8"),c=!0}catch(u){if(C(u))c=!1;else throw u}if(c){let u="<!-- prjct:start - DO NOT REMOVE THIS MARKER -->",d="<!-- prjct:end - DO NOT REMOVE THIS MARKER -->";if(a.includes(u)&&a.includes(d)){let p=a.substring(0,a.indexOf(u)),g=a.substring(a.indexOf(d)+d.length),f=i.substring(i.indexOf(u),i.indexOf(d)+d.length),S=p+f+g;return await W.writeFile(s,S,"utf-8"),{success:!0,action:"updated",path:s}}else{let p=`${a}
|
|
263
|
+
|
|
264
|
+
${i}`;return await W.writeFile(s,p,"utf-8"),{success:!0,action:"appended",path:s}}}else return await W.writeFile(s,i,"utf-8"),{success:!0,action:"created",path:s}}catch(s){return{success:!1,error:y(s),action:"failed"}}}function Iu(){let r=Vi.homedir();return{claude:{commands:J.join(r,".claude","commands","p"),config:J.join(r,".claude"),router:J.join(r,".claude","commands","p.md")},gemini:{commands:J.join(r,".gemini","commands"),config:J.join(r,".gemini"),router:J.join(r,".gemini","commands","p.toml")}}}var Bi,jy,Le,mn=w(()=>{"use strict";Jn();O();dn();l(Ay,"loadModuleConfig");l(Iy,"composeGlobalTemplate");l(Dy,"installDocs");l(Ry,"installGlobalConfig");Bi=class{static{l(this,"CommandInstaller")}homeDir;claudeCommandsPath="";claudeConfigPath="";templatesDir;_initialized=!1;constructor(){this.homeDir=Vi.homedir(),this.templatesDir=J.join(ke,"templates","commands")}async ensureInit(){if(this._initialized)return;let t=await(Ve(),at(et)).getActiveProvider();t.name==="gemini"?this.claudeCommandsPath=J.join(t.configDir,"commands"):this.claudeCommandsPath=J.join(t.configDir,"commands","p"),this.claudeConfigPath=t.configDir,this._initialized=!0}async detectActiveProvider(){await this.ensureInit();try{return await W.access(this.claudeConfigPath),!0}catch(e){if(C(e))return!1;throw e}}async detectClaude(){return this.detectActiveProvider()}async getCommandFiles(){let e=new Set(["p.md","p.toml"]),t=Vn("commands/");if(t.length>0)return t.filter(n=>n.endsWith(".md")).map(n=>n.replace("commands/","")).filter(n=>!e.has(n));try{return(await W.readdir(this.templatesDir)).filter(s=>s.endsWith(".md")&&!e.has(s))}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(Ve(),at(et)).getActiveProvider();if(!e)return{success:!1,error:`${n.displayName} not detected. Please install it first.`};try{await this.installRouter(),await W.mkdir(this.claudeCommandsPath,{recursive:!0});let s=await this.getCommandFiles(),o=[],i=[];for(let a of s)try{let c=J.join(this.claudeCommandsPath,a),u=ve(`commands/${a}`);if(u)await W.writeFile(c,u,"utf-8");else{let d=J.join(this.templatesDir,a),m=await W.readFile(d,"utf-8");await W.writeFile(c,m,"utf-8")}o.push(a.replace(".md",""))}catch(c){i.push({file:a,error:y(c)})}return{success:!0,installed:o,errors:i,path:this.claudeCommandsPath}}catch(s){return{success:!1,error:y(s)}}}async uninstallCommands(){try{let e=await this.getCommandFiles(),t=[],n=[];for(let s of e)try{let o=J.join(this.claudeCommandsPath,s);await W.unlink(o),t.push(s.replace(".md",""))}catch(o){o.code!=="ENOENT"&&n.push({file:s,error:y(o)})}try{await W.rmdir(this.claudeCommandsPath)}catch{}return{success:!0,uninstalled:t,errors:n}}catch(e){return{success:!1,error:y(e)}}}async checkInstallation(){if(!await this.detectClaude())return{installed:!1,claudeDetected:!1};try{await W.access(this.claudeCommandsPath);let n=(await W.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(C(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(ve(`commands/${e}.md`))return!0;try{let n=J.join(this.templatesDir,`${e}.md`);return await W.access(n),!0}catch(n){if(C(n))return!1;throw n}}async installRouter(){let t=await(Ve(),at(et)).getActiveProvider(),n=t.name==="gemini"?"p.toml":"p.md";try{let s=J.join(t.configDir,"commands",n);await W.mkdir(J.dirname(s),{recursive:!0});let o=ve(`commands/${n}`);if(o)return await W.writeFile(s,o,"utf-8"),!0;let i=J.join(this.templatesDir,n),a=await W.readFile(i,"utf-8");return await W.writeFile(s,a,"utf-8"),!0}catch(s){if(C(s))return!1;throw s}}async removeLegacyCommands(){let t=await(Ve(),at(et)).getActiveProvider(),n=J.join(t.configDir,"commands"),s=0;try{let i=(await W.readdir(n)).filter(a=>a.startsWith("p.")&&a.endsWith(".md"));for(let a of i)try{await W.unlink(J.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 W.mkdir(this.claudeCommandsPath,{recursive:!0});let t=await this.getCommandFiles(),n=[];try{n=await W.readdir(this.claudeCommandsPath),n=n.filter(o=>o.endsWith(".md"))}catch(o){if(C(o))n=[];else throw o}let s={success:!0,added:0,updated:0,removed:0,errors:[]};for(let o of t)try{let i=J.join(this.claudeCommandsPath,o),a=n.includes(o),c=ve(`commands/${o}`);if(c)await W.writeFile(i,c,"utf-8");else{let u=J.join(this.templatesDir,o),d=await W.readFile(u,"utf-8");await W.writeFile(i,d,"utf-8")}a?s.updated++:s.added++}catch(i){s.errors.push({file:o,error:y(i)})}return await this.removeLegacyCommands(),s}catch(t){return{success:!1,error:y(t),added:0,updated:0,removed:0}}}async installGlobalConfig(){return Ry()}async installDocs(){return Dy()}};l(Iu,"getProviderPaths");jy=new Bi,Le=jy});import{z as we}from"zod";function $u(r,e="default"){let t=Du[e]||Du.default;return r/1e3*t}function Mr(r){return r<.01?`$${(r*100).toFixed(2)}\xA2`:`$${r.toFixed(2)}`}var $y,My,Ru,ju,Du,Or=w(()=>{"use strict";$y=we.object({date:we.string(),tokensSaved:we.number(),syncs:we.number(),avgCompressionRate:we.number(),totalDuration:we.number()}),My=we.object({agentName:we.string(),usageCount:we.number(),tokensSaved:we.number()}),Ru=we.object({totalTokensSaved:we.number(),avgCompressionRate:we.number(),syncCount:we.number(),watchTriggers:we.number(),avgSyncDuration:we.number(),totalSyncDuration:we.number(),agentUsage:we.array(My),dailyStats:we.array($y),firstSync:we.string(),lastUpdated:we.string()}),ju={totalTokensSaved:0,avgCompressionRate:0,syncCount:0,watchTriggers:0,avgSyncDuration:0,totalSyncDuration:0,agentUsage:[],dailyStats:[],firstSync:"",lastUpdated:""},Du={"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($u,"estimateCostSaved");l(Mr,"formatCost")});function Oy(){return/<!-- prjct:preserve(?::([\w-]+))? -->/g}function Fy(r){let e=[],t=Oy(),n,s=0;for(;(n=t.exec(r))!==null;){let o=n.index,i=n[0],a=n[1]||`section-${s++}`,c=r.indexOf(Ji,o+i.length);if(c===-1)continue;let u=c+Ji.length,d=r.substring(o,u);e.push({id:a,content:d,startIndex:o,endIndex:u})}return e}function qi(r,e){let t=Fy(e);if(t.length===0)return r;let n=r.trimEnd();n+=`
|
|
265
|
+
|
|
266
|
+
---
|
|
267
|
+
|
|
268
|
+
`,n+=`## Your Customizations
|
|
269
|
+
|
|
270
|
+
`,n+=`_The sections below are preserved during sync. Edit freely._
|
|
271
|
+
|
|
272
|
+
`;for(let s of t)n+=s.content,n+=`
|
|
273
|
+
|
|
274
|
+
`;return`${n.trimEnd()}
|
|
275
|
+
`}function Ki(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(`
|
|
276
|
+
`);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(Ji)&&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 Ji,Yi=w(()=>{"use strict";Ji="<!-- /prjct:preserve -->";l(Oy,"createPreserveStartRegex");l(Fy,"extractPreservedSections");l(qi,"mergePreservedSections");l(Ki,"validatePreserveBlocks")});function _s(r){if(!r||typeof r!="object")return!1;let e=r;if(e.code&&_y.has(e.code))return!0;if(e.code&&Ou.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 _r(r){if(!r||typeof r!="object")return!1;let e=r;return!!(e.code&&Ou.has(e.code))}function Mu(r,e,t){let n=Kt.get(r);return n&&n.consecutiveFailures>=e&&n.openedAt?Date.now()-n.openedAt>=t?(Kt.delete(r),!1):!0:!1}function Xi(r,e){let t=Kt.get(r)||{consecutiveFailures:0,openedAt:null};t.consecutiveFailures++,t.consecutiveFailures>=e&&!t.openedAt&&(t.openedAt=Date.now()),Kt.set(r,t)}function Ny(r){Kt.delete(r)}var _y,Ou,Kt,Fr,Fu,Ns,Nr=w(()=>{"use strict";_y=new Set(["EBUSY","EAGAIN","ETIMEDOUT","ECONNRESET","ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),Ou=new Set(["ENOENT","EACCES","EPERM","EISDIR","ENOTDIR","EINVAL"]);l(_s,"isTransientError");l(_r,"isPermanentError");Kt=new Map;l(Mu,"isCircuitOpen");l(Xi,"recordFailure");l(Ny,"recordSuccess");Fr=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(Mu(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 Ny(t),o}catch(o){if(n=o,s++,_r(o))throw Xi(t,this.options.circuitBreakerThreshold),o;if(!(_s(o)&&s<this.options.maxAttempts))throw Xi(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 Xi(t,this.options.circuitBreakerThreshold),n}isTransientError(e){return _s(e)}isCircuitOpen(e){return Mu(e,this.options.circuitBreakerThreshold,this.options.circuitBreakerTimeoutMs)}getCircuitState(e){return Kt.get(e)}resetCircuit(e){Kt.delete(e)}resetAllCircuits(){Kt.clear()}},Fu=new Fr({maxAttempts:3,baseDelayMs:1e3,maxDelayMs:8e3}),Ns=new Fr({maxAttempts:2,baseDelayMs:500,maxDelayMs:2e3})});var _u=w(()=>{"use strict";Yi();Nr()});import{exec as Ly}from"node:child_process";import{promisify as Uy}from"node:util";async function Lr(r){try{let{stdout:e}=await Hy(r,{timeout:5e3});return{success:!0,output:e.trim()}}catch{return{success:!1,output:""}}}async function zy(){let r=await Lr("gh api user --jq .login");return r.success&&r.output||(r=await Lr("git config --global github.user"),r.success&&r.output)?r.output:null}async function Gy(){let r=await Lr("git config user.name");return r.success&&r.output?r.output:null}async function Wy(){let r=await Lr("git config user.email");return r.success&&r.output?r.output:null}async function qn(){let[r,e,t]=await Promise.all([zy(),Gy(),Wy()]);return{github:r,email:t,name:e||r||"Unknown"}}var Hy,Ur=w(()=>{"use strict";Hy=Uy(Ly);l(Lr,"execCommand");l(zy,"detectGitHubUsername");l(Gy,"detectGitName");l(Wy,"detectGitEmail");l(qn,"detect")});import gn from"node:fs/promises";import By from"node:path";import*as Hr from"jsonc-parser";function Nu(r){let e=[],t=Hr.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}: ${Hr.printParseErrorCode(n.error)}`)}return t}var Zi,Vy,R,nt=w(()=>{"use strict";Ut();O();se();dn();Ur();ue();l(Nu,"parseJsonc");Zi=class{static{l(this,"ConfigManager")}async readConfig(e){try{let t=E.getLocalConfigPath(e),n=await gn.readFile(t,"utf-8");return Nu(n)}catch(t){return C(t)||console.warn(`Warning: Could not read config at ${e}: ${K(t)}`),null}}async writeConfig(e,t){let n=E.getLocalConfigPath(e),s=E.getLegacyPrjctPath(e);await gn.mkdir(s,{recursive:!0});let o=JSON.stringify(t,null,2);await gn.writeFile(n,`${o}
|
|
277
|
+
`,"utf-8")}async readGlobalConfig(e){try{let t=E.getGlobalProjectConfigPath(e),n=await gn.readFile(t,"utf-8");return Nu(n)}catch(t){return C(t)||console.warn(`Warning: Could not read global config for ${e}: ${K(t)}`),null}}async writeGlobalConfig(e,t){let n=E.getGlobalProjectConfigPath(e),s=E.getGlobalProjectPath(e);await gn.mkdir(s,{recursive:!0});let o=JSON.stringify(t,null,2);await gn.writeFile(n,`${o}
|
|
278
|
+
`,"utf-8")}async ensureGlobalConfig(e){let t=await this.readGlobalConfig(e);if(!t){let n=k();t={projectId:e,authors:[],version:Wn,lastSync:n},await this.writeGlobalConfig(e,t)}return t}async createConfig(e,t){let n=E.generateProjectId(e),s=E.getGlobalProjectPath(n),o=E.getDisplayPath(s),i=k(),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:Wn,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=k(),await this.writeGlobalConfig(t,n))}validateConfig(e){return!(!e||!e.projectId||!e.dataPath)}async needsMigration(e){if(!await E.hasLegacyStructure(e))return!1;if(!await E.hasConfig(e))return!0;let s=await this.readConfig(e);if(!s||!s.projectId)return!0;let o=E.getGlobalProjectPath(s.projectId);try{return(await gn.readdir(By.join(o,"core"))).length===0}catch(i){return C(i),!0}}async getProjectId(e){let t=await this.readConfig(e);return t?.projectId?t.projectId:E.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=k();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=k(),n.lastSync=s.lastActivity,await this.writeGlobalConfig(e,n))}async getCurrentAuthor(e){let t=await qn(),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=E.generateProjectId(e);return{projectId:n,dataPath:E.getDisplayPath(E.getGlobalProjectPath(n))}}},Vy=new Zi,R=Vy});import zr from"node:fs/promises";import ea from"node:path";var ta,Lu,Uu=w(()=>{"use strict";nt();ue();O();ta=class{static{l(this,"AgentRouter")}projectId=null;projectPath=null;agentsPath=null;async initialize(e){this.projectId=await R.getProjectId(e),this.projectPath=e,this.agentsPath=E.getFilePath(this.projectId,"agents","")}async loadAvailableAgents(){if(!this.agentsPath)return[];try{let e=await zr.readdir(this.agentsPath),t=[];for(let n of e)if(n.endsWith(".md")){let s=n.replace(".md",""),o=await zr.readFile(ea.join(this.agentsPath,n),"utf-8");t.push({name:s,content:o})}return t}catch(e){return C(e)||console.error(`Agent loading error: ${y(e)}`),[]}}async getAgentNames(){return(await this.loadAvailableAgents()).map(t=>t.name)}async loadAgent(e){if(!this.agentsPath)return null;try{let t=ea.join(this.agentsPath,`${e}.md`),n=await zr.readFile(t,"utf-8");return{name:e,content:n}}catch(t){return C(t)||console.error(`Agent load error: ${y(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=ea.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})}
|
|
279
|
+
`;await zr.appendFile(s,o)}catch(s){C(s)||console.error(`Agent usage log error: ${y(s)}`)}}},Lu=ta});import Hu from"node:path";async function Ky(){if(process.env.CLAUDE_AGENT||process.env.ANTHROPIC_CLAUDE||global.mcp||process.env.MCP_AVAILABLE)return!0;let r=process.cwd();if(await M(Hu.join(r,"CLAUDE.md")))return!0;let e=process.env.HOME||process.env.USERPROFILE||"";if(await M(Hu.join(e,".claude")))return!0;let t=process.cwd();return!!(t.includes("/.claude/")||t.includes("/claude-workspace/"))}function Yy(){return{...Jy}}function Xy(){return{...qy}}async function zu(){return Gr||(Gr=await Ky()?Yy():Xy(),Gr)}var Gr,Jy,qy,Gu=w(()=>{"use strict";je();Gr=null,Jy={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}},qy={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(Ky,"isClaudeEnvironment");l(Yy,"getClaudeAgent");l(Xy,"getTerminalAgent");l(zu,"detect")});var Zy,na=w(()=>{Zy=hl({})});var ew,Wr,Kn,Wu=w(()=>{"use strict";Uu();Ut();Gu();Nr();na();ew=["claude"],Wr=class{static{l(this,"AgentService")}agent=null;agentInfo=null;agentRouter;constructor(){this.agentRouter=new Lu}async initialize(){return this.agent?this.agent:await Fu.execute(async()=>{if(this.agentInfo=await zu(),!this.agentInfo?.isSupported)throw Os.notSupported(this.agentInfo?.type??"unknown");let e=this.agentInfo.type;if(!e||!ew.includes(e))throw Os.notSupported(this.agentInfo?.type??"unknown");let{default:t}=await Zy(`../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:`
|
|
280
|
+
AGENTIC EXECUTION:
|
|
281
|
+
- Read: templates/agentic/orchestrator.md
|
|
282
|
+
- Analyze task: "${e}"
|
|
283
|
+
- Available specialists: ${s.join(", ")}
|
|
284
|
+
- Claude decides which agent(s) to use
|
|
285
|
+
- Always prefer specialists over generalist
|
|
286
|
+
- Fragment complex tasks into subtasks
|
|
287
|
+
`}}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}},Kn=new Wr});var Br,Vr,Bu=w(()=>{"use strict";Br=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"}},Vr=new Br});import tw from"node:crypto";import Jr from"node:fs/promises";import Vu from"node:path";function Ju(){return{version:St,lastUpdated:"",checksums:{}}}var St,sa,$e,Ls=w(()=>{"use strict";ue();O();se();le();St="1.0.0";l(Ju,"getDefaultChecksums");sa=class{static{l(this,"IndexStorage")}getIndexPath(e){return Vu.join(E.getGlobalProjectPath(e),"index")}async ensureIndexDir(e){let t=this.getIndexPath(e);return await Jr.mkdir(t,{recursive:!0}),t}async readIndex(e){try{let t=this.getIndexMeta(e,"project-index");if(t!==null)return t.version!==St?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 Ju()}async writeChecksums(e,t){this.setIndexMeta(e,"checksums",t)}async calculateChecksum(e){try{let t=await Jr.readFile(e);return tw.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:St,lastUpdated:k(),scores:t};this.setIndexMeta(e,"file-scores",n)}async clearIndex(e){try{$.getDb(e).prepare("DELETE FROM index_meta").run()}catch{}let t=this.getIndexPath(e);try{let n=await Jr.readdir(t);await Promise.all(n.map(s=>Jr.unlink(Vu.join(t,s))))}catch(n){if(!C(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!==St?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!==St?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=$.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=$.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)}},$e=new sa});var qu,nw,qr,sw,Ku=w(()=>{"use strict";Ls();qu=8e4,nw={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"]},qr=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||qu,[c,u,d]=await Promise.all([$e.readIndex(t),$e.readDomains(t),$e.readCategories(t)]);if(!c||!u||!d)return this.fallbackSelection(c?.relevantFiles||[],n);let m=this.detectTaskDomains(e,u.domains),p=new Set;for(let j of m){let q=d.domainIndex[j]||[];for(let Re of q)p.add(Re)}if(i&&d.domainIndex.general){let j=d.domainIndex.general.slice(0,10);for(let q of j)p.add(q)}let g=c.relevantFiles.filter(j=>p.has(j.path)&&j.score>=o);g.sort((j,q)=>q.score-j.score);let f=0,S=[];for(let j of g){let q=Math.ceil(j.size/this.CHARS_PER_TOKEN);if(f+q>a||S.length>=s)break;S.push(j),f+=q}let b=Math.ceil(c.relevantFiles.reduce((j,q)=>j+q.size,0)/this.CHARS_PER_TOKEN),D=b>0?(b-f)/b:0;return{files:S,domains:m,metrics:{totalFiles:c.relevantFiles.length,selectedFiles:S.length,compressionRate:D,estimatedTokensSaved:b-f}}}detectTaskDomains(e,t){let n=e.toLowerCase(),s=new Set;for(let[o,i]of Object.entries(nw))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 $e.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 $e.readIndex(e);return i?i.relevantFiles.filter(a=>o.has(a.path)):[]}async getFilesDomains(e,t){return $e.getFileCategories(e,t)}fallbackSelection(e,t){let n=t.maxFiles||50,s=t.minScore||30,o=t.tokenBudget||qu,i=e.filter(d=>d.score>=s).sort((d,m)=>m.score-d.score),a=0,c=[];for(let d of i){let m=Math.ceil(d.size/this.CHARS_PER_TOKEN);if(a+m>o||c.length>=n)break;c.push(d),a+=m}let u=Math.ceil(e.reduce((d,m)=>d+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)}},sw=new qr});import Yu from"node:path";var ra,Kr,rw,Xu=w(()=>{"use strict";Ls();se();ra=[{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"}],Kr=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 ra)if(c.test(a)){t.set(u,(t.get(u)||0)+1),n.has(u)||n.set(u,new Set);let d=Yu.dirname(i.path);n.get(u).add(`**/${Yu.basename(d)}/**`)}}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=ra.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=k();for(let o of e){let i=[],a=o.path.toLowerCase();for(let m of t){let p=0;for(let g of m.keywords)a.includes(g.toLowerCase())&&(p+=1);for(let{pattern:g,domain:f}of ra)f===m.name&&g.test(a)&&(p+=2);for(let g of m.filePatterns){let f=g.replace(/\*\*/g,"").replace(/\//g,"");a.includes(f.toLowerCase())&&(p+=1)}p>0&&i.push({domain:m.name,score:p})}i.sort((m,p)=>p.score-m.score);let c=i.length>0?i.slice(0,3).map(m=>m.domain):["general"],u=c[0],d=i.length>0?Math.min(1,i[0].score/5):.1;n.push({path:o.path,categories:c,primaryDomain:u,confidence:d,categorizedAt:s,method:"heuristic"})}return n}async saveToCache(e,t,n){let s=k(),o={version:St,projectId:e,domains:t,discoveredAt:s};await $e.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:St,lastUpdate:s,fileCategories:n,domainIndex:i};await $e.writeCategories(e,a)}async loadFromCache(e){let[t,n]=await Promise.all([$e.readDomains(e),$e.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 $e.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 $e.readCategories(e);if(i){let a=new Set(t.map(p=>p.path)),u=[...i.fileCategories.filter(p=>!a.has(p.path)),...o],d={};for(let p of u)for(let g of p.categories)d[g]||(d[g]=[]),d[g].push(p.path);let m={version:St,lastUpdate:k(),fileCategories:u,domainIndex:d};await $e.writeCategories(e,m)}return o}},rw=new Kr});import oa from"node:path";var ia,ow,iw,Yr,Qu,aa=w(()=>{"use strict";ia=30,ow=[/^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$/],iw=[/^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],Yr=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=ia){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=oa.basename(e.path);for(let n of ow)if(n.test(t)||n.test(e.path))return 20;return 0}calculateNameRelevance(e){let t=oa.basename(e.path);for(let s of iw)if(s.test(t))return 15;let n=oa.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}},Qu=new Yr});function Qr(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 aw[r]}var Y,ca,la,Xr,aw,kt,Zu,Us,Yt=w(()=>{"use strict";Y={GATHERING:"gathering",ANALYZING:"analyzing",PROPOSING:"proposing",PENDING_APPROVAL:"awaiting_approval",APPROVED:"approved",REJECTED:"rejected",EXECUTING:"executing",COMPLETED:"completed",ABORTED:"aborted"},ca=["feature","spec","design","refactor","migrate"],la=["ship","cleanup","git","migrate"],Xr=["Read","Glob","Grep","GetTimestamp","GetDate","GetDateTime"],aw={TOOL_CHECK:5e3,GIT_OPERATION:1e4,GIT_CLONE:6e4,API_REQUEST:3e4,NPM_INSTALL:12e4,WORKFLOW_HOOK:6e4};l(Qr,"getTimeout");kt={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},Zu={HISTORY_MAX:100},Us={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"}});function ua(r,e){return{...Cs[r],...e}}function Zr(r,e,t){return{message:r,hint:e,...t}}var eo=w(()=>{"use strict";fr();fr();l(ua,"getError");l(Zr,"createError")});import{execSync as da}from"node:child_process";var to,pa,no,so,ma=w(()=>{"use strict";eo();to={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"}},pa=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=to[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=to[e],s=t.error||{message:`${e} is not available`,hint:n?.installHint||`Install ${e} and try again`,docs:n?.docs};throw new no(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=to[s];return o?` ${s}: ${o.installHint}`:` ${s}: Install and try again`}).join(`
|
|
288
|
+
`);throw new no({message:`Missing required tools: ${t.join(", ")}`,hint:`Install the following:
|
|
289
|
+
${n}`})}}isAvailable(e){return this.checkTool(e).available}getVersion(e){return this.checkTool(e).version}checkAll(e){let t=e||Object.keys(to),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=da(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:Zr(`${e.name} is not installed or not in PATH`,e.installHint,{docs:e.docs})}}}checkUnknownTool(e){try{return da(`${e} --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}),{available:!0}}catch{try{return da(`${e} -v`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}),{available:!0}}catch{return{available:!1,error:Zr(`${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())}},no=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}},so=new pa});import{exec as cw}from"node:child_process";import{promisify as lw}from"node:util";var ZA,ed=w(()=>{"use strict";Yt();ma();ZA=lw(cw)});var Rt,ga,st,Xt=w(()=>{"use strict";yt();se();le();Rt={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},ga=class{static{l(this,"ArchiveStorage")}archive(e,t){let n=oe(),s=k();return $.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=k();return $.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(oe(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,n,i.reason)}),t.length}getArchived(e,t,n=50){return t?$.query(e,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",t,n):$.query(e,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",n)}getStats(e){let t=$.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=$.get(e,"SELECT * FROM archives WHERE id = ?",t);return n?($.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);$.run(e,"DELETE FROM archives WHERE archived_at < ?",n);let o=this.getTotalCount(e);return s-o}getTotalCount(e){return $.get(e,"SELECT COUNT(*) as count FROM archives")?.count??0}},st=new ga});var ro,Je,fa=w(()=>{"use strict";nt();Xt();le();ro=class{static{l(this,"MemoryService")}async log(e,t,n,s){try{let o=await R.getProjectId(e);if(!o)return;z.appendEvent(o,`memory.${t}`,{...n,author:s})}catch(o){console.error(`Memory log error: ${o instanceof Error?o.message:String(o)}`)}}async getRecent(e,t=100){try{let n=await R.getProjectId(e);return n?z.query(n,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(o=>{let i=JSON.parse(o.data),{author:a,...c}=i;return{timestamp:o.timestamp,action:o.type.replace("memory.",""),data:c,author:a}}):[]}catch(n){return console.error(`Memory read error: ${n instanceof Error?n.message:String(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){try{let s=await R.getProjectId(e);return s?z.query(s,"SELECT type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`memory.${t}`,n).reverse().map(i=>{let a=JSON.parse(i.data),{author:c,...u}=a;return{timestamp:i.timestamp,action:i.type.replace("memory.",""),data:u,author:c}}):[]}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async clear(e){try{let t=await R.getProjectId(e);if(!t)return;z.run(t,"DELETE FROM events WHERE type LIKE 'memory.%'")}catch(t){console.error(`Memory clear error: ${t instanceof Error?t.message:String(t)}`)}}async getRecentEvents(e,t=100){try{return z.query(e,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(s=>{let o=JSON.parse(s.data);return{timestamp:s.timestamp,action:s.type.replace("memory.",""),...o}})}catch(n){return console.error(`Memory read error: ${n instanceof Error?n.message:String(n)}`),[]}}async capEntries(e){try{let n=z.get(e,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(n<=Rt.MEMORY_MAX_ENTRIES)return 0;let s=n-Rt.MEMORY_MAX_ENTRIES,o=z.query(e,"SELECT id, type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?",s);st.archiveMany(e,o.map((a,c)=>({entityType:"memory_entry",entityId:`memory-${a.timestamp||c}`,entityData:{type:a.type,data:JSON.parse(a.data),timestamp:a.timestamp},summary:a.type.replace("memory.",""),reason:"overflow"})));let i=o[o.length-1]?.id;return i!==void 0&&z.run(e,"DELETE FROM events WHERE type LIKE 'memory.%' AND id <= ?",i),s}catch(t){return console.error(`Memory cap error: ${t instanceof Error?t.message:String(t)}`),0}}},Je=new ro});var td=w(()=>{"use strict";ue();je()});import{exec as dw}from"node:child_process";import{promisify as pw}from"node:util";var kI,nd=w(()=>{"use strict";Ls();se();aa();kI=pw(dw)});import fn from"chalk";var sd,mw,gw,bt,rd=w(()=>{"use strict";Ve();sd=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],mw=80,gw={name:"prjct",icon:"\u26A1",signature:"\u26A1 prjct",spinner:{frames:sd,speed:mw},cli:{header:l(()=>`${fn.cyan.bold("\u26A1")} ${fn.cyan("prjct")}`,"header"),footer:l(()=>fn.dim("\u26A1 prjct"),"footer"),spin:l((r,e)=>`${fn.cyan("\u26A1")} ${fn.cyan("prjct")} ${fn.cyan(sd[r%10])} ${fn.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")=>kr(r).commitFooter,"getCommitFooter"),getSignature:l((r="claude")=>kr(r).signature,"getSignature")},bt=gw});import X from"chalk";function yw(){return fw[hw]}var RI,ha,fw,hw,hn,Yn,ya,rt,Qt,ww,Sw,h,yn=w(()=>{"use strict";rd();Yt();eo();eo();RI=bt.spinner.frames,ha=bt.spinner.speed,fw={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}},hw="compact";l(yw,"getTierConfig");hn={success:X.green("\u2713"),fail:X.red("\u2717"),warn:X.yellow("\u26A0"),info:X.blue("\u2139"),debug:X.dim("\u{1F527}"),bullet:X.dim("\u2022"),arrow:X.dim("\u2192"),check:X.green("\u2713"),cross:X.red("\u2717"),spinner:X.cyan("\u25D0")},Yn=null,ya=0,rt=!1,Qt=l((r,e)=>{let t=e??(yw().maxCharsPerLine||kt.FALLBACK_TRUNCATE);return r&&r.length>t?`${r.slice(0,t-1)}\u2026`:r||""},"truncate"),ww=l(()=>process.stdout.isTTY?process.stdout.write(`\r${" ".repeat(kt.CLEAR_WIDTH)}\r`):!0,"clear"),Sw={start(){return rt||console.log(bt.cli.header()),this},end(){return rt||console.log(bt.cli.footer()),this},spin(r){return rt?this:(this.stop(),process.stdout.isTTY?(Yn=setInterval(()=>{process.stdout.write(`\r${bt.cli.spin(ya++,Qt(r,kt.SPINNER_MSG))}`)},ha),this):(process.stdout.write(`${bt.cli.spin(0,Qt(r,kt.SPINNER_MSG))}
|
|
290
|
+
`),this))},done(r,e){if(this.stop(),!rt){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=X.dim(` [${n.join(" | ")}]`))}console.log(`${hn.success} ${Qt(r,kt.DONE_MSG)}${t}`)}return this},fail(r){return this.stop(),console.error(`${hn.fail} ${Qt(r,kt.FAIL_MSG)}`),this},failWithHint(r){this.stop();let e=typeof r=="string"?ua(r):r;return console.error(),console.error(`${hn.fail} ${e.message}`),e.file&&console.error(X.dim(` File: ${e.file}`)),e.hint&&console.error(X.yellow(` \u{1F4A1} ${e.hint}`)),e.docs&&console.error(X.dim(` Docs: ${e.docs}`)),console.error(),this},warn(r){return this.stop(),rt||console.log(`${hn.warn} ${Qt(r,kt.WARN_MSG)}`),this},info(r){return this.stop(),rt||console.log(`${hn.info} ${r}`),this},debug(r){this.stop();let e=process.env.DEBUG==="1"||process.env.DEBUG==="true";return!rt&&e&&console.log(`${hn.debug} ${X.dim(r)}`),this},success(r,e){return this.done(r,e)},list(r,e={}){if(this.stop(),rt)return this;let t=e.bullet||hn.bullet,n=" ".repeat(e.indent||0);for(let s of r)console.log(`${n}${t} ${s}`);return this},table(r,e={}){if(this.stop(),rt||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(X.dim(s)),console.log(X.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(),rt)return this;let t=e.split(`
|
|
291
|
+
`),n=Math.max(r.length,...t.map(o=>o.length)),s="\u2500".repeat(n+2);console.log(X.dim(`\u250C${s}\u2510`)),console.log(`${X.dim("\u2502")} ${X.bold(r.padEnd(n))} ${X.dim("\u2502")}`),console.log(X.dim(`\u251C${s}\u2524`));for(let o of t)console.log(`${X.dim("\u2502")} ${o.padEnd(n)} ${X.dim("\u2502")}`);return console.log(X.dim(`\u2514${s}\u2518`)),this},section(r){return this.stop(),rt?this:(console.log(`
|
|
292
|
+
${X.bold(r)}`),console.log(X.dim("\u2500".repeat(r.length))),this)},stop(){return Yn&&(clearInterval(Yn),Yn=null,ww()),this},step(r,e,t){if(rt)return this;this.stop();let n=X.dim(`[${r}/${e}]`);return process.stdout.isTTY?(Yn=setInterval(()=>{process.stdout.write(`\r${bt.cli.spin(ya++,`${n} ${Qt(t,kt.STEP_MSG)}`)}`)},ha),this):(process.stdout.write(`${bt.cli.spin(0,`${n} ${Qt(t,kt.STEP_MSG)}`)}
|
|
293
|
+
`),this)},progress(r,e,t){if(rt)return this;this.stop();let n=Math.round(r/e*100),s=Math.round(n/10),o=10-s,i=X.cyan("\u2588".repeat(s))+X.dim("\u2591".repeat(o)),a=t?` ${Qt(t,kt.PROGRESS_TEXT)}`:"";return process.stdout.isTTY?(Yn=setInterval(()=>{process.stdout.write(`\r${bt.cli.spin(ya++,`[${i}] ${n}%${a}`)}`)},ha),this):(process.stdout.write(`${bt.cli.spin(0,`[${i}] ${n}%${a}`)}
|
|
294
|
+
`),this)}},h=Sw});function bw(){let r=process.env.PRJCT_DEBUG||process.env.DEBUG||"";if(!r)return{level:-1,name:"disabled"};if(kw.has(r)||r.includes("prjct"))return{level:Xn.debug,name:"debug"};let e=Xn[r]??-1,t=e>=0?r:"disabled";return{level:e,name:t}}function oo(r,e,t){return od>=r?(...n)=>console[t](e,...n):Cw}var Xn,kw,od,Pw,Cw,xw,B,Qn=w(()=>{"use strict";Xn={error:0,warn:1,info:2,debug:3},kw=new Set(["1","true","*"]);l(bw,"getLogLevel");({level:od,name:Pw}=bw()),Cw=l(()=>{},"noop");l(oo,"createLogMethod");xw={error:oo(Xn.error,"[prjct:error]","error"),warn:oo(Xn.warn,"[prjct:warn]","warn"),info:oo(Xn.info,"[prjct:info]","log"),debug:oo(Xn.debug,"[prjct:debug]","log"),isEnabled:l(()=>od>=0,"isEnabled"),level:l(()=>Pw,"level")},B=xw});var io,vw,id=w(()=>{"use strict";Ut();le();pi();Yt();Qn();io=class{static{l(this,"EventBus")}listeners;onceListeners;history;historyLimit;projectId;constructor(){this.listeners=new Map,this.onceListeners=new Map,this.history=[],this.historyLimit=Zu.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"&&B.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(gr.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(gr.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 B.error("Event callback error:",n),n}}async logEvent(e){try{$.appendEvent(this.projectId,e.type,e)}catch(t){B.debug("Failed to log event:",K(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())}},vw=new io});var ao,co,ad=w(()=>{"use strict";ue();se();je();ao=class{static{l(this,"SyncEventBus")}async publish(e){let t=E.getSyncPendingPath(e.projectId),n=await an(t,[])??[];n.push(e),await vs(t,n)}async getPending(e){let t=E.getSyncPendingPath(e);return await an(t,[])??[]}async clearPending(e){let t=E.getSyncPendingPath(e);await vs(t,[])}async updateLastSync(e){let t=E.getLastSyncPath(e),n={timestamp:k(),success:!0};await vs(t,n)}async getLastSync(e){let t=E.getLastSyncPath(e);return await an(t,null)}},co=new ao});var wa=w(()=>{"use strict";id();ad()});var Pt,lo=w(()=>{"use strict";Pt=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}}});var Te,jt=w(()=>{"use strict";wa();lo();se();le();Te=class{static{l(this,"StorageManager")}filename;cache;constructor(e,t){this.filename=e,this.cache=new Pt({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(e){let t=this.cache.get(e);if(t!==null)return t;try{let n=$.getDoc(e,this.getStoreKey());if(n!==null)return this.cache.set(e,n),n}catch{}return this.getDefault()}async write(e,t){$.setDoc(e,this.getStoreKey(),t),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:k(),projectId:e};await co.publish(s)}async publishEntityEvent(e,t,n,s){let o=`${t}.${n}`,i={...s,timestamp:k()};await this.publishEvent(e,o,i)}async exists(e){try{return $.hasDoc(e,this.getStoreKey())}catch{return!1}}clearCache(e){e?this.cache.delete(e):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});import{createHash as Ew}from"node:crypto";var Sa,$t,uo=w(()=>{"use strict";Ai();se();jt();Sa=class extends Te{static{l(this,"AnalysisStorage")}constructor(){super("analysis.json")}getDefault(){return{draft:null,sealed:null,lastUpdated:""}}getEventType(e){return`analysis.${e}d`}async saveDraft(e,t){let n={...t,status:"draft"};Ei.parse(n),await this.update(e,s=>({...s,draft:n,lastUpdated:k()})),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=k(),o={...t.draft,status:"sealed",signature:n,sealedAt:s};return Ei.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 Vl(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 Ew("sha256").update(JSON.stringify(t)).digest("hex")}},$t=new Sa});var ka,Me,Hs=w(()=>{"use strict";yt();Di();se();Xt();jt();ka=class extends Te{static{l(this,"IdeasStorage")}constructor(){super("ideas.json",Kl)}getDefault(){return{ideas:[],lastUpdated:""}}getEventType(e){return`ideas.${e}d`}async getAll(e){return(await this.read(e)).ideas}async getPending(e){return(await this.read(e)).ideas.filter(n=>n.status==="pending")}async addIdea(e,t,n={}){let s={id:oe(),text:t,status:"pending",priority:n.priority||"medium",tags:n.tags||[],addedAt:k()};return await this.update(e,o=>({ideas:[s,...o.ideas],lastUpdated:k()})),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:k()})),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:k()})),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:k()}))}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:k()}))}async removeIdea(e,t){await this.update(e,n=>({ideas:n.ideas.filter(s=>s.id!==t),lastUpdated:k()}))}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:k()})),{removed:i}}async markDormantIdeas(e){let t=await this.read(e),n=Bt(Rt.IDEA_DORMANT_DAYS),s=t.ideas.filter(i=>i.status==="pending"&&new Date(i.addedAt)<n);if(s.length===0)return 0;st.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:k()})),await this.publishEvent(e,"ideas.dormant",{count:s.length}),s.length}},Me=new ka});var ba,wn,po=w(()=>{"use strict";Or();se();jt();ba=class extends Te{static{l(this,"MetricsStorage")}constructor(){super("metrics.json",Ru)}getDefault(){return{...ju}}getEventType(e){return`metrics.${e}d`}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,d=i.syncCount===0?s:(i.avgCompressionRate*i.syncCount+s)/a,m=[...i.dailyStats],p=m.findIndex(D=>D.date===o);if(p>=0){let D=m[p];m[p]={...D,tokensSaved:D.tokensSaved+n,syncs:D.syncs+1,avgCompressionRate:(D.avgCompressionRate*D.syncs+s)/(D.syncs+1),totalDuration:D.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(D=>D.date>=f),b=[...i.agentUsage];if(t.agents)for(let D of t.agents){let j=b.findIndex(q=>q.agentName===D);j>=0?b[j]={...b[j],usageCount:b[j].usageCount+1,tokensSaved:b[j].tokensSaved+Math.floor(n/t.agents.length)}:b.push({agentName:D,usageCount:1,tokensSaved:Math.floor(n/t.agents.length)})}return{totalTokensSaved:c,avgCompressionRate:d,syncCount:a,watchTriggers:i.watchTriggers+(t.isWatch?1:0),avgSyncDuration:u/a,totalSyncDuration:u,agentUsage:b,dailyStats:S,firstSync:i.firstSync||k(),lastUpdated:k()}})}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:$u(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)}},wn=new ba});import We from"node:fs/promises";import ne from"node:path";async function zs(r){let e=Date.now(),t={success:!1,migratedFiles:[],skippedFiles:[],errors:[],backupDir:null,duration:0};try{if($.exists(r)&&$.hasDoc(r,"state"))return t.success=!0,t.duration=Date.now()-e,t;let n=E.getGlobalProjectPath(r),s=ne.join(n,"storage"),o=ne.join(n,"index"),i=ne.join(n,"memory");t.backupDir=await Aw(s,o,i),$.getDb(r);for(let{filename:a,key:c}of xa){let u=ne.join(s,a),d=await Sn(u);if(d===null){t.skippedFiles.push(a);continue}try{$.setDoc(r,c,d),cd(r,c,d),t.migratedFiles.push(a)}catch(m){t.errors.push({file:a,error:String(m)})}}for(let{filename:a,key:c}of Ca){let u=ne.join(o,a),d=await Sn(u);if(d===null){t.skippedFiles.push(`index/${a}`);continue}try{$.run(r,"INSERT OR REPLACE INTO index_meta (key, data, updated_at) VALUES (?, ?, ?)",c,JSON.stringify(d),new Date().toISOString()),ld(r,c,d),t.migratedFiles.push(`index/${a}`)}catch(m){t.errors.push({file:`index/${a}`,error:String(m)})}}return await Fw(r,o,t),await _w(r,o,t),await Nw(r,i,t),await Lw(r,i,t),t.errors.length===0&&await Uw(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 Aw(r,e,t){let n=ne.join(r,"backup");return await We.mkdir(n,{recursive:!0}),await We.mkdir(ne.join(n,"index"),{recursive:!0}),await We.mkdir(ne.join(n,"memory"),{recursive:!0}),await Pa(r,n,s=>s.endsWith(".json")||s.endsWith(".jsonl")),await Pa(e,ne.join(n,"index")),await Pa(t,ne.join(n,"memory")),n}async function Pa(r,e,t){try{let n=await We.readdir(r,{withFileTypes:!0});for(let s of n){if(!s.isFile()||t&&!t(s.name))continue;let o=ne.join(r,s.name),i=ne.join(e,s.name);await We.copyFile(o,i)}}catch(n){if(!C(n))throw n}}function cd(r,e,t){switch(e){case"state":Iw(r,t);break;case"queue":Dw(r,t);break;case"ideas":Rw(r,t);break;case"shipped":jw(r,t);break;case"metrics":$w(r,t);break;case"analysis":Mw(r,t);break}}function Iw(r,e){let t=$.getDb(r),n=t.prepare(`
|
|
262
295
|
INSERT OR REPLACE INTO tasks
|
|
263
296
|
(id, description, type, status, parent_description, branch, linear_id,
|
|
264
297
|
linear_uuid, session_id, feature_id, started_at, completed_at,
|
|
@@ -269,248 +302,79 @@ ${Oh(e.schema)}`:null}function Oh(r){if(r instanceof De.ZodObject){let e=r.shape
|
|
|
269
302
|
(id, task_id, description, status, domain, agent, sort_order,
|
|
270
303
|
depends_on, started_at, completed_at, output, summary)
|
|
271
304
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
272
|
-
`),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 d=0;d<u.length;d++){let m=u[d];s.run(m.id??`subtask-${d}`,a.id,m.description??"",m.status??"pending",m.domain??null,m.agent??null,d,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
|
|
305
|
+
`),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 d=0;d<u.length;d++){let m=u[d];s.run(m.id??`subtask-${d}`,a.id,m.description??"",m.status??"pending",m.domain??null,m.agent??null,d,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 Dw(r,e){let t=e.tasks;if(!t||!Array.isArray(t))return;let s=$.getDb(r).prepare(`
|
|
273
306
|
INSERT OR REPLACE INTO queue_tasks
|
|
274
307
|
(id, description, type, priority, section, created_at, completed, completed_at,
|
|
275
308
|
feature_id, feature_name)
|
|
276
309
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
277
|
-
`);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
|
|
310
|
+
`);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 Rw(r,e){let t=e.ideas;if(!t||!Array.isArray(t))return;let s=$.getDb(r).prepare(`
|
|
278
311
|
INSERT OR REPLACE INTO ideas
|
|
279
312
|
(id, text, status, priority, tags, added_at, converted_to, details, data)
|
|
280
313
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
281
|
-
`);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
|
|
314
|
+
`);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 jw(r,e){let t=e.shipped;if(!t||!Array.isArray(t))return;let s=$.getDb(r).prepare(`
|
|
282
315
|
INSERT OR REPLACE INTO shipped_features
|
|
283
316
|
(id, name, shipped_at, version, description, type, duration, data)
|
|
284
317
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
285
|
-
`);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
|
|
318
|
+
`);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 $w(r,e){let t=e.dailyStats;if(!t||!Array.isArray(t))return;let s=$.getDb(r).prepare(`
|
|
286
319
|
INSERT OR REPLACE INTO metrics_daily
|
|
287
320
|
(date, tokens_saved, syncs, avg_compression_rate, total_duration)
|
|
288
321
|
VALUES (?, ?, ?, ?, ?)
|
|
289
|
-
`);for(let o of t)s.run(o.date,o.tokensSaved??0,o.syncs??0,o.avgCompressionRate??0,o.totalDuration??0)}function
|
|
322
|
+
`);for(let o of t)s.run(o.date,o.tokensSaved??0,o.syncs??0,o.avgCompressionRate??0,o.totalDuration??0)}function Mw(r,e){let n=$.getDb(r).prepare(`
|
|
290
323
|
INSERT OR REPLACE INTO analysis
|
|
291
324
|
(id, status, commit_hash, signature, sealed_at, analyzed_at, data)
|
|
292
325
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
293
|
-
`),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
|
|
326
|
+
`),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 ld(r,e,t){e==="categories-cache"&&Ow(r,t)}function Ow(r,e){let t=e.fileCategories;if(!t||!Array.isArray(t))return;let s=$.getDb(r).prepare(`
|
|
294
327
|
INSERT OR REPLACE INTO index_files
|
|
295
328
|
(path, categories, domain, score, size, mtime, language)
|
|
296
329
|
VALUES (?, ?, ?, COALESCE((SELECT score FROM index_files WHERE path = ?), 0), NULL, NULL, NULL)
|
|
297
|
-
`);for(let o of t)s.run(o.path,o.categories?JSON.stringify(o.categories):null,o.primaryDomain??null,o.path)}async function
|
|
330
|
+
`);for(let o of t)s.run(o.path,o.categories?JSON.stringify(o.categories):null,o.primaryDomain??null,o.path)}async function Fw(r,e,t){let n=ne.join(e,"checksums.json"),s=await Sn(n);if(s===null){t.skippedFiles.push("index/checksums.json");return}try{let o=s.checksums;if(!o)return;let i=$.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 _w(r,e,t){let n=ne.join(e,"file-scores.json"),s=await Sn(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=$.getDb(r),a=i.prepare(`
|
|
298
331
|
INSERT OR REPLACE INTO index_files
|
|
299
332
|
(path, score, size, mtime, language, categories, domain)
|
|
300
333
|
VALUES (?, ?, ?, ?, NULL,
|
|
301
334
|
COALESCE((SELECT categories FROM index_files WHERE path = ?), NULL),
|
|
302
335
|
COALESCE((SELECT domain FROM index_files WHERE path = ?), NULL))
|
|
303
|
-
`);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
|
|
304
|
-
`).filter(c=>c.trim());if(o.length===0){t.skippedFiles.push("memory/events.jsonl");return}let i
|
|
305
|
-
`).filter(c=>c.trim());if(o.length===0){t.skippedFiles.push("memory/learnings.jsonl");return}let i
|
|
306
|
-
`).filter(f=>f.trim());if(p.length===0){await Je.unlink(d),n++;continue}let g=M.getDb(r);if(u==="events.jsonl"){let f=g.prepare("INSERT INTO events (type, task_id, data, timestamp) VALUES (?, ?, ?, ?)");g.transaction(()=>{for(let S of p)try{let k=JSON.parse(S);f.run(k.type??k.action??"unknown",k.taskId??k.task_id??null,S,k.timestamp??k.ts??new Date().toISOString())}catch{}})()}else{let f=g.prepare("INSERT OR REPLACE INTO memory (key, domain, value, confidence, updated_at) VALUES (?, ?, ?, ?, ?)");g.transaction(()=>{for(let S of p)try{let k=JSON.parse(S),v=`learning:${k.taskId??k.timestamp??Date.now()}`,D=k.tags;f.run(v,D?.[0]??null,S,1,k.timestamp??new Date().toISOString())}catch{}})()}await Je.unlink(d),n++}catch{}}let a=se.join(e,"index"),c=[...ra.map(u=>u.filename),"checksums.json","file-scores.json"];for(let u of c){let d=se.join(a,u),m=await gn(d);if(m===null)continue;let p=ra.find(g=>g.filename===u);p&&(M.run(r,"INSERT OR REPLACE INTO index_meta (key, data, updated_at) VALUES (?, ?, ?)",p.key,JSON.stringify(m),new Date().toISOString()),Zu(r,p.key,m));try{await Je.unlink(d)}catch{}n++}return n}var oa,ra,Qr=y(()=>{"use strict";re();F();de();oa=[{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"}],ra=[{filename:"project-index.json",key:"project-index"},{filename:"domains.json",key:"domains"},{filename:"categories-cache.json",key:"categories-cache"}];l(Bs,"migrateJsonToSqlite");l(Vy,"createBackup");l(sa,"copyFiles");l(Qu,"populateNormalized");l(Jy,"populateTasksFromState");l(qy,"populateQueueTasks");l(Ky,"populateIdeas");l(Yy,"populateShippedFeatures");l(Xy,"populateMetricsDaily");l(Qy,"populateAnalysis");l(Zu,"populateIndexTables");l(Zy,"populateCategoriesIndex");l(ew,"migrateChecksums");l(tw,"migrateFileScores");l(nw,"migrateEventsJsonl");l(sw,"migrateLearningsJsonl");l(rw,"cleanupJsonFiles");l(gn,"readJsonSafe");l(Xr,"sweepLegacyJson")});var ia,ce,Zn=y(()=>{"use strict";bt();Jr();te();tn();Mt();ia=class extends xe{static{l(this,"QueueStorage")}constructor(){super("queue.json",Wu)}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()}]`:"",d=i.agent?` @${i.agent}`:"",m=i.originFeature?` (from: ${i.originFeature})`:"",p=i.type==="bug"?" \u{1F41B}":"";t.push(`${a+1}. ${c}${p}${u} ${i.description}${d}${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(`
|
|
307
|
-
`)}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:ae(),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:ae(),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=Yt(Ot.QUEUE_COMPLETED_DAYS),s=t.tasks.filter(i=>i.completed&&i.completedAt&&new Date(i.completedAt)<n);if(s.length===0)return 0;rt.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()})}},ce=new ia});var aa,He,es=y(()=>{"use strict";bt();Yi();te();tn();Mt();aa=class extends xe{static{l(this,"ShippedStorage")}constructor(){super("shipped.json",_u)}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(`
|
|
308
|
-
`);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=nt(a.shippedAt),u=a.version?` v${a.version}`:"",d=a.duration?` (${a.duration})`:"";t.push(`- **${a.name}**${u}${d} - ${c}`),a.description&&t.push(` _${a.description}_`)}),t.push("")}),t.push("---"),t.push(""),t.push(`**Total shipped:** ${e.shipped.length}`),t.push(""),t.join(`
|
|
309
|
-
`)}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:ae(),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=Yt(Ot.SHIPPED_RETENTION_DAYS),s=t.shipped.filter(i=>new Date(i.shippedAt)<n);if(s.length===0)return 0;rt.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}},He=new aa});function ed(){return new ca}var ca,td=y(()=>{"use strict";ca=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(`
|
|
310
|
-
`)}get length(){return this.lines.length}};l(ed,"md")});var Vs,la,fn,ua=y(()=>{"use strict";Vs={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"}},la=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=Vs[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 Vs[e]}getPrompt(e){return Vs[e].prompt}getValidCommands(e){return Vs[e].transitions}formatNextSteps(e){return Vs[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}`}})}},fn=new la});var da,O,ts=y(()=>{"use strict";bt();Jr();te();td();ua();tn();Mt();da=class extends xe{static{l(this,"StateStorage")}constructor(){super("state.json",Gu)}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 ed().h1("NOW").when(!!e.currentTask,t=>{let n=e.currentTask;if(t.bold(n.description).blank().raw(`Started: ${nt(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: ${nt(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: ${nt(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=fn.getCurrentState(e),s=fn.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,d)=>d!==o),c={id:i.id,description:i.description,startedAt:b(),sessionId:ae()};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[];rt.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(p=>p.feedback),s=[],o=[],i=[],a=[];for(let p of n){let g=p.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)],d=new Map;for(let p of a)d.set(p,(d.get(p)||0)+1);let m=[...d.entries()].filter(([p,g])=>g>=2).map(([p])=>p);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=Uu.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:
|
|
336
|
+
`);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 Nw(r,e,t){let n=ne.join(e,"events.jsonl");try{let o=(await We.readFile(n,"utf-8")).split(`
|
|
337
|
+
`).filter(c=>c.trim());if(o.length===0){t.skippedFiles.push("memory/events.jsonl");return}let i=$.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),d=u.type??u.action??"unknown",m=u.taskId??u.task_id??null,p=u.timestamp??u.ts??new Date().toISOString();a.run(d,m,c,p)}catch{}})(),t.migratedFiles.push("memory/events.jsonl")}catch(s){C(s)?t.skippedFiles.push("memory/events.jsonl"):t.errors.push({file:"memory/events.jsonl",error:String(s)})}}async function Lw(r,e,t){let n=ne.join(e,"learnings.jsonl");try{let o=(await We.readFile(n,"utf-8")).split(`
|
|
338
|
+
`).filter(c=>c.trim());if(o.length===0){t.skippedFiles.push("memory/learnings.jsonl");return}let i=$.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),d=`learning:${u.taskId??u.timestamp??Date.now()}`,m=u.tags,p=m&&m.length>0?m[0]:null;a.run(d,p,c,1,u.timestamp??new Date().toISOString())}catch{}})(),t.migratedFiles.push("memory/learnings.jsonl")}catch(s){C(s)?t.skippedFiles.push("memory/learnings.jsonl"):t.errors.push({file:"memory/learnings.jsonl",error:String(s)})}}async function Uw(r,e,t,n){let s=l(async(i,a)=>{try{await We.unlink(i)}catch(c){C(c)||n.errors.push({file:a,error:`cleanup: ${String(c)}`})}},"deleteFile");for(let{filename:i}of xa)await s(ne.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(ne.join(e,i),`cleanup:index/${i}`);await s(ne.join(t,"events.jsonl"),"cleanup:memory/events.jsonl"),await s(ne.join(t,"learnings.jsonl"),"cleanup:memory/learnings.jsonl")}async function Sn(r){try{let e=await We.readFile(r,"utf-8");return JSON.parse(e)}catch(e){if(C(e)||e instanceof SyntaxError)return null;throw e}}async function mo(r){let e=E.getGlobalProjectPath(r),t=ne.join(e,"storage"),n=0;$.getDb(r);for(let{filename:u,key:d}of xa){let m=ne.join(t,u),p=await Sn(m);if(p!==null){$.setDoc(r,d,p),cd(r,d,p);try{await We.unlink(m)}catch{}n++}}let s=ne.join(e,"project.json"),o=await Sn(s);if(o!==null){$.setDoc(r,"project",o);try{await We.unlink(s)}catch{}n++}let i=ne.join(e,"memory");for(let u of["events.jsonl","learnings.jsonl"]){let d=ne.join(i,u);try{let p=(await We.readFile(d,"utf-8")).split(`
|
|
339
|
+
`).filter(f=>f.trim());if(p.length===0){await We.unlink(d),n++;continue}let g=$.getDb(r);if(u==="events.jsonl"){let f=g.prepare("INSERT INTO events (type, task_id, data, timestamp) VALUES (?, ?, ?, ?)");g.transaction(()=>{for(let S of p)try{let b=JSON.parse(S);f.run(b.type??b.action??"unknown",b.taskId??b.task_id??null,S,b.timestamp??b.ts??new Date().toISOString())}catch{}})()}else{let f=g.prepare("INSERT OR REPLACE INTO memory (key, domain, value, confidence, updated_at) VALUES (?, ?, ?, ?, ?)");g.transaction(()=>{for(let S of p)try{let b=JSON.parse(S),D=`learning:${b.taskId??b.timestamp??Date.now()}`,j=b.tags;f.run(D,j?.[0]??null,S,1,b.timestamp??new Date().toISOString())}catch{}})()}await We.unlink(d),n++}catch{}}let a=ne.join(e,"index"),c=[...Ca.map(u=>u.filename),"checksums.json","file-scores.json"];for(let u of c){let d=ne.join(a,u),m=await Sn(d);if(m===null)continue;let p=Ca.find(g=>g.filename===u);p&&($.run(r,"INSERT OR REPLACE INTO index_meta (key, data, updated_at) VALUES (?, ?, ?)",p.key,JSON.stringify(m),new Date().toISOString()),ld(r,p.key,m));try{await We.unlink(d)}catch{}n++}return n}var xa,Ca,go=w(()=>{"use strict";ue();O();le();xa=[{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"}],Ca=[{filename:"project-index.json",key:"project-index"},{filename:"domains.json",key:"domains"},{filename:"categories-cache.json",key:"categories-cache"}];l(zs,"migrateJsonToSqlite");l(Aw,"createBackup");l(Pa,"copyFiles");l(cd,"populateNormalized");l(Iw,"populateTasksFromState");l(Dw,"populateQueueTasks");l(Rw,"populateIdeas");l(jw,"populateShippedFeatures");l($w,"populateMetricsDaily");l(Mw,"populateAnalysis");l(ld,"populateIndexTables");l(Ow,"populateCategoriesIndex");l(Fw,"migrateChecksums");l(_w,"migrateFileScores");l(Nw,"migrateEventsJsonl");l(Lw,"migrateLearningsJsonl");l(Uw,"cleanupJsonFiles");l(Sn,"readJsonSafe");l(mo,"sweepLegacyJson")});var va,pe,Gs=w(()=>{"use strict";yt();Er();se();Xt();jt();va=class extends Te{static{l(this,"QueueStorage")}constructor(){super("queue.json",Pu)}getDefault(){return{tasks:[],lastUpdated:""}}getEventType(e){return`queue.${e}d`}async getTasks(e){return(await this.read(e)).tasks}async getActiveTasks(e){return(await this.read(e)).tasks.filter(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:oe(),createdAt:k(),completed:!1};return await this.update(e,s=>({tasks:[...s.tasks,n],lastUpdated:k()})),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=k(),s=t.map(o=>({...o,id:oe(),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:k()})),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:k()},n):i),lastUpdated:k()})),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:k()}))}async setPriority(e,t,n){await this.update(e,s=>({tasks:s.tasks.map(o=>o.id===t?{...o,priority:n}:o),lastUpdated:k()}))}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:k()})),n}async removeStaleCompleted(e){let t=await this.read(e),n=Bt(Rt.QUEUE_COMPLETED_DAYS),s=t.tasks.filter(i=>i.completed&&i.completedAt&&new Date(i.completedAt)<n);if(s.length===0)return 0;st.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:k()})),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()})}},pe=new va});var Ta,qe,Ws=w(()=>{"use strict";yt();Oi();se();Xt();jt();Ta=class extends Te{static{l(this,"ShippedStorage")}constructor(){super("shipped.json",fu)}getDefault(){return{shipped:[],lastUpdated:""}}getEventType(e){return`shipped.${e}d`}async getAll(e){return(await this.read(e)).shipped}async getRecent(e,t=5){return(await this.read(e)).shipped.sort((s,o)=>new Date(o.shippedAt).getTime()-new Date(s.shippedAt).getTime()).slice(0,t)}async addShipped(e,t){let n={...t,id:oe(),shippedAt:k()};return await this.update(e,s=>({shipped:[n,...s.shipped],lastUpdated:k()})),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=Bt(Rt.SHIPPED_RETENTION_DAYS),s=t.shipped.filter(i=>new Date(i.shippedAt)<n);if(s.length===0)return 0;st.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:k()})),await this.publishEvent(e,"shipped.archived",{count:s.length,oldestShippedAt:s[s.length-1]?.shippedAt}),s.length}},qe=new Ta});var Bs,Ea,kn,Aa=w(()=>{"use strict";Bs={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"}},Ea=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=Bs[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 Bs[e]}getPrompt(e){return Bs[e].prompt}getValidCommands(e){return Bs[e].transitions}formatNextSteps(e){return Bs[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}`}})}},kn=new Ea});var Ia,F,Vs=w(()=>{"use strict";yt();Er();se();Aa();Xt();jt();Ia=class extends Te{static{l(this,"StateStorage")}constructor(){super("state.json",ku)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],lastUpdated:""}}getEventType(e){return`state.${e}d`}validateTransition(e,t){let n=kn.getCurrentState(e),s=kn.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:k()};return await this.update(e,o=>({...o,currentTask:s,lastUpdated:k()})),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:k()})),s}async completeTask(e,t){let n=await this.read(e),s=n.currentTask;if(!s)return null;this.validateTransition(n,"done");let o=k(),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:k(),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:k()})),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,d)=>d!==o),c={id:i.id,description:i.description,startedAt:k(),sessionId:oe()};return await this.update(e,()=>({currentTask:c,previousTask:null,pausedTasks:a,lastUpdated:k()})),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[];st.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:k()}));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:k()}))}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(p=>p.feedback),s=[],o=[],i=[],a=[];for(let p of n){let g=p.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)],d=new Map;for(let p of a)d.set(p,(d.get(p)||0)+1);let m=[...d.entries()].filter(([p,g])=>g>=2).map(([p])=>p);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?k():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:k()})),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=wu.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:
|
|
311
340
|
${f.join(`
|
|
312
|
-
`)}`)}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:
|
|
313
|
-
|
|
314
|
-
`)}
|
|
315
|
-
|
|
316
|
-
<!-- projectId: ${e} -->
|
|
317
|
-
<!-- Generated: ${new Date().toISOString()} -->
|
|
318
|
-
|
|
319
|
-
## PROJECT DATA
|
|
320
|
-
|
|
321
|
-
### Dependencies (${f.length+S.length})
|
|
322
|
-
|
|
323
|
-
**Production** (${f.length}):
|
|
324
|
-
${f.length>0?f.map(v=>`- ${v}: ${c.dependencies[v]}`).join(`
|
|
325
|
-
`):"_None_"}
|
|
326
|
-
|
|
327
|
-
**Dev** (${S.length}):
|
|
328
|
-
${S.length>0?S.map(v=>`- ${v}: ${c.devDependencies[v]}`).join(`
|
|
329
|
-
`):"_None_"}
|
|
330
|
-
|
|
331
|
-
### Scripts
|
|
332
|
-
|
|
333
|
-
${Object.keys(c.scripts).length>0?Object.entries(c.scripts).map(([v,D])=>`- \`${v}\`: ${D}`).join(`
|
|
334
|
-
`):"_None_"}
|
|
335
|
-
|
|
336
|
-
### Git
|
|
337
|
-
|
|
338
|
-
- Branch: ${a.branch}
|
|
339
|
-
- Commits: ${a.commits}
|
|
340
|
-
- Contributors: ${a.contributors}
|
|
341
|
-
- Uncommitted: ${a.hasChanges?"Yes":"No"}
|
|
342
|
-
|
|
343
|
-
**Recent:**
|
|
344
|
-
${a.recentCommits.length>0?a.recentCommits.slice(0,5).map(v=>`- \`${v.hash}\` ${v.message}`).join(`
|
|
345
|
-
`):"_None_"}
|
|
346
|
-
|
|
347
|
-
---
|
|
348
|
-
|
|
349
|
-
## CURRENT STATE
|
|
350
|
-
|
|
351
|
-
**Now:** ${m?m.description:"_No active task_"}
|
|
352
|
-
|
|
353
|
-
**Queue (${p.length}):**
|
|
354
|
-
${p.length>0?p.slice(0,10).map((v,D)=>`${D+1}. ${v.description}`).join(`
|
|
355
|
-
`):"_Empty_"}
|
|
356
|
-
|
|
357
|
-
**Active Features (${g.length}):**
|
|
358
|
-
${g.length>0?g.map(v=>`- ${v.name}`).join(`
|
|
359
|
-
`):"_None_"}
|
|
360
|
-
|
|
361
|
-
**Ideas (${o.length}):**
|
|
362
|
-
${o.length>0?o.slice(0,5).map(v=>`- ${v.title}`).join(`
|
|
363
|
-
`):"_None_"}
|
|
364
|
-
|
|
365
|
-
---
|
|
366
|
-
|
|
367
|
-
## AGENTS
|
|
368
|
-
|
|
369
|
-
${i.length>0?i.map(v=>`- **${v.name}**: ${v.role||"Specialist"}`).join(`
|
|
370
|
-
`):"_None_"}
|
|
371
|
-
|
|
372
|
-
---
|
|
373
|
-
|
|
374
|
-
## DATA LOCATION
|
|
375
|
-
|
|
376
|
-
\`\`\`
|
|
377
|
-
~/.prjct-cli/projects/${e}/
|
|
378
|
-
\u251C\u2500\u2500 data/ # JSON (source of truth)
|
|
379
|
-
\u2502 \u251C\u2500\u2500 project.json
|
|
380
|
-
\u2502 \u251C\u2500\u2500 tasks/
|
|
381
|
-
\u2502 \u251C\u2500\u2500 features/
|
|
382
|
-
\u2502 \u251C\u2500\u2500 ideas/
|
|
383
|
-
\u2502 \u2514\u2500\u2500 agents/
|
|
384
|
-
\u251C\u2500\u2500 context/ # MD (for Claude)
|
|
385
|
-
\u2502 \u251C\u2500\u2500 CLAUDE.md
|
|
386
|
-
\u2502 \u251C\u2500\u2500 now.md
|
|
387
|
-
\u2502 \u2514\u2500\u2500 queue.md
|
|
388
|
-
\u2514\u2500\u2500 sync/ # Sync state
|
|
389
|
-
\u2514\u2500\u2500 pending.json
|
|
390
|
-
\`\`\`
|
|
391
|
-
`;await ss.writeFile(ns.join(r,"CLAUDE.md"),k,"utf-8")}async function mw(r,e){let t=e.find(s=>s.status==="in_progress"),n=t?`# NOW
|
|
392
|
-
|
|
393
|
-
**Task:** ${t.description}
|
|
394
|
-
|
|
395
|
-
**Started:** ${t.startedAt||"Unknown"}
|
|
396
|
-
|
|
397
|
-
**Priority:** ${t.priority||"medium"}
|
|
398
|
-
`:`# NOW
|
|
399
|
-
|
|
400
|
-
_No active task. Use /p:now to start._
|
|
401
|
-
`;await ss.writeFile(ns.join(r,"now.md"),n,"utf-8")}async function gw(r,e){let t=e.filter(s=>s.status==="pending"),n=`# QUEUE
|
|
402
|
-
|
|
403
|
-
${t.length>0?t.map((s,o)=>`${o+1}. ${s.description}${s.priority?` [${s.priority}]`:""}`).join(`
|
|
404
|
-
`):"_Empty queue. Use /p:next to add tasks._"}
|
|
405
|
-
`;await ss.writeFile(ns.join(r,"queue.md"),n,"utf-8")}async function fw(r,e,t,n){let s=`# PROJECT SUMMARY
|
|
406
|
-
|
|
407
|
-
**Name:** ${e.name||"Unknown"}
|
|
408
|
-
**Version:** ${e.version||"N/A"}
|
|
409
|
-
**Stack:** ${e.techStack?.join(", ")||"Not detected"}
|
|
410
|
-
|
|
411
|
-
## Git
|
|
412
|
-
|
|
413
|
-
- Branch: ${t.branch}
|
|
414
|
-
- Commits: ${t.commits}
|
|
415
|
-
- Status: ${t.hasChanges?"Has uncommitted changes":"Clean"}
|
|
416
|
-
|
|
417
|
-
## Dependencies
|
|
418
|
-
|
|
419
|
-
- Production: ${Object.keys(n.dependencies).length}
|
|
420
|
-
- Dev: ${Object.keys(n.devDependencies).length}
|
|
421
|
-
`;await ss.writeFile(ns.join(r,"summary.md"),s,"utf-8")}var Js,rd=y(()=>{"use strict";re();Ct();Js=lw(cw);l(sd,"generateContext");l(uw,"getGitData");l(dw,"getPackageData");l(pw,"generateClaudeMd");l(mw,"generateNowMd");l(gw,"generateQueueMd");l(fw,"generateSummaryMd")});function wa(r){if(Ll.includes(r))return[r];let e=r.toLowerCase().replace(/[-_\s]/g,""),t=[];for(let[n,s]of Object.entries(Zr))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 ya,Zr,yn,qs,Ks,Ys=y(()=>{"use strict";de();Un();te();ya={frontend:[j.CODE_STYLE,j.FILE_STRUCTURE,j.ARCHITECTURE,j.TECH_STACK],backend:[j.CODE_STYLE,j.ARCHITECTURE,j.DEPENDENCIES,j.TECH_STACK],devops:[j.SHIP_WORKFLOW,j.TEST_BEHAVIOR,j.DEPENDENCIES,j.ARCHITECTURE],docs:[j.CODE_STYLE,j.NAMING_CONVENTION,j.FILE_STRUCTURE],testing:[j.TEST_BEHAVIOR,j.CODE_STYLE,j.DEPENDENCIES],database:[j.ARCHITECTURE,j.NAMING_CONVENTION,j.TECH_STACK,j.DEPENDENCIES],general:Object.values(j)},Zr={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(wa,"resolveCanonicalDomains");yn=class{static{l(this,"CachedStore")}_data=null;_loaded=!1;_projectId=null;getSubdirectory(){return null}getStoreKey(){let e=this.getFilename().replace(".json",""),t=this.getSubdirectory();return t?`memory:${t}:${e}`:`memory:${e}`}async load(e){if(this._loaded&&this._data&&this._projectId===e)return this._data;let t=this.getStoreKey(),n=G.getDoc(e,t);return n!==null?(this._data=n,this.afterLoad(this._data)):this._data=this.getDefault(),this._loaded=!0,this._projectId=e,this._data}afterLoad(e){}async save(e){if(!this._data)return;let t=this.getStoreKey();G.setDoc(e,t,this._data)}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}},qs=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()}},Ks=class{static{l(this,"HistoryStore")}async appendHistory(e,t){let n={ts:b(),...t,type:t.type};G.appendEvent(e,`history.${t.type}`,n)}async getRecentHistory(e,t=20){return G.query(e,"SELECT data, timestamp FROM events WHERE type LIKE 'history.%' ORDER BY id DESC LIMIT ?",t).reverse().map(s=>JSON.parse(s.data))}}});var Xs,Sa=y(()=>{"use strict";de();Un();te();Ys();Xs=class r extends yn{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=Er(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=Er(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:Er(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}}async archiveStaleDecisions(e){let t=await this.load(e),n=Date.now(),s=r.ARCHIVE_AGE_DAYS*24*60*60*1e3,o=[];for(let[a,c]of Object.entries(t.decisions)){let u=new Date(c.lastSeen).getTime();n-u>s&&o.push(a)}if(o.length===0)return 0;let i=G.getDoc(e,"memory:patterns-archive")??{};for(let a of o)i[a]=t.decisions[a],delete t.decisions[a];return G.setDoc(e,"memory:patterns-archive",i),await this.save(e),o.length}}});var wn,ka=y(()=>{"use strict";bt();Un();te();Ys();wn=class extends yn{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(j),t={};for(let n of e)t[n]=[];return t}_normalizeIndex(e){let t=Object.values(j);for(let n of t)e.index[n]||(e.index[n]=[])}_coerceTags(e){let t=new Set(Object.values(j));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:ae(),title:t,content:n,tags:a,userTriggered:o,createdAt:c,updatedAt:c};i.memories.push(u);for(let d of a)i.index[d].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(d=>d!==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 p of i.tags||[])c.includes(p)&&(a+=10);let d=(Date.now()-new Date(i.updatedAt).getTime())/(1e3*60*60*24);a+=Math.max(0,5-d),i.userTriggered&&(a+=5);let m=this._extractKeywords(t);for(let p of m)i.content.toLowerCase().includes(p)&&(a+=2),i.title.toLowerCase().includes(p)&&(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(p=>{let g={domainMatch:0,tagMatch:0,recency:0,confidence:0,keywords:0,userTriggered:0};if(t.taskDomain&&(g.domainMatch=this._getSemanticDomainScore(t.taskDomain,p.tags||[])),t.commandName){let v=this._getCommandTags(t.commandName),D=(p.tags||[]).filter(q=>v.includes(q));g.tagMatch=Math.min(20,D.length*8)}let S=(Date.now()-new Date(p.updatedAt).getTime())/(1e3*60*60*24);if(g.recency=Math.max(0,Math.round(15-S*.5)),p.confidence?g.confidence=p.confidence==="high"?20:p.confidence==="medium"?12:5:p.observationCount&&(g.confidence=Math.min(20,p.observationCount*3)),t.taskDescription){let v=this._extractKeywordsFromText(t.taskDescription),D=0;for(let q of v)p.content.toLowerCase().includes(q)&&(D+=2),p.title.toLowerCase().includes(q)&&(D+=3);g.keywords=Math.min(15,D)}p.userTriggered&&(g.userTriggered=5);let k=g.domainMatch+g.tagMatch+g.recency+g.confidence+g.keywords+g.userTriggered;return{...p,relevanceScore:k,scoreBreakdown:g}}).filter(p=>p.relevanceScore>=i),d=c.sort((p,g)=>g.relevanceScore-p.relevanceScore).slice(0,o),m=d.length>0?Math.round(d.reduce((p,g)=>p+g.relevanceScore,0)/d.length):0;return{memories:d,metrics:{totalMemories:s,memoriesConsidered:c.length,memoriesReturned:d.length,filteringRatio:s>0?d.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=ya[a];if(c)for(let u of c)s.add(u)}let o=new Set;for(let a of n){let c=Zr[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 wa(e)}_getCommandTags(e){return{ship:[j.COMMIT_STYLE,j.SHIP_WORKFLOW,j.TEST_BEHAVIOR],feature:[j.ARCHITECTURE,j.CODE_STYLE],done:[j.SHIP_WORKFLOW],analyze:[j.TECH_STACK,j.ARCHITECTURE],spec:[j.ARCHITECTURE,j.CODE_STYLE],task:[j.BRANCH_NAMING,j.CODE_STYLE],sync:[j.TECH_STACK,j.ARCHITECTURE,j.DEPENDENCIES],test:[j.TEST_BEHAVIOR],bug:[j.CODE_STYLE,j.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:[j.COMMIT_STYLE,j.SHIP_WORKFLOW,j.TEST_BEHAVIOR],feature:[j.ARCHITECTURE,j.CODE_STYLE],done:[j.SHIP_WORKFLOW],analyze:[j.TECH_STACK,j.ARCHITECTURE],spec:[j.ARCHITECTURE,j.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:[j.COMMIT_STYLE],branch_naming:[j.BRANCH_NAMING],test_before_ship:[j.TEST_BEHAVIOR,j.SHIP_WORKFLOW],preferred_agent:[j.AGENT_PREFERENCE],code_style:[j.CODE_STYLE],verbosity:[j.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?`
|
|
422
|
-
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 ba,hw,pe,rs=y(()=>{"use strict";Ys();Sa();ka();Ys();Sa();ka();ba=class{static{l(this,"MemorySystem")}_semanticMemories;_patternStore;_historyStore;_sessionStore;constructor(){this._semanticMemories=new wn,this._patternStore=new Xs,this._historyStore=new Ks,this._sessionStore=new qs}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()}},hw=new ba,pe=hw});import{exec as yw}from"node:child_process";import ot from"node:fs/promises";import vt from"node:path";import{promisify as ww}from"node:util";var Sn,Pa,Sw,je,od=y(()=>{"use strict";F();Sn=ww(yw),Pa=class{static{l(this,"CodebaseAnalyzer")}projectPath=null;init(e=process.cwd()){this.projectPath=e}async readPackageJson(){try{let e=vt.join(this.projectPath,"package.json"),t=await ot.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(C(e)||e instanceof SyntaxError)return null;throw e}}async readCargoToml(){try{let e=vt.join(this.projectPath,"Cargo.toml");return await ot.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readRequirements(){try{let e=vt.join(this.projectPath,"requirements.txt");return await ot.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readGoMod(){try{let e=vt.join(this.projectPath,"go.mod");return await ot.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readGemfile(){try{let e=vt.join(this.projectPath,"Gemfile");return await ot.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readMixExs(){try{let e=vt.join(this.projectPath,"mix.exs");return await ot.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readPomXml(){try{let e=vt.join(this.projectPath,"pom.xml");return await ot.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async readComposerJson(){try{let e=vt.join(this.projectPath,"composer.json"),t=await ot.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(C(e)||e instanceof SyntaxError)return null;throw e}}async readPyprojectToml(){try{let e=vt.join(this.projectPath,"pyproject.toml");return await ot.readFile(e,"utf-8")}catch(e){if(C(e))return null;throw e}}async getFileExtensions(){try{let{stdout:e}=await Sn('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(`
|
|
423
|
-
`).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 ot.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(C(e))return[];throw e}}async listDirectories(){try{return(await ot.readdir(this.projectPath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).filter(t=>!t.startsWith(".")&&t!=="node_modules")}catch(e){if(C(e))return[];throw e}}async getGitLog(e=50){try{let{stdout:t}=await Sn(`git log -n ${e} --pretty=format:"%h|%an|%ar|%s"`,{cwd:this.projectPath});return t}catch{return""}}async getGitStats(){try{let{stdout:e}=await Sn("git rev-list --count HEAD",{cwd:this.projectPath}),{stdout:t}=await Sn('git log --format="%an" | sort -u | wc -l',{cwd:this.projectPath}),{stdout:n}=await Sn('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 Sn('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 ot.access(vt.join(this.projectPath,e)),!0}catch(t){if(C(t))return!1;throw t}}async readFile(e){try{let t=vt.join(this.projectPath,e);return await ot.readFile(t,"utf-8")}catch(t){if(C(t))return null;throw t}}async findFiles(e){try{let{stdout:t}=await Sn(`find . -type f -name "${e}" ! -path "*/node_modules/*" ! -path "*/.git/*"`,{cwd:this.projectPath});return t.trim().split(`
|
|
424
|
-
`).filter(Boolean)}catch{return[]}}},Sw=new Pa,je=Sw});import Ca from"node:fs";import to from"node:path";function id(){if(Qs)return Qs;let r=__dirname;for(let e=0;e<5;e++){let t=to.join(r,"package.json");if(Ca.existsSync(t))try{if(JSON.parse(Ca.readFileSync(t,"utf-8")).name==="prjct-cli")return Qs=r,r}catch{}r=to.dirname(r)}return Qs=to.join(__dirname,"..","..",".."),Qs}function bw(){if(eo)return eo;try{let r=to.join(id(),"package.json"),e=JSON.parse(Ca.readFileSync(r,"utf-8"));return eo=e.version,kw=e,eo}catch(r){return console.error("Failed to read version from package.json:",w(r)),"0.0.0"}}var eo,kw,Qs,os,be,kn=y(()=>{"use strict";F();eo=null,kw=null,Qs=null;l(id,"getPackageRoot");l(bw,"getVersion");os=bw(),be=id()});import xa from"node:fs";import Pw from"node:fs/promises";import no from"node:path";function Ta(){if(ad)return va;ad=!0;let r=no.join(be,"dist","templates.json");try{let e=xa.readFileSync(r,"utf-8");return va=JSON.parse(e),va}catch{return null}}function vw(r){let e=bn.indexOf(r);e>-1&&bn.splice(e,1),bn.push(r)}function xw(){for(;is.size>=Cw&&bn.length>0;){let r=bn.shift();r&&is.delete(r)}}function so(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(`
|
|
425
|
-
`).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(d=>d.trim()):o[a.trim()]=u.replace(/^["']|["']$/g,"")}}),{frontmatter:o,content:s.trim()}}async function cd(r){if(is.has(r))return vw(r),is.get(r);let e,t=Ta();if(t){let s=`commands/${r}.md`;e=t[s]}if(!e){let s=no.join(be,"templates","commands",`${r}.md`);try{e=await Pw.readFile(s,"utf-8")}catch{throw $r.notFound(r)}}let n=so(e);return xw(),is.set(r,n),bn.push(r),n}async function Tw(r){return(await cd(r)).frontmatter["allowed-tools"]||[]}function Ew(){is.clear(),bn.length=0}function Ae(r){let e=Ta();if(e?.[r])return e[r];let t=no.join(be,"templates",r);try{return xa.readFileSync(t,"utf-8")}catch{return null}}function as(r){let e=Ta();if(e)return Object.keys(e).filter(n=>n.startsWith(r));let t=no.join(be,"templates",r);try{return xa.readdirSync(t).map(s=>`${r}${s}`)}catch{return[]}}var Cw,is,bn,va,ad,Aw,Ea,cs=y(()=>{"use strict";zt();kn();Cw=50,is=new Map,bn=[],va=null,ad=!1;l(Ta,"loadBundle");l(vw,"updateLruOrder");l(xw,"evictLru");l(so,"parseFrontmatter");l(cd,"load");l(Tw,"getAllowedTools");l(Ew,"clearCache");l(Ae,"getTemplateContent");l(as,"listTemplates");Aw={load:cd,parseFrontmatter:so,getAllowedTools:Tw,clearCache:Ew,getTemplateContent:Ae,listTemplates:as},Ea=Aw});import W from"node:fs/promises";import Ia from"node:os";import J from"node:path";async function Iw(){try{let r=Ae("global/modules/module-config.json");if(r)return JSON.parse(r);let e=J.join(be,"templates/global/modules/module-config.json"),t=await W.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async function Dw(r){let e=await Iw();if(!e){let i=Ae("global/CLAUDE.md");if(i)return i;let a=J.join(be,"templates/global/CLAUDE.md");return W.readFile(a,"utf-8")}let t=r||e.default,n=e.profiles[t];if(!n&&!e.profiles[e.default]){let a=Ae("global/CLAUDE.md");if(a)return a;let c=J.join(be,"templates/global/CLAUDE.md");return W.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=Ae(`global/modules/${i}`);if(a)o.push(""),o.push(a);else try{let c=J.join(be,"templates/global/modules",i),u=await W.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(`
|
|
426
|
-
`)}async function jw(){try{let r=J.join(Ia.homedir(),".prjct-cli","docs");await W.mkdir(r,{recursive:!0});let e=as("global/docs/");if(e.length>0){for(let s of e)if(s.endsWith(".md")){let o=Ae(s);if(o){let i=J.basename(s);await W.writeFile(J.join(r,i),o,"utf-8")}}return{success:!0}}let t=J.join(be,"templates/global/docs"),n=await W.readdir(t);for(let s of n)if(s.endsWith(".md")){let o=J.join(t,s),i=J.join(r,s),a=await W.readFile(o,"utf-8");await W.writeFile(i,a,"utf-8")}return{success:!0}}catch(r){return{success:!1,error:w(r)}}}async function Rw(){let r=(Ke(),ut(st)),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 W.mkdir(e.configDir,{recursive:!0});let s=J.join(e.configDir,e.contextFile),o=J.join(be,"templates","global",e.contextFile),i="";try{let u=Ae(`global/${e.contextFile}`);u?i=u:i=await W.readFile(o,"utf-8")}catch{if(t==="claude")try{i=await Dw()}catch{let d=Ae("global/CLAUDE.md");if(d)i=d;else{let m=J.join(be,"templates/global/CLAUDE.md");i=await W.readFile(m,"utf-8")}}else{let d=Ae("global/CLAUDE.md");if(d)i=d;else{let m=J.join(be,"templates/global/CLAUDE.md");i=await W.readFile(m,"utf-8")}t==="gemini"&&(i=i.replace(/Claude/g,"Gemini"))}}let a="",c=!1;try{a=await W.readFile(s,"utf-8"),c=!0}catch(u){if(C(u))c=!1;else throw u}if(c){let u="<!-- prjct:start - DO NOT REMOVE THIS MARKER -->",d="<!-- prjct:end - DO NOT REMOVE THIS MARKER -->";if(a.includes(u)&&a.includes(d)){let p=a.substring(0,a.indexOf(u)),g=a.substring(a.indexOf(d)+d.length),f=i.substring(i.indexOf(u),i.indexOf(d)+d.length),S=p+f+g;return await W.writeFile(s,S,"utf-8"),{success:!0,action:"updated",path:s}}else{let p=`${a}
|
|
427
|
-
|
|
428
|
-
${i}`;return await W.writeFile(s,p,"utf-8"),{success:!0,action:"appended",path:s}}}else return await W.writeFile(s,i,"utf-8"),{success:!0,action:"created",path:s}}catch(s){return{success:!1,error:w(s),action:"failed"}}}function ld(){let r=Ia.homedir();return{claude:{commands:J.join(r,".claude","commands","p"),config:J.join(r,".claude"),router:J.join(r,".claude","commands","p.md")},gemini:{commands:J.join(r,".gemini","commands"),config:J.join(r,".gemini"),router:J.join(r,".gemini","commands","p.toml")}}}var Aa,$w,Ge,Pn=y(()=>{"use strict";cs();F();kn();l(Iw,"loadModuleConfig");l(Dw,"composeGlobalTemplate");l(jw,"installDocs");l(Rw,"installGlobalConfig");Aa=class{static{l(this,"CommandInstaller")}homeDir;claudeCommandsPath="";claudeConfigPath="";templatesDir;_initialized=!1;constructor(){this.homeDir=Ia.homedir(),this.templatesDir=J.join(be,"templates","commands")}async ensureInit(){if(this._initialized)return;let t=await(Ke(),ut(st)).getActiveProvider();t.name==="gemini"?this.claudeCommandsPath=J.join(t.configDir,"commands"):this.claudeCommandsPath=J.join(t.configDir,"commands","p"),this.claudeConfigPath=t.configDir,this._initialized=!0}async detectActiveProvider(){await this.ensureInit();try{return await W.access(this.claudeConfigPath),!0}catch(e){if(C(e))return!1;throw e}}async detectClaude(){return this.detectActiveProvider()}async getCommandFiles(){let e=as("commands/");if(e.length>0)return e.filter(t=>t.endsWith(".md")).map(t=>t.replace("commands/",""));try{return(await W.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(Ke(),ut(st)).getActiveProvider();if(!e)return{success:!1,error:`${n.displayName} not detected. Please install it first.`};try{await this.installRouter(),await W.mkdir(this.claudeCommandsPath,{recursive:!0});let s=await this.getCommandFiles(),o=[],i=[];for(let a of s)try{let c=J.join(this.claudeCommandsPath,a),u=Ae(`commands/${a}`);if(u)await W.writeFile(c,u,"utf-8");else{let d=J.join(this.templatesDir,a),m=await W.readFile(d,"utf-8");await W.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=J.join(this.claudeCommandsPath,s);await W.unlink(o),t.push(s.replace(".md",""))}catch(o){o.code!=="ENOENT"&&n.push({file:s,error:w(o)})}try{await W.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 W.access(this.claudeCommandsPath);let n=(await W.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(C(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(Ae(`commands/${e}.md`))return!0;try{let n=J.join(this.templatesDir,`${e}.md`);return await W.access(n),!0}catch(n){if(C(n))return!1;throw n}}async installRouter(){let t=await(Ke(),ut(st)).getActiveProvider(),n=t.name==="gemini"?"p.toml":"p.md";try{let s=J.join(t.configDir,"commands",n);await W.mkdir(J.dirname(s),{recursive:!0});let o=Ae(`commands/${n}`);if(o)return await W.writeFile(s,o,"utf-8"),!0;let i=J.join(this.templatesDir,n),a=await W.readFile(i,"utf-8");return await W.writeFile(s,a,"utf-8"),!0}catch(s){if(C(s))return!1;throw s}}async removeLegacyCommands(){let t=await(Ke(),ut(st)).getActiveProvider(),n=J.join(t.configDir,"commands"),s=0;try{let i=(await W.readdir(n)).filter(a=>a.startsWith("p.")&&a.endsWith(".md"));for(let a of i)try{await W.unlink(J.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 W.mkdir(this.claudeCommandsPath,{recursive:!0});let t=await this.getCommandFiles(),n=[];try{n=await W.readdir(this.claudeCommandsPath),n=n.filter(o=>o.endsWith(".md"))}catch(o){if(C(o))n=[];else throw o}let s={success:!0,added:0,updated:0,removed:0,errors:[]};for(let o of t)try{let i=J.join(this.claudeCommandsPath,o),a=n.includes(o),c=Ae(`commands/${o}`);if(c)await W.writeFile(i,c,"utf-8");else{let u=J.join(this.templatesDir,o),d=await W.readFile(u,"utf-8");await W.writeFile(i,d,"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 Rw()}async installDocs(){return jw()}};l(ld,"getProviderPaths");$w=new Aa,Ge=$w});function Mw(){return/<!-- prjct:preserve(?::([\w-]+))? -->/g}function Fw(r){let e=[],t=Mw(),n,s=0;for(;(n=t.exec(r))!==null;){let o=n.index,i=n[0],a=n[1]||`section-${s++}`,c=r.indexOf(Da,o+i.length);if(c===-1)continue;let u=c+Da.length,d=r.substring(o,u);e.push({id:a,content:d,startIndex:o,endIndex:u})}return e}function Zs(r,e){let t=Fw(e);if(t.length===0)return r;let n=r.trimEnd();n+=`
|
|
429
|
-
|
|
430
|
-
---
|
|
431
|
-
|
|
432
|
-
`,n+=`## Your Customizations
|
|
433
|
-
|
|
434
|
-
`,n+=`_The sections below are preserved during sync. Edit freely._
|
|
435
|
-
|
|
436
|
-
`;for(let s of t)n+=s.content,n+=`
|
|
437
|
-
|
|
438
|
-
`;return`${n.trimEnd()}
|
|
439
|
-
`}function er(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(`
|
|
440
|
-
`);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(Da)&&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 Da,ro=y(()=>{"use strict";Da="<!-- /prjct:preserve -->";l(Mw,"createPreserveStartRegex");l(Fw,"extractPreservedSections");l(Zs,"mergePreservedSections");l(er,"validatePreserveBlocks")});function tr(r){if(!r||typeof r!="object")return!1;let e=r;if(e.code&&Ow.has(e.code))return!0;if(e.code&&dd.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 io(r){if(!r||typeof r!="object")return!1;let e=r;return!!(e.code&&dd.has(e.code))}function ud(r,e,t){let n=nn.get(r);return n&&n.consecutiveFailures>=e&&n.openedAt?Date.now()-n.openedAt>=t?(nn.delete(r),!1):!0:!1}function ja(r,e){let t=nn.get(r)||{consecutiveFailures:0,openedAt:null};t.consecutiveFailures++,t.consecutiveFailures>=e&&!t.openedAt&&(t.openedAt=Date.now()),nn.set(r,t)}function _w(r){nn.delete(r)}var Ow,dd,nn,oo,pd,nr,ao=y(()=>{"use strict";Ow=new Set(["EBUSY","EAGAIN","ETIMEDOUT","ECONNRESET","ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),dd=new Set(["ENOENT","EACCES","EPERM","EISDIR","ENOTDIR","EINVAL"]);l(tr,"isTransientError");l(io,"isPermanentError");nn=new Map;l(ud,"isCircuitOpen");l(ja,"recordFailure");l(_w,"recordSuccess");oo=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(ud(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 _w(t),o}catch(o){if(n=o,s++,io(o))throw ja(t,this.options.circuitBreakerThreshold),o;if(!(tr(o)&&s<this.options.maxAttempts))throw ja(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 ja(t,this.options.circuitBreakerThreshold),n}isTransientError(e){return tr(e)}isCircuitOpen(e){return ud(e,this.options.circuitBreakerThreshold,this.options.circuitBreakerTimeoutMs)}getCircuitState(e){return nn.get(e)}resetCircuit(e){nn.delete(e)}resetAllCircuits(){nn.clear()}},pd=new oo({maxAttempts:3,baseDelayMs:1e3,maxDelayMs:8e3}),nr=new oo({maxAttempts:2,baseDelayMs:500,maxDelayMs:2e3})});var md=y(()=>{"use strict";ro();ao()});import{exec as Nw}from"node:child_process";import{promisify as Lw}from"node:util";async function co(r){try{let{stdout:e}=await Uw(r,{timeout:5e3});return{success:!0,output:e.trim()}}catch{return{success:!1,output:""}}}async function Hw(){let r=await co("gh api user --jq .login");return r.success&&r.output||(r=await co("git config --global github.user"),r.success&&r.output)?r.output:null}async function Gw(){let r=await co("git config user.name");return r.success&&r.output?r.output:null}async function zw(){let r=await co("git config user.email");return r.success&&r.output?r.output:null}async function ls(){let[r,e,t]=await Promise.all([Hw(),Gw(),zw()]);return{github:r,email:t,name:e||r||"Unknown"}}var Uw,lo=y(()=>{"use strict";Uw=Lw(Nw);l(co,"execCommand");l(Hw,"detectGitHubUsername");l(Gw,"detectGitName");l(zw,"detectGitEmail");l(ls,"detect")});import Cn from"node:fs/promises";import Ww from"node:path";import*as uo from"jsonc-parser";function gd(r){let e=[],t=uo.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}: ${uo.printParseErrorCode(n.error)}`)}return t}var $a,Bw,R,it=y(()=>{"use strict";zt();F();te();kn();lo();re();l(gd,"parseJsonc");$a=class{static{l(this,"ConfigManager")}async readConfig(e){try{let t=T.getLocalConfigPath(e),n=await Cn.readFile(t,"utf-8");return gd(n)}catch(t){return C(t)||console.warn(`Warning: Could not read config at ${e}: ${K(t)}`),null}}async writeConfig(e,t){let n=T.getLocalConfigPath(e),s=T.getLegacyPrjctPath(e);await Cn.mkdir(s,{recursive:!0});let o=JSON.stringify(t,null,2);await Cn.writeFile(n,`${o}
|
|
441
|
-
`,"utf-8")}async readGlobalConfig(e){try{let t=T.getGlobalProjectConfigPath(e),n=await Cn.readFile(t,"utf-8");return gd(n)}catch(t){return C(t)||console.warn(`Warning: Could not read global config for ${e}: ${K(t)}`),null}}async writeGlobalConfig(e,t){let n=T.getGlobalProjectConfigPath(e),s=T.getGlobalProjectPath(e);await Cn.mkdir(s,{recursive:!0});let o=JSON.stringify(t,null,2);await Cn.writeFile(n,`${o}
|
|
442
|
-
`,"utf-8")}async ensureGlobalConfig(e){let t=await this.readGlobalConfig(e);if(!t){let n=b();t={projectId:e,authors:[],version:os,lastSync:n},await this.writeGlobalConfig(e,t)}return t}async createConfig(e,t){let n=T.generateProjectId(e),s=T.getGlobalProjectPath(n),o=T.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:os,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 T.hasLegacyStructure(e))return!1;if(!await T.hasConfig(e))return!0;let s=await this.readConfig(e);if(!s||!s.projectId)return!0;let o=T.getGlobalProjectPath(s.projectId);try{return(await Cn.readdir(Ww.join(o,"core"))).length===0}catch(i){return C(i),!0}}async getProjectId(e){let t=await this.readConfig(e);return t?.projectId?t.projectId:T.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 ls(),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=T.generateProjectId(e);return{projectId:n,dataPath:T.getDisplayPath(T.getGlobalProjectPath(n))}}},Bw=new $a,R=Bw});import po from"node:fs/promises";import Ma from"node:path";var Fa,fd,hd=y(()=>{"use strict";it();re();F();Fa=class{static{l(this,"AgentRouter")}projectId=null;projectPath=null;agentsPath=null;async initialize(e){this.projectId=await R.getProjectId(e),this.projectPath=e,this.agentsPath=T.getFilePath(this.projectId,"agents","")}async loadAvailableAgents(){if(!this.agentsPath)return[];try{let e=await po.readdir(this.agentsPath),t=[];for(let n of e)if(n.endsWith(".md")){let s=n.replace(".md",""),o=await po.readFile(Ma.join(this.agentsPath,n),"utf-8");t.push({name:s,content:o})}return t}catch(e){return C(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=Ma.join(this.agentsPath,`${e}.md`),n=await po.readFile(t,"utf-8");return{name:e,content:n}}catch(t){return C(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=Ma.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})}
|
|
443
|
-
`;await po.appendFile(s,o)}catch(s){C(s)||console.error(`Agent usage log error: ${w(s)}`)}}},fd=Fa});import yd from"node:path";async function qw(){if(process.env.CLAUDE_AGENT||process.env.ANTHROPIC_CLAUDE||global.mcp||process.env.MCP_AVAILABLE)return!0;let r=process.cwd();if(await $(yd.join(r,"CLAUDE.md")))return!0;let e=process.env.HOME||process.env.USERPROFILE||"";if(await $(yd.join(e,".claude")))return!0;let t=process.cwd();return!!(t.includes("/.claude/")||t.includes("/claude-workspace/"))}function Kw(){return{...Vw}}function Yw(){return{...Jw}}async function wd(){return mo||(mo=await qw()?Kw():Yw(),mo)}var mo,Vw,Jw,Sd=y(()=>{"use strict";Fe();mo=null,Vw={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}},Jw={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(qw,"isClaudeEnvironment");l(Kw,"getClaudeAgent");l(Yw,"getTerminalAgent");l(wd,"detect")});var Qw,Oa=y(()=>{Qw=$l({})});var Zw,go,us,kd=y(()=>{"use strict";hd();zt();Sd();ao();Oa();Zw=["claude"],go=class{static{l(this,"AgentService")}agent=null;agentInfo=null;agentRouter;constructor(){this.agentRouter=new fd}async initialize(){return this.agent?this.agent:await pd.execute(async()=>{if(this.agentInfo=await wd(),!this.agentInfo?.isSupported)throw Hs.notSupported(this.agentInfo?.type??"unknown");let e=this.agentInfo.type;if(!e||!Zw.includes(e))throw Hs.notSupported(this.agentInfo?.type??"unknown");let{default:t}=await Qw(`../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:`
|
|
444
|
-
AGENTIC EXECUTION:
|
|
445
|
-
- Read: templates/agentic/orchestrator.md
|
|
446
|
-
- Analyze task: "${e}"
|
|
447
|
-
- Available specialists: ${s.join(", ")}
|
|
448
|
-
- Claude decides which agent(s) to use
|
|
449
|
-
- Always prefer specialists over generalist
|
|
450
|
-
- Fragment complex tasks into subtasks
|
|
451
|
-
`}}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}},us=new go});var fo,ho,bd=y(()=>{"use strict";fo=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"}},ho=new fo});var Pd,eS,yo,tS,Cd=y(()=>{"use strict";Ws();Pd=8e4,eS={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"]},yo=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||Pd,[c,u,d]=await Promise.all([Oe.readIndex(t),Oe.readDomains(t),Oe.readCategories(t)]);if(!c||!u||!d)return this.fallbackSelection(c?.relevantFiles||[],n);let m=this.detectTaskDomains(e,u.domains),p=new Set;for(let D of m){let q=d.domainIndex[D]||[];for(let Me of q)p.add(Me)}if(i&&d.domainIndex.general){let D=d.domainIndex.general.slice(0,10);for(let q of D)p.add(q)}let g=c.relevantFiles.filter(D=>p.has(D.path)&&D.score>=o);g.sort((D,q)=>q.score-D.score);let f=0,S=[];for(let D of g){let q=Math.ceil(D.size/this.CHARS_PER_TOKEN);if(f+q>a||S.length>=s)break;S.push(D),f+=q}let k=Math.ceil(c.relevantFiles.reduce((D,q)=>D+q.size,0)/this.CHARS_PER_TOKEN),v=k>0?(k-f)/k:0;return{files:S,domains:m,metrics:{totalFiles:c.relevantFiles.length,selectedFiles:S.length,compressionRate:v,estimatedTokensSaved:k-f}}}detectTaskDomains(e,t){let n=e.toLowerCase(),s=new Set;for(let[o,i]of Object.entries(eS))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 Oe.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 Oe.readIndex(e);return i?i.relevantFiles.filter(a=>o.has(a.path)):[]}async getFilesDomains(e,t){return Oe.getFileCategories(e,t)}fallbackSelection(e,t){let n=t.maxFiles||50,s=t.minScore||30,o=t.tokenBudget||Pd,i=e.filter(d=>d.score>=s).sort((d,m)=>m.score-d.score),a=0,c=[];for(let d of i){let m=Math.ceil(d.size/this.CHARS_PER_TOKEN);if(a+m>o||c.length>=n)break;c.push(d),a+=m}let u=Math.ceil(e.reduce((d,m)=>d+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)}},tS=new yo});import vd from"node:path";var _a,wo,nS,xd=y(()=>{"use strict";Ws();te();_a=[{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"}],wo=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 _a)if(c.test(a)){t.set(u,(t.get(u)||0)+1),n.has(u)||n.set(u,new Set);let d=vd.dirname(i.path);n.get(u).add(`**/${vd.basename(d)}/**`)}}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=_a.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 p=0;for(let g of m.keywords)a.includes(g.toLowerCase())&&(p+=1);for(let{pattern:g,domain:f}of _a)f===m.name&&g.test(a)&&(p+=2);for(let g of m.filePatterns){let f=g.replace(/\*\*/g,"").replace(/\//g,"");a.includes(f.toLowerCase())&&(p+=1)}p>0&&i.push({domain:m.name,score:p})}i.sort((m,p)=>p.score-m.score);let c=i.length>0?i.slice(0,3).map(m=>m.domain):["general"],u=c[0],d=i.length>0?Math.min(1,i[0].score/5):.1;n.push({path:o.path,categories:c,primaryDomain:u,confidence:d,categorizedAt:s,method:"heuristic"})}return n}async saveToCache(e,t,n){let s=b(),o={version:Pt,projectId:e,domains:t,discoveredAt:s};await Oe.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:Pt,lastUpdate:s,fileCategories:n,domainIndex:i};await Oe.writeCategories(e,a)}async loadFromCache(e){let[t,n]=await Promise.all([Oe.readDomains(e),Oe.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 Oe.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 Oe.readCategories(e);if(i){let a=new Set(t.map(p=>p.path)),u=[...i.fileCategories.filter(p=>!a.has(p.path)),...o],d={};for(let p of u)for(let g of p.categories)d[g]||(d[g]=[]),d[g].push(p.path);let m={version:Pt,lastUpdate:b(),fileCategories:u,domainIndex:d};await Oe.writeCategories(e,m)}return o}},nS=new wo});import Na from"node:path";var La,sS,rS,So,Td,Ua=y(()=>{"use strict";La=30,sS=[/^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$/],rS=[/^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],So=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=La){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=Na.basename(e.path);for(let n of sS)if(n.test(t)||n.test(e.path))return 20;return 0}calculateNameRelevance(e){let t=Na.basename(e.path);for(let s of rS)if(s.test(t))return 15;let n=Na.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}},Td=new So});function Ha(r,e){return{...Fs[r],...e}}function ko(r,e,t){return{message:r,hint:e,...t}}var bo=y(()=>{"use strict";Tr();Tr();l(Ha,"getError");l(ko,"createError")});import{execSync as Ga}from"node:child_process";var Po,za,Co,vo,Wa=y(()=>{"use strict";bo();Po={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"}},za=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=Po[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=Po[e],s=t.error||{message:`${e} is not available`,hint:n?.installHint||`Install ${e} and try again`,docs:n?.docs};throw new Co(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=Po[s];return o?` ${s}: ${o.installHint}`:` ${s}: Install and try again`}).join(`
|
|
452
|
-
`);throw new Co({message:`Missing required tools: ${t.join(", ")}`,hint:`Install the following:
|
|
453
|
-
${n}`})}}isAvailable(e){return this.checkTool(e).available}getVersion(e){return this.checkTool(e).version}checkAll(e){let t=e||Object.keys(Po),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=Ga(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:ko(`${e.name} is not installed or not in PATH`,e.installHint,{docs:e.docs})}}}checkUnknownTool(e){try{return Ga(`${e} --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}),{available:!0}}catch{try{return Ga(`${e} -v`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}),{available:!0}}catch{return{available:!1,error:ko(`${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())}},Co=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}},vo=new za});import{exec as oS}from"node:child_process";import{promisify as iS}from"node:util";var _0,Ed=y(()=>{"use strict";Qt();Wa();_0=iS(oS)});var xo,Ye,Ba=y(()=>{"use strict";it();tn();de();xo=class{static{l(this,"MemoryService")}async log(e,t,n,s){try{let o=await R.getProjectId(e);if(!o)return;G.appendEvent(o,`memory.${t}`,{...n,author:s})}catch(o){console.error(`Memory log error: ${o instanceof Error?o.message:String(o)}`)}}async getRecent(e,t=100){try{let n=await R.getProjectId(e);return n?G.query(n,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(o=>{let i=JSON.parse(o.data),{author:a,...c}=i;return{timestamp:o.timestamp,action:o.type.replace("memory.",""),data:c,author:a}}):[]}catch(n){return console.error(`Memory read error: ${n instanceof Error?n.message:String(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){try{let s=await R.getProjectId(e);return s?G.query(s,"SELECT type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`memory.${t}`,n).reverse().map(i=>{let a=JSON.parse(i.data),{author:c,...u}=a;return{timestamp:i.timestamp,action:i.type.replace("memory.",""),data:u,author:c}}):[]}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async clear(e){try{let t=await R.getProjectId(e);if(!t)return;G.run(t,"DELETE FROM events WHERE type LIKE 'memory.%'")}catch(t){console.error(`Memory clear error: ${t instanceof Error?t.message:String(t)}`)}}async getRecentEvents(e,t=100){try{return G.query(e,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(s=>{let o=JSON.parse(s.data);return{timestamp:s.timestamp,action:s.type.replace("memory.",""),...o}})}catch(n){return console.error(`Memory read error: ${n instanceof Error?n.message:String(n)}`),[]}}async capEntries(e){try{let n=G.get(e,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(n<=Ot.MEMORY_MAX_ENTRIES)return 0;let s=n-Ot.MEMORY_MAX_ENTRIES,o=G.query(e,"SELECT id, type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?",s);rt.archiveMany(e,o.map((a,c)=>({entityType:"memory_entry",entityId:`memory-${a.timestamp||c}`,entityData:{type:a.type,data:JSON.parse(a.data),timestamp:a.timestamp},summary:a.type.replace("memory.",""),reason:"overflow"})));let i=o[o.length-1]?.id;return i!==void 0&&G.run(e,"DELETE FROM events WHERE type LIKE 'memory.%' AND id <= ?",i),s}catch(t){return console.error(`Memory cap error: ${t instanceof Error?t.message:String(t)}`),0}}},Ye=new xo});import To from"node:fs/promises";import Se from"node:path";var sr,Va=y(()=>{"use strict";re();Fe();sr=class{static{l(this,"NestedContextResolver")}rootPath;monoInfo=null;constructor(e){this.rootPath=Se.resolve(e)}async initialize(){this.monoInfo=await T.detectMonorepo(this.rootPath)}async discoverContextFiles(){let e=[],t=Se.join(this.rootPath,"PRJCT.md");if(await $(t)){let s=await this.loadContext(t,null);e.push(s)}if(this.monoInfo?.isMonorepo)for(let s of this.monoInfo.packages){let o=Se.join(s.path,"PRJCT.md");if(await $(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 To.readFile(e,"utf-8"),o=Se.relative(this.rootPath,e),i=o.split(Se.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(`
|
|
454
|
-
`),s=null,o=[];for(let i of n){let a=i.match(/^##\s+(.+)$/);if(a){s&&(s.content=o.join(`
|
|
455
|
-
`).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(`
|
|
456
|
-
`).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 To.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 d=Se.join(i,u.name),m=Se.join(d,"PRJCT.md");if(await $(m)&&!s.has(m)){let p=this.findParentContext(m,t.concat(n)),g=await this.loadContext(m,p);n.push(g),s.add(m),p&&p.children.push(g)}await o(d,a+1)}}catch{}},"scan");return await o(e,0),n}findParentContext(e,t){let n=Se.dirname(e),s=[...t].sort((o,i)=>i.depth-o.depth);for(let o of s){let i=Se.dirname(o.path);if(n.startsWith(i)&&n!==i)return o}return null}async resolveContextForPath(e){let t=await this.discoverContextFiles(),n=Se.resolve(e),s=null;for(let a of t){let c=Se.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}
|
|
457
|
-
|
|
458
|
-
${a.content}`)}}let o=[];for(let[i,a]of t)o.push(`## ${i}
|
|
459
|
-
|
|
460
|
-
${a}`);return{content:o.join(`
|
|
461
|
-
|
|
462
|
-
---
|
|
463
|
-
|
|
464
|
-
`),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=Se.join(this.rootPath,"AGENTS.md");if(await $(t)){let s=await this.loadAgents(t,null);e.push(s)}if(this.monoInfo?.isMonorepo)for(let s of this.monoInfo.packages){let o=Se.join(s.path,"AGENTS.md");if(await $(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 To.readFile(e,"utf-8"),o=Se.relative(this.rootPath,e),i=o.split(Se.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(`
|
|
465
|
-
`),s=null,o=null,i=[],a=l(()=>{if(s){if(o){let c=i.join(`
|
|
466
|
-
`).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(`
|
|
467
|
-
`).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],p=m.includes("@override")||m.includes("(override)");s={name:m.replace(/@override|\(override\)/gi,"").trim(),description:"",override:p},o=null,i=[];continue}let d=c.match(/^###\s+(.+)$/);if(d&&s){a(),o=d[1].trim(),i=[];continue}s&&i.push(c)}return s&&(a(),t.push(s)),t}parseListItems(e){return e.split(`
|
|
468
|
-
`).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 To.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 d=Se.join(i,u.name),m=Se.join(d,"AGENTS.md");if(await $(m)&&!s.has(m)){let p=this.findParentAgents(m,t.concat(n)),g=await this.loadAgents(m,p);n.push(g),s.add(m),p&&p.children.push(g)}await o(d,a+1)}}catch{}},"scan");return await o(e,0),n}findParentAgents(e,t){let n=Se.dirname(e),s=[...t].sort((o,i)=>i.depth-o.depth);for(let o of s){let i=Se.dirname(o.path);if(n.startsWith(i)&&n!==i)return o}return null}async resolveAgentsForPath(e){let t=await this.discoverAgentFiles(),n=Se.resolve(e),s=null;for(let a of t){let c=Se.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}
|
|
469
|
-
|
|
470
|
-
${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 aS}from"node:child_process";import{promisify as cS}from"node:util";var tj,Ad=y(()=>{"use strict";Ws();te();Ua();tj=cS(aS)});import vn from"chalk";var Id,lS,uS,xt,Dd=y(()=>{"use strict";Ke();Id=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],lS=80,uS={name:"prjct",icon:"\u26A1",signature:"\u26A1 prjct",spinner:{frames:Id,speed:lS},cli:{header:l(()=>`${vn.cyan.bold("\u26A1")} ${vn.cyan("prjct")}`,"header"),footer:l(()=>vn.dim("\u26A1 prjct"),"footer"),spin:l((r,e)=>`${vn.cyan("\u26A1")} ${vn.cyan("prjct")} ${vn.cyan(Id[r%10])} ${vn.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")=>jr(r).commitFooter,"getCommitFooter"),getSignature:l((r="claude")=>jr(r).signature,"getSignature")},xt=uS});import X from"chalk";function mS(){return dS[pS]}var pj,Ja,dS,pS,xn,ds,qa,at,sn,gS,fS,h,Tn=y(()=>{"use strict";Dd();Qt();bo();bo();pj=xt.spinner.frames,Ja=xt.spinner.speed,dS={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}},pS="compact";l(mS,"getTierConfig");xn={success:X.green("\u2713"),fail:X.red("\u2717"),warn:X.yellow("\u26A0"),info:X.blue("\u2139"),debug:X.dim("\u{1F527}"),bullet:X.dim("\u2022"),arrow:X.dim("\u2192"),check:X.green("\u2713"),cross:X.red("\u2717"),spinner:X.cyan("\u25D0")},ds=null,qa=0,at=!1,sn=l((r,e)=>{let t=e??(mS().maxCharsPerLine||St.FALLBACK_TRUNCATE);return r&&r.length>t?`${r.slice(0,t-1)}\u2026`:r||""},"truncate"),gS=l(()=>process.stdout.isTTY?process.stdout.write(`\r${" ".repeat(St.CLEAR_WIDTH)}\r`):!0,"clear"),fS={start(){return at||console.log(xt.cli.header()),this},end(){return at||console.log(xt.cli.footer()),this},spin(r){return at?this:(this.stop(),process.stdout.isTTY?(ds=setInterval(()=>{process.stdout.write(`\r${xt.cli.spin(qa++,sn(r,St.SPINNER_MSG))}`)},Ja),this):(process.stdout.write(`${xt.cli.spin(0,sn(r,St.SPINNER_MSG))}
|
|
471
|
-
`),this))},done(r,e){if(this.stop(),!at){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=X.dim(` [${n.join(" | ")}]`))}console.log(`${xn.success} ${sn(r,St.DONE_MSG)}${t}`)}return this},fail(r){return this.stop(),console.error(`${xn.fail} ${sn(r,St.FAIL_MSG)}`),this},failWithHint(r){this.stop();let e=typeof r=="string"?Ha(r):r;return console.error(),console.error(`${xn.fail} ${e.message}`),e.file&&console.error(X.dim(` File: ${e.file}`)),e.hint&&console.error(X.yellow(` \u{1F4A1} ${e.hint}`)),e.docs&&console.error(X.dim(` Docs: ${e.docs}`)),console.error(),this},warn(r){return this.stop(),at||console.log(`${xn.warn} ${sn(r,St.WARN_MSG)}`),this},info(r){return this.stop(),at||console.log(`${xn.info} ${r}`),this},debug(r){this.stop();let e=process.env.DEBUG==="1"||process.env.DEBUG==="true";return!at&&e&&console.log(`${xn.debug} ${X.dim(r)}`),this},success(r,e){return this.done(r,e)},list(r,e={}){if(this.stop(),at)return this;let t=e.bullet||xn.bullet,n=" ".repeat(e.indent||0);for(let s of r)console.log(`${n}${t} ${s}`);return this},table(r,e={}){if(this.stop(),at||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(X.dim(s)),console.log(X.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(),at)return this;let t=e.split(`
|
|
472
|
-
`),n=Math.max(r.length,...t.map(o=>o.length)),s="\u2500".repeat(n+2);console.log(X.dim(`\u250C${s}\u2510`)),console.log(`${X.dim("\u2502")} ${X.bold(r.padEnd(n))} ${X.dim("\u2502")}`),console.log(X.dim(`\u251C${s}\u2524`));for(let o of t)console.log(`${X.dim("\u2502")} ${o.padEnd(n)} ${X.dim("\u2502")}`);return console.log(X.dim(`\u2514${s}\u2518`)),this},section(r){return this.stop(),at?this:(console.log(`
|
|
473
|
-
${X.bold(r)}`),console.log(X.dim("\u2500".repeat(r.length))),this)},stop(){return ds&&(clearInterval(ds),ds=null,gS()),this},step(r,e,t){if(at)return this;this.stop();let n=X.dim(`[${r}/${e}]`);return process.stdout.isTTY?(ds=setInterval(()=>{process.stdout.write(`\r${xt.cli.spin(qa++,`${n} ${sn(t,St.STEP_MSG)}`)}`)},Ja),this):(process.stdout.write(`${xt.cli.spin(0,`${n} ${sn(t,St.STEP_MSG)}`)}
|
|
474
|
-
`),this)},progress(r,e,t){if(at)return this;this.stop();let n=Math.round(r/e*100),s=Math.round(n/10),o=10-s,i=X.cyan("\u2588".repeat(s))+X.dim("\u2591".repeat(o)),a=t?` ${sn(t,St.PROGRESS_TEXT)}`:"";return process.stdout.isTTY?(ds=setInterval(()=>{process.stdout.write(`\r${xt.cli.spin(qa++,`[${i}] ${n}%${a}`)}`)},Ja),this):(process.stdout.write(`${xt.cli.spin(0,`[${i}] ${n}%${a}`)}
|
|
475
|
-
`),this)}},h=fS});function ze(r,e,t=2){return`${"#".repeat(t)} ${r}
|
|
476
|
-
${e}`}function Tt(r,e=!1){return r.map((t,n)=>e?`${n+1}. ${t}`:`- ${t}`).join(`
|
|
477
|
-
`)}function Ka(r){let e=[];r.branch&&e.push(`Branch: \`${r.branch}\``),r.linearId&&e.push(`Linear: ${r.linearId}`),r.type&&e.push(`Type: ${r.type}`),r.duration&&e.push(`Duration: ${r.duration}`);let t=e.length>0?`
|
|
478
|
-
${e.join(" | ")}`:"";return`## ${r.description}${t}`}function Ya(r,e){return`### Subtasks
|
|
341
|
+
`)}`)}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:k(),output:s,summary:o};let d=u.filter(f=>f.status==="completed").length,m=u.length,p=Math.round(d/m*100),g=a+1;return g<u.length&&(u[g]={...u[g],status:"in_progress",startedAt:k()}),await this.update(e,f=>({...f,currentTask:{...f.currentTask,subtasks:u,currentSubtaskIndex:g<m?g:a,subtaskProgress:{completed:d,total:m,percentage:p}},lastUpdated:k()})),await this.publishEvent(e,"subtask.completed",{taskId:i.currentTask.id,subtaskId:c.id,description:c.description,output:s,handoff:o.outputForNextAgent,filesChanged:o.filesChanged.length,progress:{completed:d,total:m,percentage:p}}),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:k(),output:`Failed: ${t}`};let a=s+1,c=i.length;a<c&&(i[a]={...i[a],status:"in_progress",startedAt:k()});let u=i.filter(m=>m.status==="completed"||m.status==="failed"||m.status==="skipped").length,d=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:d}},lastUpdated:k()})),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:k(),output:`Skipped: ${t}`,skipReason:t};let a=s+1,c=i.length;a<c&&(i[a]={...i[a],status:"in_progress",startedAt:k()});let u=i.filter(m=>m.status==="completed"||m.status==="failed"||m.status==="skipped").length,d=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:d}},lastUpdated:k()})),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:k()}),await this.update(e,u=>({...u,currentTask:{...u.currentTask,subtasks:i,currentSubtaskIndex:a<c?a:s},lastUpdated:k()})),await this.publishEvent(e,"subtask.blocked",{taskId:n.currentTask.id,subtaskId:o.id,description:o.description,blocker:t}),a<c?i[a]:null}},F=new Ia});var ud=w(()=>{"use strict";wa();O()});var Da,Ra,ja=w(()=>{"use strict";Un();jt();Da=class extends Te{static{l(this,"VelocityStorage")}constructor(){super("velocity.json")}getDefault(){return{metrics:xu,lastUpdated:""}}getEventType(e){return`velocity.${e}d`}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}},Ra=new Da});var Mt=w(()=>{"use strict";uo();Xt();le();Hs();Ls();po();go();Gs();Ws();Vs();ud();jt();ja()});function Ue(r,e,t=2){return`${"#".repeat(t)} ${r}
|
|
342
|
+
${e}`}function Ct(r,e=!1){return r.map((t,n)=>e?`${n+1}. ${t}`:`- ${t}`).join(`
|
|
343
|
+
`)}function $a(r){let e=[];r.branch&&e.push(`Branch: \`${r.branch}\``),r.linearId&&e.push(`Linear: ${r.linearId}`),r.type&&e.push(`Type: ${r.type}`),r.duration&&e.push(`Duration: ${r.duration}`);let t=e.length>0?`
|
|
344
|
+
${e.join(" | ")}`:"";return`## ${r.description}${t}`}function Ma(r,e){return`### Subtasks
|
|
479
345
|
${r.map((n,s)=>{let o=n.status==="completed",i=s===e?" \u2190 current":"";return`${o?"- [x]":"- [ ]"} ${n.description}${i}`}).join(`
|
|
480
|
-
`)}`}function
|
|
481
|
-
${
|
|
346
|
+
`)}`}function dd(r){return`### Rules
|
|
347
|
+
${Ct(r)}`}function Oe(r){return`### Next
|
|
482
348
|
${r.map(t=>`- ${t.label}: \`${t.command}\``).join(`
|
|
483
|
-
`)}`}function
|
|
484
|
-
`)}function
|
|
485
|
-
${e}`:`## ${r} \u2713`}function
|
|
349
|
+
`)}`}function xt(r){let e=[];for(let[t,n]of Object.entries(r))n!=null&&e.push(`- **${t}:** ${n}`);return e.join(`
|
|
350
|
+
`)}function Ot(r,e){return e?`## ${r} \u2713
|
|
351
|
+
${e}`:`## ${r} \u2713`}function Zt(r){return`> \u26A0\uFE0F ${r}`}function me(...r){return r.filter(Boolean).join(`
|
|
486
352
|
|
|
487
|
-
`)}var
|
|
488
|
-
Next:`));for(let o of s){let i=
|
|
353
|
+
`)}var Zn=w(()=>{"use strict";l(Ue,"mdSection");l(Ct,"mdList");l($a,"mdTaskHeader");l(Ma,"mdSubtasks");l(dd,"mdRules");l(Oe,"mdNextSteps");l(xt,"mdStats");l(Ot,"mdDone");l(Zt,"mdWarn");l(me,"mdJoin")});import Js from"chalk";function ot(r,e={}){if(e.quiet)return;let t=md[r]||"idle",n=kn.getValidCommands(t);if(n.length===0)return;let s=n.map(o=>({cmd:`p. ${o}`,desc:pd[o]||o}));console.log(Js.dim(`
|
|
354
|
+
Next:`));for(let o of s){let i=Js.cyan(o.cmd.padEnd(12));console.log(Js.dim(` ${i} \u2192 ${o.desc}`))}}function fo(r){let e=md[r]||"idle";return kn.getValidCommands(e).map(n=>({cmd:`p. ${n}`,desc:pd[n]||n}))}function qs(r){let e=kn.getStateInfo(r);console.log(Js.dim(`\u{1F4CD} State: ${Js.white(r.toUpperCase())} - ${e.description}`))}var pd,md,es=w(()=>{"use strict";Aa();pd={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"},md={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(ot,"showNextSteps");l(fo,"getNextSteps");l(qs,"showStateInfo")});import ct from"chalk";import bn from"prompts";var Oa,gd,ts,fd=w(()=>{"use strict";yn();Oa=[{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."}],gd=[{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"}],ts=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,bn.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 bn({type:"select",name:"projectType",message:this.detectedType!=="unknown"?`Detected: ${this.getProjectTypeLabel(this.detectedType)}. Is this correct?`:"What type of project is this?",choices:Oa.map(t=>({title:t.title,description:t.description,value:t.value,selected:t.value===this.detectedType})),initial:Oa.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 bn({type:"multiselect",name:"agents",message:"Which AI agents do you use?",choices:gd.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(ct.dim(`
|
|
489
355
|
Detected: ${e}
|
|
490
|
-
`));let t=await
|
|
356
|
+
`));let t=await bn({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 bn([{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 bn([{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(ct.bold(" Configuration Summary")),console.log(ct.dim(` ${"\u2500".repeat(40)}`)),console.log(` ${ct.cyan("Project Type:")} ${this.getProjectTypeLabel(this.confirmedType)}`),console.log(` ${ct.cyan("AI Agents:")} ${this.selectedAgents.map(t=>this.getAgentLabel(t)).join(", ")}`),console.log(` ${ct.cyan("Stack:")} ${this.formatStackDisplay(this.confirmedStack)}`),console.log(` ${ct.cyan("Verbosity:")} ${this.preferences.verbosity}`),console.log(` ${ct.cyan("Auto-sync:")} ${this.preferences.autoSync?"Yes":"No"}`),console.log("");let e=await bn({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(ct.bold.cyan(" Welcome to prjct-cli!")),console.log(ct.dim(" Let's set up your project in 60 seconds.")),console.log("")}printStepHeader(e){console.log(""),console.log(ct.dim(` Step ${this.currentStep}/${this.totalSteps}: ${e}`)),console.log("")}handleCancel(){this.aborted=!0,console.log(ct.yellow(`
|
|
491
357
|
Setup cancelled. Run again anytime.
|
|
492
|
-
`))}getProjectTypeLabel(e){return
|
|
493
|
-
`).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}},wS=new Ao,Xe=wS});var Io,SS,Za,Od=y(()=>{"use strict";An();Io=class{static{l(this,"OutcomeAnalyzer")}async summarize(e){let t=await Xe.getAll(e);if(t.length===0)return{totalOutcomes:0,avgQualityScore:0,estimateAccuracy:0,topBlockers:[],topAgents:[],patternsDetected:[]};let n=t.reduce((m,p)=>m+p.qualityScore,0)/t.length,s=await Xe.getEstimateAccuracy(e),o=new Map;for(let m of t)for(let p of m.blockers||[])o.set(p,(o.get(p)||0)+1);let i=[...o.entries()].sort((m,p)=>p[1]-m[1]).slice(0,5).map(([m])=>m),c=(await this.getAgentMetrics(e)).sort((m,p)=>p.successRate-m.successRate).slice(0,3).map(m=>m.agent),d=(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:d}}async getAgentMetrics(e){let t=await Xe.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),d=i.reduce((S,k)=>S+k.qualityScore,0)/a,m=i.filter(S=>{if(!S.variance)return!1;let k=this.parseVariance(S.variance),v=this.parseDuration(S.estimatedDuration);return v===0?!1:Math.abs(k)/v<=.2}),p=Math.round(m.length/a*100),g=new Map;for(let S of i.filter(k=>k.completedAsPlanned))for(let k of S.tags||[])g.set(k,(g.get(k)||0)+1);let f=[...g.entries()].sort((S,k)=>k[1]-S[1]).slice(0,3).map(([S])=>S);s.push({agent:o,tasksCompleted:a,successRate:u,avgQualityScore:Math.round(d*10)/10,estimateAccuracy:p,bestFor:f})}return s}async detectPatterns(e){let t=await Xe.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 Xe.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}},SS=new Io,Za=SS});var ir,Do,ec,tc=y(()=>{"use strict";Un();te();ir=3,Do=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>=ir){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}/${ir} 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>=ir){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}/${ir} 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]}`,d=t.get(u)||{count:0,tasks:[]};d.count++,d.tasks.push(s.taskId),t.set(u,d)}}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>=ir&&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:[j.FILE_STRUCTURE,j.ARCHITECTURE],tech_stack:[j.TECH_STACK],architecture:[j.ARCHITECTURE,j.CODE_STYLE],estimation:[j.SHIP_WORKFLOW],workflow:[j.SHIP_WORKFLOW,j.CODE_STYLE],gotcha:[j.TEST_BEHAVIOR,j.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(`
|
|
494
|
-
`)}},
|
|
495
|
-
`);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=nt(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(`
|
|
496
|
-
`)}async addFeatureOutcome(e,t){await this.update(e,n=>({...n,outcomes:[t,...n.outcomes],aggregates:Br([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?Br(t.outcomes):t.aggregates}async reaggregate(e){await this.update(e,t=>({...t,aggregates:Br(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=Iu(n,s),i={whatWorked:[],whatDidnt:[],surprises:[],recommendations:[]},a=100,c=Du(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:ju(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}},_d=new jo});var sc=y(()=>{"use strict";Fd();Od();tc();An();nc()});import Nt from"chalk";function kS(r){return Nd[r.toLowerCase()]||Nd.default}var Nd,rc,Ro,Ld=y(()=>{"use strict";Nd={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(kS,"getIcon");rc=class{static{l(this,"AgentStream")}currentAgent=null;startTime=0;quiet=!1;setQuiet(e){this.quiet=e}orchestrate(e){this.quiet||console.log(Nt.cyan(`
|
|
358
|
+
`))}getProjectTypeLabel(e){return Oa.find(t=>t.value===e)?.title||"Unknown"}getAgentLabel(e){return gd.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}}});import Fa from"node:path";var Hw,zw,ho,Gw,Ke,Pn=w(()=>{"use strict";ue();yt();je();Hw="outcomes",zw="outcomes.jsonl",ho=class{static{l(this,"OutcomeRecorder")}getOutcomesDir(e){let t=E.getGlobalProjectPath(e);return Fa.join(t,Hw)}getOutcomesPath(e){return Fa.join(this.getOutcomesDir(e),zw)}async record(e,t){let n={...t,id:oe()},s=this.getOutcomesPath(e);return await ft(Fa.dirname(s)),await gi(s,JSON.stringify(n)),n}async getAll(e){let t=this.getOutcomesPath(e);if(!await M(t))return[];let n=await _n(t);return n.trim()?n.trim().split(`
|
|
359
|
+
`).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}},Gw=new ho,Ke=Gw});var yo,Ww,_a,hd=w(()=>{"use strict";Pn();yo=class{static{l(this,"OutcomeAnalyzer")}async summarize(e){let t=await Ke.getAll(e);if(t.length===0)return{totalOutcomes:0,avgQualityScore:0,estimateAccuracy:0,topBlockers:[],topAgents:[],patternsDetected:[]};let n=t.reduce((m,p)=>m+p.qualityScore,0)/t.length,s=await Ke.getEstimateAccuracy(e),o=new Map;for(let m of t)for(let p of m.blockers||[])o.set(p,(o.get(p)||0)+1);let i=[...o.entries()].sort((m,p)=>p[1]-m[1]).slice(0,5).map(([m])=>m),c=(await this.getAgentMetrics(e)).sort((m,p)=>p.successRate-m.successRate).slice(0,3).map(m=>m.agent),d=(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:d}}async getAgentMetrics(e){let t=await Ke.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),d=i.reduce((S,b)=>S+b.qualityScore,0)/a,m=i.filter(S=>{if(!S.variance)return!1;let b=this.parseVariance(S.variance),D=this.parseDuration(S.estimatedDuration);return D===0?!1:Math.abs(b)/D<=.2}),p=Math.round(m.length/a*100),g=new Map;for(let S of i.filter(b=>b.completedAsPlanned))for(let b of S.tags||[])g.set(b,(g.get(b)||0)+1);let f=[...g.entries()].sort((S,b)=>b[1]-S[1]).slice(0,3).map(([S])=>S);s.push({agent:o,tasksCompleted:a,successRate:u,avgQualityScore:Math.round(d*10)/10,estimateAccuracy:p,bestFor:f})}return s}async detectPatterns(e){let t=await Ke.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 Ke.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}},Ww=new yo,_a=Ww});var Ks,wo,Na,La=w(()=>{"use strict";On();se();Ks=3,wo=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>=Ks){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}/${Ks} 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>=Ks){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}/${Ks} 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]}`,d=t.get(u)||{count:0,tasks:[]};d.count++,d.tasks.push(s.taskId),t.set(u,d)}}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>=Ks&&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:[I.FILE_STRUCTURE,I.ARCHITECTURE],tech_stack:[I.TECH_STACK],architecture:[I.ARCHITECTURE,I.CODE_STYLE],estimation:[I.SHIP_WORKFLOW],workflow:[I.SHIP_WORKFLOW,I.CODE_STYLE],gotcha:[I.TEST_BEHAVIOR,I.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: ${k()}`];return e.sourceTasks.length>0&&t.push(`source_tasks: ${e.sourceTasks.slice(0,5).join(", ")}`),t.join(`
|
|
360
|
+
`)}},Na=new wo});var So,yd,Ua=w(()=>{"use strict";$i();jt();se();So=class extends Te{static{l(this,"OutcomeStorage")}constructor(){super("outcomes.json")}getDefault(){return{...iu,lastUpdated:""}}getEventType(e){return`outcomes.${e}d`}async addFeatureOutcome(e,t){await this.update(e,n=>({...n,outcomes:[t,...n.outcomes],aggregates:vr([t,...n.outcomes]),lastUpdated:k()})),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:k()}))}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?vr(t.outcomes):t.aggregates}async reaggregate(e){await this.update(e,t=>({...t,aggregates:vr(t.outcomes),lastAggregated:k(),lastUpdated:k()}))}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=au(n,s),i={whatWorked:[],whatDidnt:[],surprises:[],recommendations:[]},a=100,c=cu(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:lu(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}},yd=new So});var Ha=w(()=>{"use strict";fd();hd();La();Pn();Ua()});import Ft from"chalk";function Bw(r){return wd[r.toLowerCase()]||wd.default}var wd,za,ko,Sd=w(()=>{"use strict";wd={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(Bw,"getIcon");za=class{static{l(this,"AgentStream")}currentAgent=null;startTime=0;quiet=!1;setQuiet(e){this.quiet=e}orchestrate(e){this.quiet||console.log(Ft.cyan(`
|
|
497
361
|
\u{1F3AF} Orchestrating: ${e.join(", ")} domains detected
|
|
498
|
-
`))}startAgent(e,t,n){if(this.quiet)return;this.currentAgent=e,this.startTime=Date.now();let s=
|
|
499
|
-
`),this.currentAgent=null}status(e,t){this.quiet||console.log(`${e} ${t}`)}complete(e,t){if(this.quiet)return;let n=t?` ${
|
|
500
|
-
`)}function
|
|
501
|
-
`)}var
|
|
362
|
+
`))}startAgent(e,t,n){if(this.quiet)return;this.currentAgent=e,this.startTime=Date.now();let s=Bw(t);console.log(Ft.cyan(`\u250C\u2500 ${s} ${e} (${t})`)),n&&console.log(Ft.dim(`\u2502 ${n}`))}progress(e){this.quiet||!this.currentAgent||console.log(Ft.dim(`\u2502 \u2514\u2500\u2500 ${e}`))}progressList(e){if(!(this.quiet||!this.currentAgent))for(let t of e)console.log(Ft.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?Ft.green("\u2713"):Ft.red("\u2717");console.log(`\u2514\u2500 ${s} ${e?"Complete":"Failed"} ${Ft.dim(`(${n})`)}
|
|
363
|
+
`),this.currentAgent=null}status(e,t){this.quiet||console.log(`${e} ${t}`)}complete(e,t){if(this.quiet)return;let n=t?` ${Ft.dim(`[${this.formatDuration(t)}]`)}`:"";console.log(Ft.green(`\u2705 ${e}${n}`))}formatDuration(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}},ko=new za});import Fe from"chalk";function Vw(r){let e=0;for(let n of r)e=(e<<5)-e+n.charCodeAt(0),e=e&e;let t=Math.abs(e)%kd.length;return kd[t]}function Jw(r,e,t="\u25B6"){let n=Fe.dim(String(r+1).padStart(2)),o=Vw(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=Fe.green("\u2713 Complete");break;case"in_progress":a=Fe.yellow(`${t} Working...`);break;case"pending":a=Fe.gray("\u25CB Pending");break;case"failed":a=Fe.red("\u2717 Failed");break;case"blocked":a=Fe.gray("\u2298 Blocked");break;default:a=Fe.gray(`\u25CB ${e.status}`)}return` ${n} ${o} ${i} ${a}`}function qw(r){if(r.length===0)return"";let e=[];e.push(""),e.push(` ${Fe.bold.white("SUBTASK PROGRESS")}`),e.push(` ${Fe.dim("\u2500".repeat(58))}`);for(let t=0;t<r.length;t++)e.push(Jw(t,r[t]));return e.push(""),e.join(`
|
|
364
|
+
`)}function bd(r){console.log(qw(r))}var kd,Pd=w(()=>{"use strict";kd=[Fe.cyan,Fe.magenta,Fe.yellow,Fe.blue,Fe.green,Fe.redBright,Fe.magentaBright,Fe.cyanBright];l(Vw,"getDomainColor");l(Jw,"formatSubtaskLine");l(qw,"renderSubtaskProgress");l(bd,"printSubtaskProgress")});function Kw(r){return Cd.includes(r)}async function Yw(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 Xw(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(`
|
|
365
|
+
`)}var Cd,Qw,bo,xd=w(()=>{"use strict";Cd=["ship","feature","spec","cleanup","migrate"];l(Kw,"requiresReasoning");l(Yw,"reason");l(Xw,"formatPlan");Qw={requiresReasoning:Kw,reason:Yw,formatPlan:Xw,REASONING_REQUIRED_COMMANDS:Cd},bo=Qw});import Ys from"node:fs/promises";var Ga,Zw,Ye,Wa=w(()=>{"use strict";nt();ue();O();lo();Ga=class{static{l(this,"ContextBuilder")}_cache;_currentProjectId;constructor(){this._cache=new Pt({ttl:5e3,maxSize:200}),this._currentProjectId=null}async build(e,t={}){let n=await R.getProjectId(e),s=E.getGlobalProjectPath(n);return this._currentProjectId!==null&&this._currentProjectId!==n&&this._cache.clear(),this._currentProjectId=n,{projectId:n,projectPath:e,globalPath:s,paths:{now:E.getFilePath(n,"core","now.md"),next:E.getFilePath(n,"core","next.md"),context:E.getFilePath(n,"core","context.md"),shipped:E.getFilePath(n,"progress","shipped.md"),metrics:E.getFilePath(n,"progress","metrics.md"),ideas:E.getFilePath(n,"planning","ideas.md"),roadmap:E.getFilePath(n,"planning","roadmap.md"),specs:E.getFilePath(n,"planning","specs"),memory:E.getFilePath(n,"memory","context.jsonl"),patterns:E.getFilePath(n,"memory","patterns.json"),analysis:E.getFilePath(n,"analysis","repo-summary.md"),codePatterns:E.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 Ys.stat(a);(!c.mtime||u.mtimeMs>c.mtime)&&this._cache.delete(a)}catch(u){if(C(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,d])=>{try{let[m,p]=await Promise.all([Ys.readFile(d,"utf-8"),Ys.stat(d)]);return{key:u,filePath:d,content:m,mtime:p.mtimeMs}}catch(m){if(C(m))return{key:u,filePath:d,content:null,mtime:null};throw m}}),c=await Promise.all(a);for(let{key:u,filePath:d,content:m,mtime:p}of c)n[u]=m,this._cache.set(d,{content:m,mtime:p})}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 Ys.readFile(i,"utf-8");return{filePath:i,content:a}}catch(a){if(C(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 Ys.access(e),!0}catch(t){if(C(t))return!1;throw t}}getCacheStats(){return this._cache.stats()}},Zw=new Ga,Ye=Zw});import{exec as eS}from"node:child_process";import ge from"node:fs/promises";import vd from"node:os";import en from"node:path";import{promisify as tS}from"node:util";function Td(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 Ba(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sS(r){if(r.verified||r.warnings.length===0)return null;let e=` Ground Truth Warnings:
|
|
502
366
|
`;return r.warnings.forEach(t=>{e+=` - ${t}
|
|
503
367
|
`}),r.recommendations.length>0&&(e+=`
|
|
504
368
|
Recommendations:
|
|
505
369
|
`,r.recommendations.forEach(t=>{e+=` -> ${t}
|
|
506
|
-
`})),e}async function
|
|
507
|
-
`).filter(Boolean).length,n.hasUncommittedChanges&&(e.push(`${n.uncommittedFiles} uncommitted file(s)`),t.push("Commit changes before shipping"))}catch{n.gitAvailable=!1}let s=on.join(r.projectPath,"package.json");try{let i=await ge.readFile(s,"utf-8"),a=JSON.parse(i);n.currentVersion=a.version,n.hasPackageJson=!0}catch(i){if(C(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 ge.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}.*${ac(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(C(i))n.shippedExists=!1;else throw i}if(n.hasPackageJson)try{let i=await ge.readFile(s,"utf-8"),a=JSON.parse(i);n.hasTestScript=!!a.scripts?.test}catch(i){if(C(i)||i instanceof SyntaxError)n.hasTestScript=!1;else throw i}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function Kd(r){let e=[],t=[],n={},s=r.paths.next;try{let a=await ge.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(C(a))n.nextExists=!1,n.taskCount=0;else throw a}let o=r.paths.roadmap;try{let a=await ge.readFile(o,"utf-8");n.roadmapExists=!0;let c=r.params.description||r.params.feature;c&&new RegExp(ac(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(C(a))n.roadmapExists=!1;else throw a}let i=r.paths.now;try{let a=await ge.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(C(a))n.hasActiveTask=!1;else throw a}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function Yd(r){let e=[],t=[],n={},s=r.paths.now;try{let i=await ge.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(C(i))n.nowExists=!1,n.hasActiveTask=!1;else throw i}let o=r.paths.next;try{let a=((await ge.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(C(i))n.pendingTasks=0;else throw i}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function Xd(r){let e=[],t=[],n={},s=on.join(r.projectPath,".prjct/prjct.config.json");try{let i=await ge.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(C(i))n.alreadyInitialized=!1;else if(i instanceof SyntaxError)n.alreadyInitialized=!1,e.push("Existing config has invalid JSON");else throw i}let o=on.join(Bd.homedir(),".prjct-cli");try{await ge.access(o,ge.constants.W_OK),n.globalPathWritable=!0}catch(i){if(C(i))try{await ge.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 Qd(r){let e=[],t=[],n={},s=on.join(r.projectPath,".prjct/prjct.config.json");try{let a=await ge.readFile(s,"utf-8");n.hasConfig=!0,n.config=JSON.parse(a)}catch(a){if(C(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=on.join(Bd.homedir(),".prjct-cli/projects",o||"");try{await ge.access(i),n.globalStorageExists=!0}catch(a){if(C(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 Zd(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 ge.access(on.join(r.projectPath,i)),n.detectedFiles.push(i)}catch(a){if(!C(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 ge.stat(on.join(r.projectPath,i))).isDirectory()&&n.detectedSrcDirs.push(i)}catch(a){if(!C(a))throw a}return{verified:!0,actual:n,warnings:e,recommendations:t}}async function ep(r){let e=[],t=[],n={},s=r.paths.specs;try{await ge.access(s),n.specsExists=!0;let i=await ge.readdir(s);n.existingSpecs=i.filter(a=>a.endsWith(".md")),n.specCount=n.existingSpecs.length}catch(i){if(C(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 np(r,e,t){let n=tp[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 $S(r,e,t){let n=await np(r,e,t);return{...e,groundTruth:{...n,verifiedAt:new Date().toISOString(),command:r}}}function MS(r){return["done","ship","feature","spec","now","init","sync","analyze"].includes(r)}var jS,tp,FS,Mo,sp=y(()=>{"use strict";F();jS=DS(IS);l(Vd,"formatDuration");l(ac,"escapeRegex");l(RS,"formatWarnings");l(Jd,"verifyDone");l(qd,"verifyShip");l(Kd,"verifyFeature");l(Yd,"verifyNow");l(Xd,"verifyInit");l(Qd,"verifySync");l(Zd,"verifyAnalyze");l(ep,"verifySpec");tp={done:Jd,ship:qd,feature:Kd,now:Yd,init:Xd,sync:Qd,analyze:Zd,spec:ep};l(np,"verify");l($S,"prepareCommand");l(MS,"requiresVerification");FS={verify:np,prepareCommand:$S,requiresVerification:MS,verifiers:tp,formatWarnings:RS,formatDuration:Vd,escapeRegex:ac,verifyDone:Jd,verifyShip:qd,verifyFeature:Kd,verifyNow:Yd,verifyInit:Xd,verifySync:Qd,verifyAnalyze:Zd,verifySpec:ep},Mo=FS});function _S(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 NS(r){if(!r||typeof r!="string")return{detected:!1};for(let{pattern:e,type:t,description:n}of OS)if(e.test(r))return{detected:!0,type:t,pattern:e.source,description:n,message:`Potential hallucination detected: ${n}`,suggestion:_S(t)};return{detected:!1}}function LS(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 US(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 HS(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 GS(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 OS,cc,zS,fs,rp=y(()=>{"use strict";OS=[{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(_S,"getHallucinationSuggestion");l(NS,"detectHallucination");l(LS,"isSimilarError");l(US,"analyzeErrorPattern");l(HS,"generateEscalationMessage");l(GS,"generateSuggestion");cc=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=>LS(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=US(s.errors);return{status:"BLOCKED",command:e,context:t,attempts:s.attempts,duration:s.lastAttempt-s.firstAttempt,errorPattern:o,message:HS(e,o,this.maxAttempts),suggestion:GS(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 NS(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}}},zS=new cc,fs=zS});function lc(r,e){let t=cr(e),n=WS[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 BS(r,e){let t=cr(e),n=new Date(r);return n.setDate(n.getDate()+t.sprintLengthDays-1),n.setHours(23,59,59,999),n}function VS(r,e,t){let n=cr(t),s=lc(r,t),o=lc(e,t),i=s.getTime()-o.getTime(),a=Math.round(i/(1e3*60*60*24));return Math.floor(a/n.sprintLengthDays)+1}function Fo(r,e=en){let t=cr(e);if(r.length===0)return{sprints:[],averageVelocity:0,velocityTrend:"stable",estimationAccuracy:0,overEstimated:[],underEstimated:[],lastUpdated:new Date().toISOString()};let n=JS(r,e),s=qS(n,t.accuracyTolerance),o=s.slice(-t.windowSize),i=XS(o),a=KS(o),c=YS(r,t.accuracyTolerance),{overEstimated:u,underEstimated:d}=QS(r);return{sprints:s,averageVelocity:i,velocityTrend:a,estimationAccuracy:c,overEstimated:u,underEstimated:d,lastUpdated:new Date().toISOString()}}function ip(r,e,t=en){let n=cr(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 JS(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=VS(i,s,e);if(!t.has(a)){let c=lc(i,e),u=BS(c,e);t.set(a,{sprintNumber:a,startDate:c,endDate:u,outcomes:[]})}t.get(a).outcomes.push(o)}return t}function qS(r,e){let t=[];for(let[,n]of r){let s=n.outcomes.reduce((u,d)=>u+ZS(d),0),o=n.outcomes.filter(u=>u.variance).map(u=>dc(u)),i=o.length>0?Math.round(o.reduce((u,d)=>u+d,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 KS(r){if(r.length<3)return"stable";let e=r.map(d=>d.pointsCompleted),t=e.length,n=0,s=0,o=0,i=0;for(let d=0;d<t;d++)n+=d,s+=e[d],o+=d*e[d],i+=d*d;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 YS(r,e){let t=r.filter(s=>s.variance);if(t.length===0)return 0;let n=t.filter(s=>{let o=dc(s);return Math.abs(o)<=e});return Math.round(n.length/t.length*100)}function XS(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 QS(r){let e=new Map;for(let s of r){if(!s.variance)continue;let o=dc(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 dc(r){if(!r.variance)return 0;let e=uc(r.estimatedDuration),t=uc(r.actualDuration);return e<=0?0:Math.round((t-e)/e*100)}function uc(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 ap(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(`
|
|
508
|
-
`)}function
|
|
370
|
+
`})),e}async function Ed(r){let e=[],t=[],n={},s=r.paths.now;try{let a=await ge.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=Td(n.durationMs))}}catch(a){if(C(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 ge.readFile(o,"utf-8");n.nextExists=!0;let c=a.match(/- \[ \]/g)||[];n.pendingTasks=c.length}catch(a){if(C(a))n.nextExists=!1,n.pendingTasks=0;else throw a}let i=r.paths.metrics;try{await ge.access(en.dirname(i),ge.constants.W_OK),n.metricsWritable=!0}catch(a){if(C(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 Ad(r){let e=[],t=[],n={};try{let{stdout:i}=await nS("git status --porcelain",{cwd:r.projectPath});n.hasUncommittedChanges=i.trim().length>0,n.uncommittedFiles=i.trim().split(`
|
|
371
|
+
`).filter(Boolean).length,n.hasUncommittedChanges&&(e.push(`${n.uncommittedFiles} uncommitted file(s)`),t.push("Commit changes before shipping"))}catch{n.gitAvailable=!1}let s=en.join(r.projectPath,"package.json");try{let i=await ge.readFile(s,"utf-8"),a=JSON.parse(i);n.currentVersion=a.version,n.hasPackageJson=!0}catch(i){if(C(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 ge.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}.*${Ba(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(C(i))n.shippedExists=!1;else throw i}if(n.hasPackageJson)try{let i=await ge.readFile(s,"utf-8"),a=JSON.parse(i);n.hasTestScript=!!a.scripts?.test}catch(i){if(C(i)||i instanceof SyntaxError)n.hasTestScript=!1;else throw i}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function Id(r){let e=[],t=[],n={},s=r.paths.next;try{let a=await ge.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(C(a))n.nextExists=!1,n.taskCount=0;else throw a}let o=r.paths.roadmap;try{let a=await ge.readFile(o,"utf-8");n.roadmapExists=!0;let c=r.params.description||r.params.feature;c&&new RegExp(Ba(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(C(a))n.roadmapExists=!1;else throw a}let i=r.paths.now;try{let a=await ge.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(C(a))n.hasActiveTask=!1;else throw a}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function Dd(r){let e=[],t=[],n={},s=r.paths.now;try{let i=await ge.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(C(i))n.nowExists=!1,n.hasActiveTask=!1;else throw i}let o=r.paths.next;try{let a=((await ge.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(C(i))n.pendingTasks=0;else throw i}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function Rd(r){let e=[],t=[],n={},s=en.join(r.projectPath,".prjct/prjct.config.json");try{let i=await ge.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(C(i))n.alreadyInitialized=!1;else if(i instanceof SyntaxError)n.alreadyInitialized=!1,e.push("Existing config has invalid JSON");else throw i}let o=en.join(vd.homedir(),".prjct-cli");try{await ge.access(o,ge.constants.W_OK),n.globalPathWritable=!0}catch(i){if(C(i))try{await ge.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 jd(r){let e=[],t=[],n={},s=en.join(r.projectPath,".prjct/prjct.config.json");try{let a=await ge.readFile(s,"utf-8");n.hasConfig=!0,n.config=JSON.parse(a)}catch(a){if(C(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=en.join(vd.homedir(),".prjct-cli/projects",o||"");try{await ge.access(i),n.globalStorageExists=!0}catch(a){if(C(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 $d(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 ge.access(en.join(r.projectPath,i)),n.detectedFiles.push(i)}catch(a){if(!C(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 ge.stat(en.join(r.projectPath,i))).isDirectory()&&n.detectedSrcDirs.push(i)}catch(a){if(!C(a))throw a}return{verified:!0,actual:n,warnings:e,recommendations:t}}async function Md(r){let e=[],t=[],n={},s=r.paths.specs;try{await ge.access(s),n.specsExists=!0;let i=await ge.readdir(s);n.existingSpecs=i.filter(a=>a.endsWith(".md")),n.specCount=n.existingSpecs.length}catch(i){if(C(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 Fd(r,e,t){let n=Od[r];if(!n)return{verified:!0,actual:{},warnings:[],recommendations:[]};try{return await n(e,t)}catch(s){return{verified:!1,actual:{},warnings:[`Verification error: ${y(s)}`],recommendations:["Check file permissions and project configuration"]}}}async function rS(r,e,t){let n=await Fd(r,e,t);return{...e,groundTruth:{...n,verifiedAt:new Date().toISOString(),command:r}}}function oS(r){return["done","ship","feature","spec","now","init","sync","analyze"].includes(r)}var nS,Od,iS,Po,_d=w(()=>{"use strict";O();nS=tS(eS);l(Td,"formatDuration");l(Ba,"escapeRegex");l(sS,"formatWarnings");l(Ed,"verifyDone");l(Ad,"verifyShip");l(Id,"verifyFeature");l(Dd,"verifyNow");l(Rd,"verifyInit");l(jd,"verifySync");l($d,"verifyAnalyze");l(Md,"verifySpec");Od={done:Ed,ship:Ad,feature:Id,now:Dd,init:Rd,sync:jd,analyze:$d,spec:Md};l(Fd,"verify");l(rS,"prepareCommand");l(oS,"requiresVerification");iS={verify:Fd,prepareCommand:rS,requiresVerification:oS,verifiers:Od,formatWarnings:sS,formatDuration:Td,escapeRegex:Ba,verifyDone:Ed,verifyShip:Ad,verifyFeature:Id,verifyNow:Dd,verifyInit:Rd,verifySync:jd,verifyAnalyze:$d,verifySpec:Md},Po=iS});function cS(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 lS(r){if(!r||typeof r!="string")return{detected:!1};for(let{pattern:e,type:t,description:n}of aS)if(e.test(r))return{detected:!0,type:t,pattern:e.source,description:n,message:`Potential hallucination detected: ${n}`,suggestion:cS(t)};return{detected:!1}}function uS(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 dS(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 pS(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 mS(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 aS,Va,gS,ns,Nd=w(()=>{"use strict";aS=[{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(cS,"getHallucinationSuggestion");l(lS,"detectHallucination");l(uS,"isSimilarError");l(dS,"analyzeErrorPattern");l(pS,"generateEscalationMessage");l(mS,"generateSuggestion");Va=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=>uS(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=dS(s.errors);return{status:"BLOCKED",command:e,context:t,attempts:s.attempts,duration:s.lastAttempt-s.firstAttempt,errorPattern:o,message:pS(e,o,this.maxAttempts),suggestion:mS(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 lS(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}}},gS=new Va,ns=gS});function Ja(r,e){let t=Xs(e),n=fS[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 hS(r,e){let t=Xs(e),n=new Date(r);return n.setDate(n.getDate()+t.sprintLengthDays-1),n.setHours(23,59,59,999),n}function yS(r,e,t){let n=Xs(t),s=Ja(r,t),o=Ja(e,t),i=s.getTime()-o.getTime(),a=Math.round(i/(1e3*60*60*24));return Math.floor(a/n.sprintLengthDays)+1}function Co(r,e=qt){let t=Xs(e);if(r.length===0)return{sprints:[],averageVelocity:0,velocityTrend:"stable",estimationAccuracy:0,overEstimated:[],underEstimated:[],lastUpdated:new Date().toISOString()};let n=wS(r,e),s=SS(n,t.accuracyTolerance),o=s.slice(-t.windowSize),i=PS(o),a=kS(o),c=bS(r,t.accuracyTolerance),{overEstimated:u,underEstimated:d}=CS(r);return{sprints:s,averageVelocity:i,velocityTrend:a,estimationAccuracy:c,overEstimated:u,underEstimated:d,lastUpdated:new Date().toISOString()}}function Ud(r,e,t=qt){let n=Xs(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 wS(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=yS(i,s,e);if(!t.has(a)){let c=Ja(i,e),u=hS(c,e);t.set(a,{sprintNumber:a,startDate:c,endDate:u,outcomes:[]})}t.get(a).outcomes.push(o)}return t}function SS(r,e){let t=[];for(let[,n]of r){let s=n.outcomes.reduce((u,d)=>u+xS(d),0),o=n.outcomes.filter(u=>u.variance).map(u=>Ka(u)),i=o.length>0?Math.round(o.reduce((u,d)=>u+d,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 kS(r){if(r.length<3)return"stable";let e=r.map(d=>d.pointsCompleted),t=e.length,n=0,s=0,o=0,i=0;for(let d=0;d<t;d++)n+=d,s+=e[d],o+=d*e[d],i+=d*d;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 bS(r,e){let t=r.filter(s=>s.variance);if(t.length===0)return 0;let n=t.filter(s=>{let o=Ka(s);return Math.abs(o)<=e});return Math.round(n.length/t.length*100)}function PS(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 CS(r){let e=new Map;for(let s of r){if(!s.variance)continue;let o=Ka(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 Ka(r){if(!r.variance)return 0;let e=qa(r.estimatedDuration),t=qa(r.actualDuration);return e<=0?0:Math.round((t-e)/e*100)}function qa(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 Hd(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(`
|
|
372
|
+
`)}function xS(r){if(!r.estimatedDuration)return 0;let e=qa(r.estimatedDuration);if(e<=0)return 0;let t=Ld[0],n=Number.POSITIVE_INFINITY;for(let s of Ld){let o=Math.abs(s.typical-e);o<n&&(n=o,t=s)}return t.points}function Xs(r){return{sprintLengthDays:r.sprintLengthDays??7,startDay:r.startDay??"monday",windowSize:r.windowSize??6,accuracyTolerance:r.accuracyTolerance??20}}var fS,Ld,Ya=w(()=>{"use strict";Un();fS={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};l(Ja,"getSprintStart");l(hS,"getSprintEnd");l(yS,"getSprintNumber");l(Co,"calculateVelocity");l(Ud,"projectCompletion");l(wS,"bucketBySprint");l(SS,"buildSprintVelocities");l(kS,"detectTrend");l(bS,"calculateOverallAccuracy");l(PS,"calculateAverageVelocity");l(CS,"detectEstimationPatterns");l(Ka,"parseVariancePercent");l(qa,"parseDurationMinutes");l(Hd,"formatVelocityContext");Ld=[{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(xS,"derivePoints");l(Xs,"resolveConfig")});import{exec as vS}from"node:child_process";import TS from"node:fs/promises";import xo from"node:path";import{promisify as ES}from"node:util";async function zd(r,e,t={}){let n=Date.now(),s=t.maxFiles??30,o=t.minScore??.1,i=t.includeTests??!1,a=jS(r),c=await $S(e),u=await MS(e),d=[];for(let p of c){if(!i&&FS(p))continue;let g=OS(p,a,u);g.score>=o&&d.push(g)}d.sort((p,g)=>g.score-p.score);let m=d.slice(0,s);return{files:m,metrics:{filesScanned:c.length,filesReturned:m.length,scanDuration:Date.now()-n}}}function jS(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 $S(r){let e=[];async function t(n,s=""){try{let o=await TS.readdir(n,{withFileTypes:!0});for(let i of o){let a=xo.join(n,i.name),c=xo.join(s,i.name);if(i.isDirectory()){if(RS.has(i.name)||i.name.startsWith("."))continue;await t(a,c)}else if(i.isFile()){let u=xo.extname(i.name).toLowerCase();DS.has(u)&&e.push(c)}}}catch(o){C(o)}}return l(t,"walk"),await t(r),e}async function MS(r){let e=new Map;try{let{stdout:t}=await AS(`git log -30 --pretty=format:"%H %ct" --name-only | awk '
|
|
509
373
|
/^[a-f0-9]{40}/ { commit=$1; timestamp=$2; next }
|
|
510
374
|
NF { files[$0]++; if (!lastmod[$0]) lastmod[$0]=timestamp }
|
|
511
375
|
END { for (f in files) print files[f], lastmod[f], f }
|
|
512
376
|
'`,{cwd:r,maxBuffer:10485760}),n=Math.floor(Date.now()/1e3),s=t.trim().split(`
|
|
513
|
-
`).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],d=Math.floor((n-c)/86400);e.set(u,{commits:a,daysAgo:d})}}}catch{}return e}function
|
|
377
|
+
`).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],d=Math.floor((n-c)/86400);e.set(u,{commits:a,daysAgo:d})}}}catch{}return e}function OS(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(IS))for(let S of f)if(c.includes(S)&&e.some(D=>f.includes(D)||D.includes(g)||g.includes(D))){o+=.4,n.push(`domain:${g}`);break}o=Math.min(1,o);let d=t.get(r);d&&(d.daysAgo<=1?(i=1,n.push("recent:1d")):d.daysAgo<=3?(i=.8,n.push("recent:3d")):d.daysAgo<=7?(i=.6,n.push("recent:1w")):d.daysAgo<=30&&(i=.3,n.push("recent:1m")),d.commits>=5&&(i=Math.min(1,i+.2)));let m=xo.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 p=s*.6+o*.2+i*.15+a*.05;return{path:r,score:Math.min(1,p),reasons:[...new Set(n)]}}function FS(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 AS,IS,DS,RS,Gd=w(()=>{"use strict";O();AS=ES(vS),IS={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"]},DS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".swift",".rb",".php",".c",".cpp",".h",".hpp",".cs",".vue",".svelte"]),RS=new Set(["node_modules",".git","dist","build",".next",".nuxt",".output","coverage",".cache","__pycache__",".pytest_cache","vendor","target",".turbo",".vercel"]);l(zd,"findRelevantFiles");l(jS,"extractKeywords");l($S,"getAllCodeFiles");l(MS,"getGitRecency");l(OS,"scoreFile");l(FS,"isTestFile")});import{exec as _S}from"node:child_process";import{promisify as NS}from"node:util";async function Wd(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 HS(r);o=c.hotFiles,i=c.branchOnlyFiles,a=c.analysisWindow}else o=await US(r,t);return o=o.filter(c=>!zS(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 US(r,e){let{stdout:t}=await Qs(`git log -${e} --pretty=format:"%ct" --name-only | awk '
|
|
514
378
|
/^[0-9]+$/ { timestamp=$1; next }
|
|
515
379
|
NF {
|
|
516
380
|
count[$0]++
|
|
@@ -520,8 +384,8 @@ Recommendations:
|
|
|
520
384
|
for (f in count) print count[f], lastmod[f], f
|
|
521
385
|
}
|
|
522
386
|
' | sort -rn`,{cwd:r,maxBuffer:10485760}),n=[],s=t.trim().split(`
|
|
523
|
-
`).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),d=parseInt(c[2],10),m=c[3],p=o-d,g=Math.floor(p/86400),f=Math.floor(p/3600),S=Math.max(0,1-g/30),
|
|
524
|
-
`).filter(Boolean),{stdout:i}=await
|
|
387
|
+
`).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),d=parseInt(c[2],10),m=c[3],p=o-d,g=Math.floor(p/86400),f=Math.floor(p/3600),S=Math.max(0,1-g/30),b=u/i,D=S*.6+b*.4,j;f<1?j="just now":f<24?j=`${f}h ago`:g<7?j=`${g}d ago`:g<30?j=`${Math.floor(g/7)}w ago`:j=`${Math.floor(g/30)}mo ago`,n.push({path:m,changes:u,heatScore:Math.round(D*100)/100,lastChanged:j,lastChangedAt:new Date(d*1e3).toISOString()})}return n.sort((a,c)=>c.heatScore-a.heatScore)}async function HS(r){let{stdout:e}=await Qs("git branch --show-current",{cwd:r}),t=e.trim(),n="main";try{await Qs("git rev-parse --verify main",{cwd:r})}catch{n="master"}let{stdout:s}=await Qs(`git diff --name-only ${n}...HEAD`,{cwd:r}),o=s.trim().split(`
|
|
388
|
+
`).filter(Boolean),{stdout:i}=await Qs(`git log ${n}..HEAD --pretty=format:"%ct" --name-only | awk '
|
|
525
389
|
/^[0-9]+$/ { timestamp=$1; next }
|
|
526
390
|
NF {
|
|
527
391
|
count[$0]++
|
|
@@ -531,10 +395,10 @@ Recommendations:
|
|
|
531
395
|
for (f in count) print count[f], lastmod[f], f
|
|
532
396
|
}
|
|
533
397
|
'`,{cwd:r,maxBuffer:10*1024*1024}),a=[],c=i.trim().split(`
|
|
534
|
-
`).filter(Boolean),u=Math.floor(Date.now()/1e3),d=1;for(let m of c){let p=m.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(p){let g=parseInt(p[1],10);g>d&&(d=g)}}for(let m of c){let p=m.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(!p)continue;let g=parseInt(p[1],10),f=parseInt(p[2],10),S=p[3],
|
|
535
|
-
`);return{file:r,language:o,signatures:a,fallback:!1,metrics:
|
|
398
|
+
`).filter(Boolean),u=Math.floor(Date.now()/1e3),d=1;for(let m of c){let p=m.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(p){let g=parseInt(p[1],10);g>d&&(d=g)}}for(let m of c){let p=m.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(!p)continue;let g=parseInt(p[1],10),f=parseInt(p[2],10),S=p[3],b=u-f,D=Math.floor(b/86400),j=Math.floor(b/3600),q=Math.max(0,1-D/14),Re=g/d,Be=q*.5+Re*.5,gt;j<1?gt="just now":j<24?gt=`${j}h ago`:gt=`${D}d ago`,a.push({path:S,changes:g,heatScore:Math.round(Be*100)/100,lastChanged:gt,lastChangedAt:new Date(f*1e3).toISOString()})}return{hotFiles:a.sort((m,p)=>p.heatScore-m.heatScore),branchOnlyFiles:o,analysisWindow:`${n}..HEAD`}}function zS(r){let e=r.split("/").pop()||"";for(let t of LS)if(t.startsWith("*.")){if(e.endsWith(t.slice(1)))return!0}else if(e===t)return!0;return!1}var Qs,LS,Bd=w(()=>{"use strict";Qs=NS(_S),LS=["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb",".gitignore",".env",".env.local","*.md","CHANGELOG.md","LICENSE"];l(Wd,"getRecentFiles");l(US,"getHotFilesFromCommits");l(HS,"getBranchOnlyFiles");l(zS,"shouldIgnore")});function Xa(r){return!r||r.length===0?0:Math.ceil(r.length/4)}function Vd(r,e){let t=GS[e],n=r/1e3*t.input,s=r/1e3*t.output*.3;return{inputSaved:n,outputPotential:s,total:n+s}}function BS(r){return r<.001?"<$0.01":r<.01?`$${r.toFixed(3)}`:`$${r.toFixed(2)}`}function qd(r,e){let t=Xa(r),n=Xa(e),s=Math.max(0,t-n),o=t>0?(t-n)/t:0,i=Vd(s,WS),a=Jd.map(c=>({model:c,...Vd(s,c)}));return{tokens:{original:t,filtered:n,saved:s},compression:Math.max(0,Math.min(1,o)),cost:{saved:i.total,formatted:BS(i.total),byModel:a}}}function Qa(r){let e=Xa(r);return{tokens:{original:e,filtered:e,saved:0},compression:0,cost:{saved:0,formatted:"$0.00",byModel:Jd.map(t=>({model:t,inputSaved:0,outputPotential:0,total:0}))}}}var GS,WS,Jd,Kd=w(()=>{"use strict";GS={"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}},WS="claude-sonnet-4.5";l(Xa,"countTokens");Jd=["claude-sonnet-4.5","claude-opus-4.5","claude-opus-4-6","gpt-4o","gemini-1.5-pro"];l(Vd,"calculateModelCost");l(BS,"formatCostSaved");l(qd,"measureCompression");l(Qa,"noCompression")});import VS from"node:fs/promises";import Za from"node:path";async function Qd(r,e=process.cwd()){let t=Za.isAbsolute(r)?r:Za.join(e,r),n;try{n=await VS.readFile(t,"utf-8")}catch(u){if(C(u))return{file:r,language:"unknown",signatures:[],fallback:!0,fallbackReason:"File not found",metrics:Qa("")};throw u}let s=Za.extname(r).toLowerCase(),o=JS[s]||"unknown",i=XS[o];if(!i||i.length===0)return{file:r,language:o,signatures:[],fallback:!0,fallbackReason:`No extraction patterns for ${o}`,metrics:Qa(n)};let a=QS(n,i),c=a.map(u=>`${u.exported?"export ":""}${u.type} ${u.name}: ${u.signature}`).join(`
|
|
399
|
+
`);return{file:r,language:o,signatures:a,fallback:!1,metrics:qd(n,c)}}function QS(r,e){let t=[],n=r.split(`
|
|
536
400
|
`),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,d=r.substring(0,u).split(`
|
|
537
|
-
`).length,m=i[0].trim(),p;if(d>1){let g=n[d-2]?.trim();(g?.startsWith("/**")||g?.startsWith("///")||g?.startsWith("#"))&&(p=g)}t.push({type:o.type,name:a,signature:
|
|
401
|
+
`).length,m=i[0].trim(),p;if(d>1){let g=n[d-2]?.trim();(g?.startsWith("/**")||g?.startsWith("///")||g?.startsWith("#"))&&(p=g)}t.push({type:o.type,name:a,signature:ZS(m),exported:o.exported||!1,line:d,docstring:p})}}return t.sort((o,i)=>o.line-i.line)}function ZS(r){return r.replace(/\{$/,"").replace(/\s+/g," ").trim()}var JS,Yd,qS,KS,YS,Xd,XS,Zd=w(()=>{"use strict";O();Kd();JS={".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"},Yd=[{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}],qS=[{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}],KS=[{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}],YS=[{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}],Xd=[{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}],XS={typescript:Yd,javascript:Yd,python:qS,go:KS,rust:YS,java:Xd,csharp:Xd,php:[],ruby:[],unknown:[]};l(Qd,"extractSignatures");l(QS,"extractFromContent");l(ZS,"cleanSignature")});import{createHash as ek}from"node:crypto";import np from"node:fs/promises";import sp from"node:path";function ep(r){return ek("sha256").update(r.toLowerCase().trim()).digest("hex").slice(0,16)}async function tp(r){try{let e=sp.join(r,"storage","classification-cache.json"),t=await np.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return C(e)?Ii:(console.warn("[classifier] Failed to load cache:",y(e)),Ii)}}async function ec(r,e){try{let t=sp.join(r,"storage","classification-cache.json");await np.writeFile(t,JSON.stringify(e,null,2))}catch(t){console.warn("[classifier] Failed to save cache:",y(t))}}function nk(r,e,t){let n=r.entries[e];return!n||n.projectId!==t||Date.now()-new Date(n.classifiedAt).getTime()>tk?null:n.classification}function sk(r,e){return r.confirmedPatterns.find(n=>n.descriptionHash===e)?.classification??null}async function rk(r,e){let t=process.env.ANTHROPIC_API_KEY;if(!t)return null;let n=rp(e),s=ji("classification")||"",o=`Classify this software engineering task into a domain.
|
|
538
402
|
|
|
539
403
|
Task: "${r}"
|
|
540
404
|
|
|
@@ -542,19 +406,19 @@ Available domains in this project: ${n.join(", ")}
|
|
|
542
406
|
Available agents: ${e.agents.join(", ")||"none"}
|
|
543
407
|
Stack: ${e.stack?.language||"unknown"} / ${e.stack?.framework||"unknown"}
|
|
544
408
|
|
|
545
|
-
${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),d=
|
|
546
|
-
`);return{path:c.path,content:d}}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([
|
|
547
|
-
`).filter(Boolean),i=0,a=0,c=0;for(let m of o){let p=m.substring(0,2);p.startsWith("??")?a++:p[0]!==" "&&p[0]!=="?"?c++:i++}let u=[];c>0&&u.push(`${c} staged`),i>0&&u.push(`${i} modified`),a>0&&u.push(`${a} untracked`);let d=u.length>0?u.join(", "):"clean";return{branch:s,status:d}}catch{return{branch:"unknown",status:"git unavailable"}}}async loadSealedAnalysis(e){try{let t=await
|
|
548
|
-
`)}_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`}},
|
|
549
|
-
`);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=
|
|
409
|
+
${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),d=Jt.safeParse(u);return d.success?d.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 ik(r,e){let t=rp(e),n=new Map;for(let[p,g]of Object.entries(ok)){if(p==="general"||!t.includes(p))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(p,f)}if(n.size===0)return Jl;let s=Array.from(n.entries()).sort((p,g)=>g[1]-p[1]),o=s[0][0],i=s[0][1],a=s.slice(1,3).map(([p])=>p),c=s.reduce((p,[,g])=>p+g,0),u=Math.min(.85,i/c+.2),d=ak(o),m=e.agents.filter(p=>p===o||p.includes(o)||o.includes(p.replace(".md","")));return{primaryDomain:o,secondaryDomains:a,confidence:u,filePatterns:d,relevantAgents:m}}function rp(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 ak(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 tk,ok,tc,ck,op,ip=w(()=>{"use strict";Ms();xr();O();tk=3600*1e3;l(ep,"hashDescription");l(tp,"loadCache");l(ec,"saveCache");l(nk,"lookupCache");l(sk,"lookupPatterns");l(rk,"classifyWithLLM");ok={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(ik,"classifyWithHeuristic");l(rp,"buildAvailableDomains");l(ak,"getFilePatterns");tc=class{static{l(this,"DomainClassifier")}async classify(e,t,n,s){let o=ep(e),i=await tp(n),a=nk(i,o,t);if(a)return{classification:a,source:"cache"};let c=sk(i,o);if(c)return{classification:c,source:"history"};let u=await rk(e,s);if(u)return i.entries[o]={classification:u,classifiedAt:new Date().toISOString(),source:"llm",descriptionHash:o,projectId:t},await ec(n,i),{classification:u,source:"llm"};let d=ik(e,s);return i.entries[o]={classification:d,classifiedAt:new Date().toISOString(),source:"heuristic",descriptionHash:o,projectId:t},await ec(n,i),{classification:d,source:"heuristic"}}async confirmClassification(e,t,n){let s=ep(e),o=await tp(n);o.confirmedPatterns.some(i=>i.descriptionHash===s)||(o.confirmedPatterns.push({descriptionHash:s,classification:t,confirmedAt:new Date().toISOString(),taskDescription:e}),await ec(n,o))}},ck=new tc,op=ck});import{exec as lk}from"node:child_process";import Zs from"node:fs/promises";import uk from"node:os";import Cn from"node:path";import{promisify as dk}from"node:util";var ap,cp,nc,pk,vo,sc=w(()=>{"use strict";Ya();nt();ue();Un();Mt();Gd();Bd();Zd();O();Pn();ip();Jn();ap=dk(lk),cp=["database","backend","frontend","testing","devops"],nc=class{static{l(this,"OrchestratorExecutor")}async execute(e,t,n){let s=await R.getProjectId(n),o=E.getGlobalProjectPath(s),i=await this.loadRepoAnalysis(o),{domains:a,primary:c}=await this.detectDomains(t,s,i),u=await this.loadAgents(a,s),d=await this.loadSkills(u),[m,p,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:d,requiresFragmentation:f,subtasks:S,project:{id:s,ecosystem:i?.ecosystem||"unknown",conventions:i?.conventions||[]},realContext:m,sealedAnalysis:p,velocityContext:g}}async gatherRealContext(e,t){try{let[n,s,o]=await Promise.all([this.getGitState(t),zd(e,t,{maxFiles:10,minScore:.15}),Wd(t,{commits:10,maxFiles:10})]),i=s.files.slice(0,3),a=await Promise.all(i.map(async c=>{try{let u=await Qd(c.path,t);if(u.signatures.length===0)return null;let d=u.signatures.map(m=>`${m.exported?"export ":""}${m.type} ${m.name}: ${m.signature}`).join(`
|
|
410
|
+
`);return{path:c.path,content:d}}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([ap("git branch --show-current",{cwd:e}),ap("git status --porcelain",{cwd:e})]),s=t.stdout.trim()||"main",o=n.stdout.trim().split(`
|
|
411
|
+
`).filter(Boolean),i=0,a=0,c=0;for(let m of o){let p=m.substring(0,2);p.startsWith("??")?a++:p[0]!==" "&&p[0]!=="?"?c++:i++}let u=[];c>0&&u.push(`${c} staged`),i>0&&u.push(`${i} modified`),a>0&&u.push(`${a} untracked`);let d=u.length>0?u.join(", "):"clean";return{branch:s,status:d}}catch{return{branch:"unknown",status:"git unavailable"}}}async loadSealedAnalysis(e){try{let t=await $t.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 Ke.getAll(e);if(t.length===0)return null;let n=Co(t,qt);return n.sprints.length===0?null:Hd(n)}catch{return null}}async loadRepoAnalysis(e){try{let t=Cn.join(e,"analysis","repo-analysis.json"),n=await Zs.readFile(t,"utf-8");return JSON.parse(n)}catch(t){return C(t)||console.warn("Failed to load repo-analysis.json:",y(t)),null}}async detectDomains(e,t,n){let s=E.getGlobalProjectPath(t),o=await this.getAvailableAgentNames(s),i={hasFrontend:!1,hasBackend:!0,hasDatabase:!1,hasTesting:!1,hasDocker:!1};try{let m=await F.read(t);m.domains&&(i=m.domains)}catch{}let a={domains:i,agents:o,stack:n?{language:n.ecosystem}:void 0},{classification:c}=await op.classify(e,t,s,a),d=[c.primaryDomain,...c.secondaryDomains].filter(m=>o.some(p=>p===m||p.includes(m)||m.includes(p.replace(".md",""))));return d.length===0?{domains:["general"],primary:"general"}:{domains:d,primary:d[0]}}async getAvailableAgentNames(e){try{let t=Cn.join(e,"agents");return(await Zs.readdir(t)).filter(s=>s.endsWith(".md")).map(s=>s.replace(".md",""))}catch{return[]}}async loadAgents(e,t){let n=E.getGlobalProjectPath(t),s=Cn.join(n,"agents"),o=e.map(async a=>{let c=[`${a}.md`,`${a}-agent.md`,`prjct-${a}.md`];for(let u of c){let d=Cn.join(s,u);try{let m=await Zs.readFile(d,"utf-8"),{frontmatter:p,body:g}=this.parseAgentFile(m);return{name:u.replace(".md",""),domain:a,content:g,skills:p.skills||[],filePath:d,effort:p.effort,model:p.model}}catch{}}return null});return(await Promise.all(o)).filter(a=>a!==null)}parseAgentFile(e){let t=$r(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=Cn.join(uk.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=Cn.join(t,`${i}.md`),c=Cn.join(t,i,"SKILL.md");try{let u=await Zs.readFile(c,"utf-8");return{name:i,content:u,filePath:c}}catch{try{let u=await Zs.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=cp.indexOf(a),d=cp.indexOf(c);return(u===-1?99:u)-(d===-1?99:d)}),i=o.map((a,c)=>{let u=n.find(p=>p.domain===a),d=u?`${u.name}.md`:`${a}.md`,m=o.slice(0,c).map((p,g)=>`subtask-${g+1}`);return{id:`subtask-${c+1}`,description:this.generateSubtaskDescription(e,a),domain:a,agent:d,status:c===0?"in_progress":"pending",dependsOn:m,order:c+1}});return await F.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?"...":""}`}},pk=new nc,vo=pk});function mk(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 rc,gk,be,lp=w(()=>{"use strict";yt();se();Yt();Yt();l(mk,"generateApprovalPrompt");rc=class{static{l(this,"PlanMode")}activePlans;constructor(){this.activePlans=new Map}requiresPlanning(e){return ca.includes(e)}isDestructive(e){return la.includes(e)}isToolAllowedInPlanning(e){return Xr.includes(e)}getAllowedTools(e,t){return e?t.filter(n=>Xr.includes(n)):t}startPlanning(e,t,n){let s={id:oe(),projectId:e,command:t,params:n,status:Y.GATHERING,startedAt:k(),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?[Y.GATHERING,Y.ANALYZING,Y.PROPOSING,Y.PENDING_APPROVAL].includes(t.status):!1}recordGatheredInfo(e,t){let n=this.getActivePlan(e);n&&n.gatheredInfo.push({...t,gatheredAt:k()})}updateStatus(e,t){let n=this.getActivePlan(e);n&&(n.status=t,t===Y.APPROVED?n.approvedAt=k():t===Y.EXECUTING?n.executionStartedAt=k():(t===Y.COMPLETED||t===Y.ABORTED)&&(n.completedAt=k()))}setAnalysis(e,t){let n=this.getActivePlan(e);n&&(n.analysis=t,n.status=Y.ANALYZING)}proposePlan(e,t){let n=this.getActivePlan(e);return n?(n.proposedPlan=t,n.status=Y.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!==Y.PENDING_APPROVAL?null:(n.userFeedback=t,n.status=Y.APPROVED,n.approvedAt=k(),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=Y.REJECTED,n.userFeedback=t,n.completedAt=k(),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!==Y.APPROVED?null:(t.status=Y.EXECUTING,t.executionStartedAt=k(),t.currentStep=0,this.getNextStep(e))}getNextStep(e){let t=this.getActivePlan(e);if(!t||t.status!==Y.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!==Y.EXECUTING?null:(n.steps[n.currentStep].status="completed",n.steps[n.currentStep].result=t,n.steps[n.currentStep].completedAt=k(),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=Y.COMPLETED,t.completedAt=k();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=Y.ABORTED,n.completedAt=k(),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 mk(e,t)}formatStatus(e){let t=this.getActivePlan(e);if(!t)return"No active plan";let s=[`${{[Y.GATHERING]:"\u{1F50D}",[Y.ANALYZING]:"\u{1F9E0}",[Y.PROPOSING]:"\u{1F4DD}",[Y.PENDING_APPROVAL]:"\u23F3",[Y.APPROVED]:"\u2705",[Y.EXECUTING]:"\u26A1",[Y.COMPLETED]:"\u{1F389}",[Y.REJECTED]:"\u274C",[Y.ABORTED]:"\u{1F6D1}"}[t.status]||"\u{1F4CB}"} Plan: ${t.command}`,`Status: ${t.status}`];if(t.status===Y.EXECUTING){let o=Math.round(t.currentStep/t.steps.length*100);s.push(`Progress: ${t.currentStep}/${t.steps.length} (${o}%)`)}return s.join(`
|
|
412
|
+
`)}_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`}},gk=new rc,be=gk});function fk(r){let e=r.trim().toLowerCase(),t=e.replace(/[.\s-]/g,"");return To[t]?To[t]:To[e]?To[e]:e}function Eo(r){let e=new Set,t=[];for(let n of r){let s=fk(n);e.has(s)||(e.add(s),t.push(n))}return t}var To,oc=w(()=>{"use strict";To={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(fk,"normalizeFrameworkName");l(Eo,"deduplicateTechStack")});import{z as Pe}from"zod";function up(r){let e=[];e.push(`## CONSTRAINTS (Read Before Acting)
|
|
413
|
+
`);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=Eo(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])=>hk[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(`
|
|
550
414
|
Context: ${r.fileCount} files in project.`),e.join(`
|
|
551
|
-
`)}var
|
|
552
|
-
`,"utf-8"),
|
|
553
|
-
${[["project",r.projectName],["path",r.projectPath],["git",r.isGitRepo?"true":"false"],["branch",r.gitBranch],["platform",
|
|
415
|
+
`)}var Fj,hk,dp=w(()=>{"use strict";oc();Fj=Pe.object({projectPath:Pe.string(),language:Pe.string().optional(),framework:Pe.string().optional(),techStack:Pe.array(Pe.string()).default([]),domains:Pe.object({hasFrontend:Pe.boolean().default(!1),hasBackend:Pe.boolean().default(!1),hasDatabase:Pe.boolean().default(!1),hasTesting:Pe.boolean().default(!1),hasDocker:Pe.boolean().default(!1)}).optional(),fileCount:Pe.number().optional(),availableAgents:Pe.array(Pe.string()).default([]),analysisLanguages:Pe.array(Pe.string()).default([]),analysisFrameworks:Pe.array(Pe.string()).default([]),analysisPackageManager:Pe.string().optional()}),hk={hasFrontend:"Frontend (UI/components)",hasBackend:"Backend (APIs/servers)",hasDatabase:"Database (SQL/ORM)",hasTesting:"Testing (unit/integration)",hasDocker:"Docker/containers"};l(up,"buildAntiHallucinationBlock")});import{z as vt}from"zod";var yk,pp,mp=w(()=>{"use strict";yk=vt.object({agents:vt.boolean(),patterns:vt.boolean(),checklist:vt.boolean(),modules:vt.array(vt.string())}),pp=vt.object({version:vt.string(),description:vt.string().optional(),commands:vt.record(vt.string(),yk).refine(r=>"*"in r,{message:'Config must include a "*" wildcard entry for unknown commands'})})});function ic(r,e){return e.filter(t=>new RegExp(`\\b${t}\\b`).test(r)).length}function gp(r,e){let t=(e.frontmatter?.description||"").toLowerCase(),n=e.content.toLowerCase(),s=e.frontmatter?.["allowed-tools"]||[],o=`${r} ${t} ${n}`,i=ic(o,wk),a=ic(o,Sk),c=ic(o,kk);return s.some(d=>bk.includes(d))&&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 wk,Sk,kk,bk,fp=w(()=>{"use strict";wk=["build","create","add","implement","fix","refactor","update","modify","change","write","generate","scaffold","migrate","optimize","improve","enhance","redesign","rewrite"],Sk=["list","show","get","status","info","check","view","display","describe","explain","analyze","report","dashboard"],kk=["test","verify","validate","review","audit","check","lint","ship","deploy","release","complete","done","finish"],bk=["Write","Edit","Bash"];l(ic,"countMatches");l(gp,"classifyCommand")});import ac from"node:fs/promises";import Pk from"node:path";async function yp(){if(er)return er;let r=await ac.readFile(cc,"utf-8"),e=JSON.parse(r);return er=pp.parse(e),er}function Ck(r){return wp.get(r)}function xk(r,e){wp.set(r,e)}function Tk(r,e){let t=r,n=hp.get(t);return n&&Ak(n.entry,e)?(n.count++,n.count>=vk):(hp.set(t,{entry:e,count:1}),!1)}async function Ek(r,e){let t=await ac.readFile(cc,"utf-8"),n=JSON.parse(t);n.commands[r]=e,await ac.writeFile(cc,`${JSON.stringify(n,null,2)}
|
|
416
|
+
`,"utf-8"),er=null}function Ak(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 Sp(r,e,t){if(e in r.commands&&e!=="*")return{entry:r.commands[e],source:"config"};let n=Ck(e);if(n)return{entry:n,source:"cache"};if(t){let s=gp(e,t);return xk(e,s),Tk(e,s)&&Ek(e,s).catch(()=>{}),{entry:s,source:"classified"}}return{entry:r.commands["*"],source:"wildcard"}}var cc,er,wp,hp,vk,kp=w(()=>{"use strict";mp();dn();fp();cc=Pk.join(ke,"core/config/command-context.config.json"),er=null;l(yp,"loadCommandContextConfig");wp=new Map;l(Ck,"getCachedClassification");l(xk,"cacheClassification");hp=new Map,vk=3;l(Tk,"trackClassification");l(Ek,"persistClassification");l(Ak,"isSameEntry");l(Sp,"resolveCommandContextFull")});import Ik from"node:os";import{z as _t}from"zod";function Dk(){return typeof globalThis<"u"&&"Bun"in globalThis?"bun":"node"}function Rk(r){return{darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD"}[r]??r}function bp(r){let e=r.platform??Ik.platform(),t=r.runtime??Dk(),n=r.date??new Date().toISOString().split("T")[0];return`<env>
|
|
417
|
+
${[["project",r.projectName],["path",r.projectPath],["git",r.isGitRepo?"true":"false"],["branch",r.gitBranch],["platform",Rk(e)],["runtime",t],["date",n],["model",r.model],["provider",r.provider]].filter(([,i])=>i!==void 0).map(([i,a])=>`${i}: ${a}`).join(`
|
|
554
418
|
`)}
|
|
555
|
-
</env>`}var
|
|
556
|
-
... (truncated to ~${e} tokens)`}function
|
|
557
|
-
`);return
|
|
419
|
+
</env>`}var Qj,Pp=w(()=>{"use strict";Qj=_t.object({projectName:_t.string(),projectPath:_t.string(),isGitRepo:_t.boolean().default(!0),gitBranch:_t.string().optional(),platform:_t.string().optional(),runtime:_t.string().optional(),date:_t.string().optional(),model:_t.string().optional(),provider:_t.string().optional()});l(Dk,"detectRuntime");l(Rk,"normalizePlatform");l(bp,"buildEnvironmentBlock")});function xp(r){let e=r.getAllocationFor("injection");return{...Io,totalPrompt:e}}function xn(r,e){let t=e*vp;return r.length<=t?r:`${r.substring(0,t)}
|
|
420
|
+
... (truncated to ~${e} tokens)`}function Cp(r){return Math.ceil(r.length/vp)}function Tp(r,e){if(e.length===0||r.length===0)return r;let t=new Set;for(let n of e){let s=jk[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 Io,vp,jk,Ao,Ep=w(()=>{"use strict";Io={autoContext:500,agentContent:400,skillContent:500,stateData:1e3,memories:600,totalPrompt:8e3};l(xp,"budgetsFromCoordinator");vp=4;l(xn,"truncateToTokenBudget");l(Cp,"estimateTokens");jk={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(Tp,"filterSkillsByDomains");Ao=class{static{l(this,"InjectionBudgetTracker")}used=0;budgets;constructor(e={}){this.budgets={...Io,...e}}addSection(e,t){let n=xn(e,t),s=Cp(n);if(this.used+s>this.budgets.totalPrompt){let o=this.budgets.totalPrompt-this.used;if(o<=0)return"";let i=xn(n,o);return this.used+=Cp(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 Ap from"node:fs/promises";import vn from"node:path";var lc,$k,Ip,Dp=w(()=>{"use strict";Mt();O();je();dn();Ha();dp();kp();Pp();Ep();oc();Jn();lc=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 M(e)){let s=await Ap.readFile(e,"utf-8");return this._templateCache.set(e,{content:s,loadedAt:n}),s}}catch(s){C(s)||console.error(`Template loading warning: ${y(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?xp(this._coordinator):Io}resetContext(){this._currentContext=null}setContext(e){this._currentContext=e}async loadModule(e){let t=ve(`global/modules/${e}`);if(t)return t;let n=vn.join(ke,"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=Vn("checklists/");if(n.length>0){for(let s of n)if(s.endsWith(".md")){let o=ve(s);if(o){let i=vn.basename(s,".md");t[i]=o}}}else{let s=vn.join(ke,"templates","checklists");if(await M(s)){let o=(await Ap.readdir(s)).filter(i=>i.endsWith(".md"));for(let i of o){let a=i.replace(".md",""),c=vn.join(s,i),u=await this.getTemplate(c);u&&(t[a]=u)}}}}catch(n){C(n)||console.error(`Checklist loading warning: ${y(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([F.read(e),pe.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(C(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 _a.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){!C(o)&&!(o instanceof SyntaxError)&&console.error(`Outcome detection warning: ${y(o)}`)}n.push("---"),n.push("");let s=n.join(`
|
|
421
|
+
`);return xn(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=vn.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 d=await this.build(e,t,n,s,o,i,a,c);return u.push(d),u.join("")}async build(e,t,n,s=null,o=null,i=null,a=null,c=null,u=null){let d=[];this._currentContext=t;let m=e.frontmatter?.name?.replace("p:","")||"",p;try{let P=await yp();p=Sp(P,m,e).entry}catch{p={agents:!0,patterns:!0,checklist:!1,modules:[]}}let g=p.agents;s&&g&&(d.push(`# AGENT: ${s.name}
|
|
558
422
|
`),s.role&&d.push(`Role: ${s.role}
|
|
559
423
|
`),s.skills?.length&&d.push(`Skills: ${s.skills.join(", ")}
|
|
560
424
|
`),d.push(`
|
|
@@ -563,8 +427,8 @@ Apply specialized expertise. Read agent file for details if needed.
|
|
|
563
427
|
`)),d.push(`TASK: ${e.frontmatter.description}
|
|
564
428
|
`),e.frontmatter["allowed-tools"]&&d.push(`TOOLS: ${e.frontmatter["allowed-tools"].join(", ")}
|
|
565
429
|
`);let f=t;(f.params?.task||f.params?.description)&&d.push(`INPUT: ${f.params.task||f.params.description}
|
|
566
|
-
`);let S=t.projectPath;if(S){let P=u?.project?.id?
|
|
567
|
-
${
|
|
430
|
+
`);let S=t.projectPath;if(S){let P=u?.project?.id?vn.basename(S):vn.basename(S),A=bp({projectName:P,projectPath:S,isGitRepo:!0,gitBranch:u?.realContext?.gitBranch});d.push(`
|
|
431
|
+
${A}
|
|
568
432
|
`)}if(u){let P=u.sealedAnalysis;if(d.push(`
|
|
569
433
|
## PROJECT ANALYSIS (Sealed)
|
|
570
434
|
`),d.push(`**Ecosystem**: ${u.project.ecosystem}
|
|
@@ -579,46 +443,46 @@ ${I}
|
|
|
579
443
|
`),d.push(`**Analysis Status**: ${P.status}${P.commitHash?` (commit: ${P.commitHash.slice(0,8)})`:""}
|
|
580
444
|
`),P.patterns.length>0){d.push(`
|
|
581
445
|
### Code Patterns (Follow These)
|
|
582
|
-
`);for(let
|
|
446
|
+
`);for(let A of P.patterns)d.push(`- **${A.name}**: ${A.description}${A.location?` (${A.location})`:""}
|
|
583
447
|
`)}if(P.antiPatterns.length>0){d.push(`
|
|
584
448
|
### Anti-Patterns (Avoid These)
|
|
585
|
-
`);for(let
|
|
449
|
+
`);for(let A of P.antiPatterns)d.push(`- **${A.issue}** in \`${A.file}\` \u2014 ${A.suggestion}
|
|
586
450
|
`)}}d.push(`
|
|
587
|
-
`)}let
|
|
451
|
+
`)}let b=p.patterns,D=n?.codePatterns||"";if(b&&D&&D.trim()){let P=this.extractPatternSummary(D);P&&(d.push(`## CODE PATTERNS
|
|
588
452
|
`),d.push(P),d.push(`
|
|
589
453
|
Full patterns: Read analysis/patterns.md
|
|
590
|
-
`))}let
|
|
454
|
+
`))}let j=n?.analysis||"";if(b&&j&&j.trim()){let P=j.match(/Stack[:\s]+([^\n]+)/i)||j.match(/Technology[:\s]+([^\n]+)/i),A=P?P[1].trim():"detected";d.push(`
|
|
591
455
|
## STACK
|
|
592
|
-
Stack: ${
|
|
593
|
-
`),
|
|
456
|
+
Stack: ${A}
|
|
457
|
+
`),D||d.push(`Read analysis/repo-summary.md + similar files before coding. Match patterns exactly.
|
|
594
458
|
`)}if(u){if(u.agents.length>0){d.push(`
|
|
595
459
|
### LOADED AGENTS (Project-Specific Specialists)
|
|
596
460
|
|
|
597
|
-
`);for(let
|
|
598
|
-
`),
|
|
599
|
-
`),
|
|
600
|
-
`),
|
|
601
|
-
`);let
|
|
602
|
-
${
|
|
461
|
+
`);for(let A of u.agents){d.push(`#### Agent: ${A.name} (${A.domain})
|
|
462
|
+
`),A.effort&&d.push(`Effort: ${A.effort}
|
|
463
|
+
`),A.model&&d.push(`Model: ${A.model}
|
|
464
|
+
`),A.skills.length>0&&d.push(`Skills: ${A.skills.join(", ")}
|
|
465
|
+
`);let Se=xn(A.content,this.getEffectiveBudgets().agentContent);d.push(`\`\`\`markdown
|
|
466
|
+
${Se}
|
|
603
467
|
\`\`\`
|
|
604
468
|
|
|
605
|
-
`)}}let P=
|
|
469
|
+
`)}}let P=Tp(u.skills,u.detectedDomains);if(P.length>0){d.push(`### LOADED SKILLS (From Agent Frontmatter)
|
|
606
470
|
|
|
607
|
-
`);for(let
|
|
608
|
-
`);let
|
|
609
|
-
${
|
|
471
|
+
`);for(let A of P){d.push(`#### Skill: ${A.name}
|
|
472
|
+
`);let Se=xn(A.content,this.getEffectiveBudgets().skillContent);d.push(`\`\`\`markdown
|
|
473
|
+
${Se}
|
|
610
474
|
\`\`\`
|
|
611
475
|
|
|
612
|
-
`)}}}let q=this.getModulesForCommand(m,p);if(q.length>0)for(let P of q){let
|
|
613
|
-
`),d.push(
|
|
476
|
+
`)}}}let q=this.getModulesForCommand(m,p);if(q.length>0)for(let P of q){let A=await this.loadModule(P);A&&(d.push(`
|
|
477
|
+
`),d.push(A))}if(c?.isPlanning&&(d.push(`
|
|
614
478
|
## PLAN MODE
|
|
615
479
|
Read-only. Gather info \u2192 Analyze \u2192 Propose plan \u2192 Wait for approval.
|
|
616
480
|
`),c.allowedTools&&d.push(`Tools: ${c.allowedTools.join(", ")}
|
|
617
481
|
`)),c?.requiresApproval&&d.push(`
|
|
618
482
|
## APPROVAL REQUIRED
|
|
619
483
|
Show changes, list affected files, ask for confirmation.
|
|
620
|
-
`),S){let P=u?.sealedAnalysis,
|
|
621
|
-
${
|
|
484
|
+
`),S){let P=u?.sealedAnalysis,A=[...P?.frameworks||[],...u?.project?.conventions||[]],Se={projectPath:S,language:u?.project?.ecosystem,framework:P?.frameworks?.[0],techStack:Eo(A),domains:this.extractDomains(n),fileCount:t.files?.length||t.filteredSize||0,availableAgents:u?.agents?.map(U=>U.name)||[],analysisLanguages:P?.languages||[],analysisFrameworks:P?.frameworks||[],analysisPackageManager:P?.packageManager};d.push(`
|
|
485
|
+
${up(Se)}
|
|
622
486
|
`)}else d.push(this.buildCriticalRules());if(u?.realContext){let P=u.realContext;if(d.push(`
|
|
623
487
|
### CODEBASE CONTEXT
|
|
624
488
|
|
|
@@ -627,27 +491,27 @@ ${Dp(ke)}
|
|
|
627
491
|
`),P.relevantFiles.length>0){d.push(`**Relevant Files** (scored by task relevance):
|
|
628
492
|
`),d.push(`| Score | File | Why |
|
|
629
493
|
`),d.push(`|-------|------|-----|
|
|
630
|
-
`);for(let
|
|
494
|
+
`);for(let A of P.relevantFiles.slice(0,8))d.push(`| ${A.score} | ${A.path} | ${A.reason} |
|
|
631
495
|
`);d.push(`
|
|
632
496
|
`)}if(P.signatures.length>0){d.push(`**Code Signatures** (top files):
|
|
633
|
-
`);for(let
|
|
634
|
-
// ${
|
|
635
|
-
${
|
|
497
|
+
`);for(let A of P.signatures)d.push(`\`\`\`typescript
|
|
498
|
+
// ${A.path}
|
|
499
|
+
${A.content}
|
|
636
500
|
\`\`\`
|
|
637
501
|
`);d.push(`
|
|
638
|
-
`)}if(P.recentFiles.length>0){d.push("**Recently Changed**: ");let
|
|
502
|
+
`)}if(P.recentFiles.length>0){d.push("**Recently Changed**: ");let A=P.recentFiles.slice(0,5).map(Se=>`${Se.path} (${Se.lastChanged})`).join(", ");d.push(`${A}
|
|
639
503
|
|
|
640
|
-
`)}}let
|
|
641
|
-
## FILES: ${
|
|
504
|
+
`)}}let Re=t.files||[];if(Re.length>0){let P=Re.slice(0,5).join(", ");d.push(`
|
|
505
|
+
## FILES: ${Re.length} available. Top: ${P}
|
|
642
506
|
`),d.push(`Read BEFORE modifying. Use Glob/Grep to find more.
|
|
643
507
|
|
|
644
508
|
`)}else S&&d.push(`
|
|
645
509
|
## PROJECT: ${S}
|
|
646
510
|
Read files before modifying.
|
|
647
511
|
|
|
648
|
-
`);let
|
|
512
|
+
`);let Be=this.filterRelevantState(n);if(Be&&(d.push(`
|
|
649
513
|
## PRJCT STATE (Project Management Data)
|
|
650
|
-
`),d.push(
|
|
514
|
+
`),d.push(Be),d.push(`
|
|
651
515
|
`)),u?.velocityContext&&(d.push(`
|
|
652
516
|
### VELOCITY (Historical Estimation Data)
|
|
653
517
|
|
|
@@ -655,7 +519,7 @@ Read files before modifying.
|
|
|
655
519
|
|
|
656
520
|
`)),o&&Object.keys(o).some(P=>o[P])){d.push(`
|
|
657
521
|
## PROJECT DEFAULTS (apply automatically)
|
|
658
|
-
`);for(let[P,
|
|
522
|
+
`);for(let[P,A]of Object.entries(o))A&&d.push(`- ${P}: ${A}
|
|
659
523
|
`)}if(i?.plan&&i.plan.length>0){if(d.push(`
|
|
660
524
|
## THINK FIRST (reasoning from analysis)
|
|
661
525
|
`),i.conclusions&&i.conclusions.length>0){d.push(`Conclusions:
|
|
@@ -674,34 +538,34 @@ Read files before modifying.
|
|
|
674
538
|
|
|
675
539
|
`),d.push("**IMPORTANT**: Focus on the CURRENT subtask. Use `p. done` when complete to advance.\n\n"),d.push(`| # | Domain | Description | Status |
|
|
676
540
|
`),d.push(`|---|--------|-------------|--------|
|
|
677
|
-
`);for(let
|
|
678
|
-
`)}let P=u.subtasks.find(
|
|
541
|
+
`);for(let A of u.subtasks){let Se=A.status==="in_progress"?"\u25B6\uFE0F **CURRENT**":A.status==="completed"?"\u2705 Done":A.status==="failed"?"\u274C Failed":"\u23F3 Pending";d.push(`| ${A.order} | ${A.domain} | ${A.description} | ${Se} |
|
|
542
|
+
`)}let P=u.subtasks.find(A=>A.status==="in_progress");if(P&&(d.push(`
|
|
679
543
|
**FOCUS ON SUBTASK #${P.order}**: ${P.description}
|
|
680
544
|
`),d.push(`Agent: ${P.agent} | Domain: ${P.domain}
|
|
681
545
|
`),P.dependsOn.length>0&&d.push(`Dependencies: ${P.dependsOn.join(", ")}
|
|
682
|
-
`),P.handoff)){let
|
|
546
|
+
`),P.handoff)){let A=P.handoff;d.push(`
|
|
683
547
|
### Previous Subtask Handoff
|
|
684
548
|
|
|
685
|
-
`),d.push(`**From:** ${
|
|
549
|
+
`),d.push(`**From:** ${A.fromSubtask}
|
|
686
550
|
|
|
687
551
|
`),d.push(`**What was done:**
|
|
688
|
-
`);for(let
|
|
689
|
-
`);if(
|
|
552
|
+
`);for(let Se of A.whatWasDone)d.push(`- ${Se}
|
|
553
|
+
`);if(A.filesChanged.length>0){d.push(`
|
|
690
554
|
**Files changed:**
|
|
691
|
-
`);for(let
|
|
555
|
+
`);for(let Se of A.filesChanged)d.push(`- \`${Se.path}\` (${Se.action})
|
|
692
556
|
`)}d.push(`
|
|
693
557
|
**Context for this subtask:**
|
|
694
|
-
${
|
|
558
|
+
${A.outputForNextAgent}
|
|
695
559
|
`)}d.push(`
|
|
696
|
-
`)}let
|
|
697
|
-
${
|
|
698
|
-
`)}if(p.checklist){let P=await this.loadChecklistRouting(),
|
|
560
|
+
`)}let gt=this.getSchemaTypeForCommand(m);if(gt){let{renderSchemaForPrompt:P}=await Promise.resolve().then(()=>(xr(),nu)),A=P(gt);A&&d.push(`
|
|
561
|
+
${A}
|
|
562
|
+
`)}if(p.checklist){let P=await this.loadChecklistRouting(),A=await this.loadChecklists();P&&Object.keys(A).length>0&&(d.push(`
|
|
699
563
|
## QUALITY CHECKLISTS
|
|
700
564
|
`),d.push(`Apply relevant checklists based on task. Read checklist-routing.md for guidance.
|
|
701
|
-
`),d.push(`Available: ${Object.keys(
|
|
565
|
+
`),d.push(`Available: ${Object.keys(A).join(", ")}
|
|
702
566
|
`),d.push(`Path: templates/checklists/{name}.md
|
|
703
567
|
`),d.push(`Use Read tool to load checklists you determine are relevant.
|
|
704
|
-
`))}return d.push(this.buildEfficiencyDirective()),d.join("")}filterRelevantState(e){if(!e||Object.keys(e).length===0)return null;let t=this.getEffectiveBudgets(),n=new
|
|
568
|
+
`))}return d.push(this.buildEfficiencyDirective()),d.join("")}filterRelevantState(e){if(!e||Object.keys(e).length===0)return null;let t=this.getEffectiveBudgets(),n=new Ao({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}
|
|
705
569
|
${a}`,c);u&&o.push(u)}return o.length>0?o.join(`
|
|
706
570
|
|
|
707
571
|
`):null}buildAnalysis(e,t){let n=[];return n.push(`# Analyze: ${e}
|
|
@@ -718,7 +582,7 @@ ${a}`,c);u&&o.push(u)}return o.length>0?o.join(`
|
|
|
718
582
|
`);a&&t.push(a)}let s=e.match(/### High Priority[\s\S]*?(?=###|##|$)/i);if(s){let a=s[0].substring(0,300);t.push(`
|
|
719
583
|
Avoid:
|
|
720
584
|
${a}`)}let o=t.join(`
|
|
721
|
-
`);return
|
|
585
|
+
`);return xn(o,200)||null}getSchemaTypeForCommand(e){return{task:"subtaskBreakdown",bug:"classification"}[e]??null}buildCriticalRules(){return`
|
|
722
586
|
## RULES (CRITICAL)
|
|
723
587
|
1. **READ FIRST**: Use Read tool BEFORE modifying any file. Never assume code structure.
|
|
724
588
|
2. **MATCH PATTERNS**: Follow existing style, architecture, naming, imports exactly.
|
|
@@ -735,7 +599,7 @@ Context: ${this._currentContext?.files?.length||this._currentContext?.filteredSi
|
|
|
735
599
|
- Prefer structured output (JSON) over free text when applicable.
|
|
736
600
|
|
|
737
601
|
EXECUTE: Follow flow. Use tools. Decide.
|
|
738
|
-
`}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}}}}
|
|
602
|
+
`}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}}}},$k=new lc,Ip=$k});import Rp from"node:fs/promises";import lt from"node:path";var Mk,Ok,uc,dc,Do,pc=w(()=>{"use strict";nt();ue();O();Mk=["task","done","ship","resume","bug","enrich"],Ok=["init","sync","pause","next","dash","history","undo","redo"],uc=class{static{l(this,"TemplateExecutor")}async getNpmRoot(){return lt.dirname(Ps.resolve("prjct-cli/package.json"))}async getProjectId(e){return R.getProjectId(e)}async buildContext(e,t,n){let s=await this.getProjectId(n),o=E.getGlobalProjectPath(s),a=await(Ve(),at(et)).getActiveProvider(),c;try{let u=await this.getNpmRoot();c=lt.join(u,"templates")}catch{c=lt.join(__dirname,"..","..","templates")}return{projectPath:n,projectId:s,globalPath:o,command:e,args:t,agentName:a.displayName,agentSettingsPath:await E.getAgentSettingsPath(),paths:{orchestrator:lt.join(c,"agentic","orchestrator.md"),agentRouting:lt.join(c,"agentic","agent-routing.md"),taskFragmentation:lt.join(c,"agentic","task-fragmentation.md"),commandTemplate:lt.join(c,"commands",`${e}.md`),repoAnalysis:lt.join(o,"analysis","repo-analysis.json"),agentsDir:lt.join(o,"agents"),skillsDir:a.skillsDir,stateJson:lt.join(o,"storage","state.json")}}}requiresOrchestration(e){return Mk.includes(e)?!0:!Ok.includes(e)}async hasAgents(e){try{let t=await this.getProjectId(e),n=lt.join(E.getGlobalProjectPath(t),"agents");return(await Rp.readdir(n)).some(o=>o.endsWith(".md"))}catch(t){return C(t),!1}}async getAvailableAgents(e){try{let t=await this.getProjectId(e),n=lt.join(E.getGlobalProjectPath(t),"agents");return(await Rp.readdir(n)).filter(o=>o.endsWith(".md")).map(o=>o.replace(".md",""))}catch{return[]}}buildAgenticPrompt(e){let t=this.requiresOrchestration(e.command);return{prompt:`
|
|
739
603
|
## Agentic Execution Mode
|
|
740
604
|
|
|
741
605
|
You are executing a prjct command as ${e.agentName}. Follow the template-first approach.
|
|
@@ -818,13 +682,13 @@ When fragmenting tasks:
|
|
|
818
682
|
2. Track progress: currentSubtaskIndex, subtaskProgress
|
|
819
683
|
3. Each completed subtask generates a summary
|
|
820
684
|
4. Pass summary to next agent for context handoff
|
|
821
|
-
`,context:e,requiresOrchestration:t}}},
|
|
822
|
-
`+
|
|
823
|
-
`+
|
|
824
|
-
`+
|
|
825
|
-
`+
|
|
826
|
-
`+
|
|
827
|
-
`}},
|
|
685
|
+
`,context:e,requiresOrchestration:t}}},dc=new uc,Do=dc});import{exec as Fk}from"node:child_process";import jp from"node:fs/promises";import{promisify as _k}from"node:util";var Nk,Tn,De,mc=w(()=>{"use strict";Nr();Nk=_k(Fk),Tn={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())}};Tn.register("Read",async r=>{try{return await Ns.execute(async()=>await jp.readFile(r,"utf-8"),`read-${r}`)}catch(e){return _r(e)||_s(e),null}});Tn.register("Write",async(r,e)=>{try{return await Ns.execute(async()=>await jp.writeFile(r,e,"utf-8"),`write-${r}`),!0}catch(t){return _r(t)||_s(t),!1}});Tn.register("Bash",async r=>{try{return await Ns.execute(async()=>await Nk(r),`bash-${r}`)}catch(e){let t=e;return{stdout:t.stdout||"",stderr:t.stderr||t.message||"Command failed"}}});Tn.register("GetTimestamp",async()=>new Date().toISOString());Tn.register("GetDate",async()=>new Date().toISOString().split("T")[0]);Tn.register("GetDateTime",async()=>new Date().toISOString());De=Tn});import gc from"node:fs/promises";import Lk from"node:os";import $p from"node:path";async function Uk(r){try{let e=$p.dirname(Ro);await M(e)||await gc.mkdir(e,{recursive:!0}),await gc.writeFile(Ro,`/p:${r}`)}catch{}}async function Hk(){try{await M(Ro)&&await gc.unlink(Ro)}catch{}}var Ro,fc,zk,jo,hc=w(()=>{"use strict";O();Sd();je();Pd();xd();Wa();_d();Nd();Hn();sc();lp();Dp();pc();Jn();mc();Ro=$p.join(Lk.homedir(),".prjct-cli",".running");l(Uk,"signalStart");l(Hk,"signalEnd");fc=class{static{l(this,"CommandExecutor")}async signalStart(e){await Uk(e)}async signalEnd(){await Hk()}async execute(e,t,n){await this.signalStart(e);let s=t.task||t.description||"";if(ns.shouldEscalate(e,s)){let o=ns.getEscalationInfo(e,s);return await this.signalEnd(),{success:!1,error:o?.message,escalation:o,isLoopDetected:!0,suggestion:o?.suggestion}}try{let o=await Wi.load(e),i=await Ye.build(n,t),a=be.requiresPlanning(e),c=be.isDestructive(e),u=be.isInPlanningMode(i.projectId),d=null;a&&!u&&!t.skipPlanning?d=be.startPlanning(i.projectId,e,t):u&&(d=be.getActivePlan(i.projectId));let m=null;if(Po.requiresVerification(e)){let P=await Ye.loadStateForCommand(i,e);m=await Po.verify(e,i,P),!m.verified&&m.warnings.length>0&&console.log(Po.formatWarnings(m))}let p=null;if(bo.requiresReasoning(e)){let P=await Ye.loadStateForCommand(i,e);p=await bo.reason(e,i,P),p.reasoning&&!p.reasoning.allPassed&&(console.log("\u26A0\uFE0F Chain of Thought detected issues:"),console.log(bo.formatPlan(p)))}let g=t.task||t.description||"",f=await Do.buildContext(e,g,n),S=Do.buildAgenticPrompt(f),b=null;if(Do.requiresOrchestration(e)&&g)try{b=await vo.execute(e,g,n),b.detectedDomains.length>0&&ko.orchestrate(b.detectedDomains);for(let P of b.agents){let A=P.domain||P.name.replace(".md","");ko.startAgent(P.name,A,`Loading ${A} specialist...`),ko.endAgent(!0)}if(b.requiresFragmentation&&b.subtasks){let P=b.subtasks.map(A=>({id:A.id,domain:A.domain,description:A.description,status:A.status}));bd(P)}}catch(P){console.warn(`\u26A0\uFE0F Orchestrator warning: ${y(P)}`)}let D={...i,agentsPath:f.paths.agentsDir,agentRoutingPath:f.paths.agentRouting,orchestratorPath:f.paths.orchestrator,taskFragmentationPath:f.paths.taskFragmentation,agenticDelegation:!0,agenticMode:!0},j=await Ye.loadState(i),q=null,Re=null;i.projectId&&(q={commit_footer:await de.getSmartDecision(i.projectId,"commit_footer"),branch_naming:await de.getSmartDecision(i.projectId,"branch_naming"),test_before_ship:await de.getSmartDecision(i.projectId,"test_before_ship"),preferred_agent:await de.getSmartDecision(i.projectId,`preferred_agent_${e}`)},Re=await de.getRelevantMemories(i.projectId,{commandName:e,params:t},5));let Be={isPlanning:a||u,requiresApproval:c&&!t.approved,active:d,allowedTools:be.getAllowedTools(u,o.frontmatter["allowed-tools"]||[])},gt=await Ip.build(o,D,j,null,q,null,Re,Be,b);return console.log("\u{1F916} Template-first execution: Claude reads templates and decides"),S.requiresOrchestration&&console.log(` \u2192 Orchestration: ${f.paths.orchestrator}`),ns.recordSuccess(e,s),await this.signalEnd(),{success:!0,template:o,context:D,state:j,prompt:gt,agenticDelegation:!0,agenticMode:!0,agenticExecContext:f,agenticPrompt:S.prompt,requiresOrchestration:S.requiresOrchestration,agentsPath:D.agentsPath,agentRoutingPath:D.agentRoutingPath,orchestratorPath:f.paths.orchestrator,taskFragmentationPath:f.paths.taskFragmentation,reasoning:p,groundTruth:m,learnedPatterns:q,relevantMemories:Re,orchestratorContext:b,memory:{create:l(P=>de.createMemory(i.projectId,P),"create"),autoRemember:l((P,A,Se)=>de.autoRemember(i.projectId,P,A,Se),"autoRemember"),search:l(P=>de.searchMemories(i.projectId,P),"search"),findByTags:l(P=>de.findByTags(i.projectId,P),"findByTags"),getStats:l(()=>de.getMemoryStats(i.projectId),"getStats")},plan:{active:d,isPlanning:a||u,isDestructive:c,requiresApproval:c&&!t.approved,recordInfo:l(P=>be.recordGatheredInfo(i.projectId,P),"recordInfo"),setAnalysis:l(P=>be.setAnalysis(i.projectId,P),"setAnalysis"),propose:l(P=>be.proposePlan(i.projectId,P),"propose"),approve:l(P=>be.approvePlan(i.projectId,P),"approve"),reject:l(P=>be.rejectPlan(i.projectId,P),"reject"),getApprovalPrompt:l(()=>be.generateApprovalPrompt(e,{changedFiles:[],filesToDelete:[],operation:e==="ship"?"git_push":e==="cleanup"?"delete_files":"run_command",warnings:[]}),"getApprovalPrompt"),startExecution:l(()=>be.startExecution(i.projectId),"startExecution"),getNextStep:l(()=>be.getNextStep(i.projectId),"getNextStep"),completeStep:l(P=>be.completeStep(i.projectId,P),"completeStep"),failStep:l(P=>be.failStep(i.projectId,P),"failStep"),abort:l(P=>be.abortPlan(i.projectId,P),"abort"),getStatus:l(()=>be.formatStatus(i.projectId),"getStatus"),getAllowedTools:l(()=>be.getAllowedTools(u,o.frontmatter["allowed-tools"]||[]),"getAllowedTools")}}}catch(o){await this.signalEnd();let i=ns.recordAttempt(e,s,{success:!1,error:y(o)});if(i.shouldEscalate){let a=ns.getEscalationInfo(e,s);return{success:!1,error:a?.message,escalation:a,isLoopDetected:!0,suggestion:a?.suggestion}}return{success:!1,error:y(o),attemptNumber:i.attemptNumber,isLooping:i.isLooping}}}async executeTool(e,t,n){if(!De.isAllowed(e,n))throw new Error(`Tool ${e} not allowed for this command`);let s=De.get(e);if(!s)throw new Error(`Tool ${e} not found`);return await s(...t)}async executeSimple(e,t,n){try{let o=(await Wi.load(e)).frontmatter["allowed-tools"]||[],i=await Ye.build(n);return{success:!0,result:await t({read:l(async u=>this.executeTool("Read",[u],o),"read"),write:l(async(u,d)=>this.executeTool("Write",[u,d],o),"write"),bash:l(async u=>this.executeTool("Bash",[u],o),"bash")},i)}}catch(s){return{success:!1,error:y(s)}}}},zk=new fc,jo=zk});import $o from"node:fs/promises";import Gk from"node:https";import Wk from"node:os";import yc from"node:path";import Tt from"chalk";var wc,Mp,Op=w(()=>{"use strict";O();je();wc=class{static{l(this,"UpdateChecker")}packageName;cacheDir;cacheFile;checkInterval;constructor(){this.packageName="prjct-cli",this.cacheDir=yc.join(Wk.homedir(),".prjct-cli","config"),this.cacheFile=yc.join(this.cacheDir,"update-cache.json"),this.checkInterval=1440*60*1e3}async getCurrentVersion(){try{let e=yc.join(__dirname,"..","..","package.json");return JSON.parse(await $o.readFile(e,"utf8")).version}catch(e){return console.error("Error reading package version:",y(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=Gk.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 M(this.cacheFile))return JSON.parse(await $o.readFile(this.cacheFile,"utf8"))}catch{}return null}async writeCache(e){try{await M(this.cacheDir)||await $o.mkdir(this.cacheDir,{recursive:!0}),await $o.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:`
|
|
686
|
+
`+Tt.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")+`
|
|
687
|
+
`+Tt.yellow("\u2502")+" "+Tt.bold("Update available!")+" "+Tt.dim(`${e.currentVersion} \u2192 ${e.latestVersion}`)+" "+Tt.yellow("\u2502")+`
|
|
688
|
+
`+Tt.yellow("\u2502")+" "+Tt.yellow("\u2502")+`
|
|
689
|
+
`+Tt.yellow("\u2502")+" Run: "+Tt.cyan("npm update -g prjct-cli")+" "+Tt.yellow("\u2502")+`
|
|
690
|
+
`+Tt.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")+`
|
|
691
|
+
`}},Mp=wc});var ae,He=w(()=>{"use strict";hc();Wa();mc();nt();ue();Op();nn();se();je();yn();ae=class{static{l(this,"PrjctCommandsBase")}prjctDir;updateChecker;updateNotificationShown;commandExecutor;constructor(){this.prjctDir=".prjct",this.updateChecker=new Mp,this.updateNotificationShown=!1,this.commandExecutor=jo}get agent(){return Kn.getAgent()}get agentInfo(){return Kn.getInfo()}get currentAuthor(){return tn.getCurrentAuthor()}async initializeAgent(){return Kn.initialize()}async ensureProjectInit(e){return tn.ensureInit(e)}async ensureAuthor(){return tn.ensureAuthor()}async getGlobalProjectPath(e){return tn.getGlobalPath(e)}async logToMemory(e,t,n){let s=await this.ensureAuthor();return Je.log(e,t,n,s.name)}async _detectEmptyDirectory(e){return tn.isEmptyDirectory(e)}async _detectExistingCode(e){return tn.hasExistingCode(e)}_breakdownFeatureTasks(e){return Vr.breakdownFeature(e)}_detectBugSeverity(e){return Vr.detectBugSeverity(e)}async _assignAgentForTask(e,t,n){return Kn.assignForTask(e,t,n)}}});var Fp={};Mn(Fp,{PlanningCommands:()=>An});import En from"node:path";async function Bk(){if(!Sc){let{AnalysisCommands:r}=await Promise.resolve().then(()=>(Oo(),_p));Sc=new r}return Sc}var Sc,An,Mo=w(()=>{"use strict";Ur();mn();yt();Mt();O();Zn();es();Ha();He();Sc=null;l(Bk,"getAnalysisCommands");An=class extends ae{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 R.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 ts(t).runNonInteractive());else if(a=await new ts(t).run(),a.skipped)return{success:!1,message:"Setup cancelled"};h.step(1,4,"Detecting author...");let c=await qn(),u={name:c.name||void 0,email:c.email||void 0,github:c.github||void 0},m=(await R.createConfig(t,u)).projectId;h.step(2,4,"Creating structure..."),await E.ensureProjectStructure(m);let p=E.getGlobalProjectPath(m),g={"core/now.md":`# NOW
|
|
828
692
|
|
|
829
693
|
No current task. Use \`/p:now\` to set focus.
|
|
830
694
|
`,"core/next.md":`# NEXT
|
|
@@ -844,17 +708,17 @@ No current task. Use \`/p:now\` to set focus.
|
|
|
844
708
|
`,"planning/roadmap.md":`# ROADMAP
|
|
845
709
|
|
|
846
710
|
`,"planning/specs/.gitkeep":`# Specs directory - created by /p:spec
|
|
847
|
-
`,"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[
|
|
711
|
+
`,"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[D,j]of Object.entries(g))await De.get("Write")(En.join(p,D),j);let f=await this._detectEmptyDirectory(t),S=await this._detectExistingCode(t);if(S||!f){h.step(3,4,"Analyzing project...");let D=await Bk();if((await D.analyze({},t)).success)return h.step(4,4,"Generating agents..."),a?.agents?await D.sync(t,{aiTools:a.agents}):await D.sync(t),h.done("initialized"),this._printNextSteps(a),{success:!0,mode:"existing",projectId:m,wizard:a}}let b=n.idea;if(f&&!S){if(!b)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 D=En.join(p,"planning","architect-session.md"),j=`# Architect Session
|
|
848
712
|
|
|
849
713
|
## Idea
|
|
850
|
-
${
|
|
714
|
+
${b}
|
|
851
715
|
|
|
852
716
|
## Status
|
|
853
717
|
Initialized - awaiting stack recommendation
|
|
854
718
|
|
|
855
719
|
Generated: ${new Date().toLocaleString()}
|
|
856
|
-
`;return await
|
|
857
|
-
`);let s=await this.getGlobalProjectPath(t),o
|
|
720
|
+
`;return await De.get("Write")(D,j),await Le.installGlobalConfig(),h.done("architect mode ready"),{success:!0,mode:"architect",projectId:m,idea:b,wizard:a}}return await Le.installGlobalConfig(),h.done("initialized"),this._printNextSteps(a),{success:!0,projectId:m,wizard:a}}catch(n){return h.fail(y(n)),{success:!1,error:y(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 R.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};h.spin(`planning ${e}...`);let o=await Ye.build(t,{description:e}),i=this._breakdownFeatureTasks(e),a=oe(),c=[];for(let m of i){let g=(await this._assignAgentForTask(m,t,o)).agent?.name||"generalist";c.push({task:m,agent:g})}await pe.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:H.getTimestamp()});let u=c.reduce((m,p)=>(m[p.agent]=(m[p.agent]||0)+1,m),{}),d=Object.entries(u).map(([m,p])=>`${m}:${p}`).join(" ");return h.done(`${i.length} tasks [${d}]`),{success:!0,feature:e,featureId:a,tasks:c}}catch(n){return h.fail(y(n)),{success:!1,error:y(n)}}}async bug(e,t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;if(!e)return n.md||h.fail("bug description required"),{success:!1,error:"Description required"};let o=await R.getProjectId(t);if(!o)return n.md||h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};n.md||h.spin("tracking bug...");let i=await Ye.build(t,{description:e}),a=this._detectBugSeverity(e),u=(await this._assignAgentForTask(`fix bug: ${e}`,t,i)).agent?.name||"generalist",m={critical:"critical",high:"high",medium:"medium",low:"low"}[a]||"medium";return await pe.addTask(o,{description:`\u{1F41B} ${e}`,priority:m,type:"bug",section:"active",agent:u}),await this.logToMemory(t,"bug_reported",{bug:e,severity:a,priority:m,agent:u,timestamp:H.getTimestamp()}),n.md?console.log(me(Ue("Bug Reported",e),xt({Severity:a,Priority:m,Agent:u}),Oe([{label:"Fix now",command:`prjct task "fix: ${e}" --md`},{label:"View queue",command:"prjct next --md"}]))):(h.done(`bug [${a}] \u2192 ${u}`),ot("bug")),{success:!0,bug:e,severity:a,agent:u}}catch(s){return n.md||h.fail(y(s)),{success:!1,error:y(s)}}}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
|
|
721
|
+
`);let s=await this.getGlobalProjectPath(t),o=En.join(s,"planning","architect-session.md"),i;try{i=await te.readFile(o)}catch{return{success:!1,message:`\u274C No architect plan found.
|
|
858
722
|
|
|
859
723
|
Create a plan first:
|
|
860
724
|
1. Run /p:init in an empty directory
|
|
@@ -875,7 +739,7 @@ The architect plan is ready. Claude will now:
|
|
|
875
739
|
4. Create starter files with boilerplate
|
|
876
740
|
`),console.log(`
|
|
877
741
|
\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.
|
|
878
|
-
`),await this.logToMemory(t,"architect_executed",{timestamp:
|
|
742
|
+
`),await this.logToMemory(t,"architect_executed",{timestamp:H.getTimestamp(),idea:d}),{success:!0,plan:i,idea:d}}catch(n){return console.error("\u274C Error:",y(n)),{success:!1,error:y(n)}}}async idea(e,t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;if(!e)return n.md||h.fail("idea description required"),{success:!1,error:"Idea description required"};let o=await R.getProjectId(t);if(!o)return n.md||h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(e.split(/\s+/).length>20||e.includes("with")||e.includes("that")){n.md||h.spin("analyzing idea...");let c=E.getGlobalProjectPath(o),u=En.join(c,"planning","architect-session.md"),d=`# Architect Session
|
|
879
743
|
|
|
880
744
|
## Idea
|
|
881
745
|
${e}
|
|
@@ -890,14 +754,14 @@ Initialized - awaiting architecture design
|
|
|
890
754
|
4. Generate roadmap
|
|
891
755
|
|
|
892
756
|
Generated: ${new Date().toLocaleString()}
|
|
893
|
-
`;return await
|
|
757
|
+
`;return await De.get("Write")(u,d),await this.logToMemory(t,"idea_architecture_started",{idea:e,timestamp:H.getTimestamp()}),n.md?console.log(me(Ue("Idea Captured",e),xt({Mode:"architecture"}),Oe([{label:"Continue planning",command:"prjct architect execute"}]))):(h.done("architecture session created"),console.log(`
|
|
894
758
|
\u{1F4A1} Use /p:architect execute to continue planning
|
|
895
|
-
`)),{success:!0,mode:"architecture",idea:e}}else return n.md||h.spin("capturing idea..."),await
|
|
759
|
+
`)),{success:!0,mode:"architecture",idea:e}}else return n.md||h.spin("capturing idea..."),await Me.addIdea(o,e),await this.logToMemory(t,"idea_captured",{idea:e,timestamp:H.getTimestamp()}),n.md?console.log(me(Ue("Idea Captured",e),xt({Mode:"capture"}),Oe([{label:"Start working on it",command:`prjct task "${e}" --md`},{label:"View ideas",command:"prjct dash ideas"}]))):(h.done(`idea captured: ${e.slice(0,40)}`),ot("idea")),{success:!0,mode:"capture",idea:e}}catch(s){return n.md||h.fail(y(s)),{success:!1,error:y(s)}}}async spec(e=null,t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await R.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(!e){h.spin("loading specs...");let d=E.getGlobalProjectPath(s),m=En.join(d,"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(`
|
|
896
760
|
\u{1F4A1} Create one with /p:spec "feature name"
|
|
897
761
|
`),{success:!0,specs:[]}):(console.log(`
|
|
898
762
|
\u{1F4CB} SPECIFICATIONS
|
|
899
|
-
`),console.log("\u2550".repeat(50)),f.forEach((S,
|
|
900
|
-
`),{success:!0,specs:f})}catch{return h.warn("no specs directory"),{success:!0,specs:[]}}}h.spin("creating spec...");let o=
|
|
763
|
+
`),console.log("\u2550".repeat(50)),f.forEach((S,b)=>{let D=S.replace(".md","").replace(/-/g," ");console.log(` ${b+1}. ${D}`)}),console.log(`${"\u2550".repeat(50)}
|
|
764
|
+
`),{success:!0,specs:f})}catch{return h.warn("no specs directory"),{success:!0,specs:[]}}}h.spin("creating spec...");let o=E.getGlobalProjectPath(s),i=En.join(o,"planning","specs");await te.ensureDir(i);let a=e.toLowerCase().replace(/\s+/g,"-"),c=En.join(i,`${a}.md`),u=`# Specification: ${e}
|
|
901
765
|
|
|
902
766
|
## Overview
|
|
903
767
|
[Brief description of the feature]
|
|
@@ -927,27 +791,27 @@ Generated: ${new Date().toLocaleString()}
|
|
|
927
791
|
---
|
|
928
792
|
Created: ${new Date().toLocaleString()}
|
|
929
793
|
Status: Draft
|
|
930
|
-
`;return await
|
|
794
|
+
`;return await De.get("Write")(c,u),await this.logToMemory(t,"spec_created",{feature:e,timestamp:H.getTimestamp()}),h.done(`spec created: ${a}.md`),console.log(`
|
|
931
795
|
\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
|
|
932
|
-
`),{success:!0,feature:e,specPath:c}}catch(n){return h.fail(
|
|
933
|
-
`).filter(Boolean):[],s){let c=new Date(s),u=new Date;t.daysSinceSync=Math.floor((u.getTime()-c.getTime())/(1e3*60*60*24))}return t.significantChanges=t.changedFiles.filter(c=>this.config.significantFiles.some(u=>c.endsWith(u)||c.includes(u))),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: ${
|
|
934
|
-
`)}async getSessionInfo(e){return
|
|
796
|
+
`),{success:!0,feature:e,specPath:c}}catch(n){return h.fail(y(n)),{success:!1,error:y(n)}}}}});var Fo,tn,Np=w(()=>{"use strict";Ut();Ur();nt();ue();O();je();yn();Fo=class{static{l(this,"ProjectService")}currentAuthor=null;async ensureInit(e){if(await R.isConfigured(e))return{success:!0};h.spin("initializing project...");let{PlanningCommands:t}=await Promise.resolve().then(()=>(Mo(),Fp)),s=await new t().init(null,e);return s.success?{success:!0}:s}async getProjectId(e){let t=await R.getProjectId(e);if(!t)throw Ar.notInitialized();return t}async getGlobalPath(e){let t=await this.getProjectId(e);return await E.ensureProjectStructure(t),E.getGlobalProjectPath(t)}async ensureAuthor(){if(this.currentAuthor)return this.currentAuthor;let e=await qn();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 Nn(e)).filter(s=>!s.startsWith(".")&&s!=="node_modules"&&s!=="package.json"&&s!=="package-lock.json"&&s!=="README.md").length===0}catch(t){return C(t)||console.error(`Directory check error: ${y(t)}`),!0}}async hasExistingCode(e){try{let t=["src","lib","app","components","pages","api","main.go","main.rs","main.py"];return(await Nn(e)).some(s=>t.includes(s))}catch(t){return C(t)||console.error(`Code check error: ${y(t)}`),!1}}async isConfigured(e){return await R.isConfigured(e)}async needsMigration(e){return await R.needsMigration(e)}},tn=new Fo});var Vk,Lp,Up,kc,Hp,zp=w(()=>{"use strict";le();se();Vk=1800*1e3,Lp=50,Up=200,kc=class{static{l(this,"SessionTracker")}async read(e){try{return $.getDoc(e,"session-tracker")??this.getDefault()}catch{return this.getDefault()}}async write(e,t){$.setDoc(e,"session-tracker",t)}getDefault(){return{current:null,config:{idleTimeoutMs:Vk}}}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=k();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=k();s.current.lastActivity=o,s.current.commands.push({command:t,timestamp:o,durationMs:n}),s.current.commands.length>Lp&&(s.current.commands=s.current.commands.slice(-Lp)),await this.write(e,s)}async trackFile(e,t,n){let s=await this.read(e);if(!s.current)return;let o=k();s.current.lastActivity=o,s.current.files.push({path:t,operation:n,timestamp:o}),s.current.files.length>Up&&(s.current.files=s.current.files.slice(-Up)),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),d=n.commands.map(g=>g.command),m=new Set(n.files.filter(g=>g.operation==="read").map(g=>g.path)).size,p=new Set(n.files.filter(g=>g.operation==="write").map(g=>g.path)).size;return{active:!0,id:n.id,duration:xs(s-o),idleSince:n.lastActivity,idleMs:a,expiresIn:xs(u),commandCount:n.commands.length,commands:d,filesRead:m,filesWritten:p}}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}},Hp=new kc});import{exec as Jk}from"node:child_process";import{promisify as qk}from"node:util";var bc,Kk,_o,tr,Gp=w(()=>{"use strict";le();O();zp();bc=qk(Jk),Kk={commitThreshold:10,dayThreshold:3,significantFiles:["package.json","tsconfig.json","Cargo.toml","go.mod","requirements.txt","pyproject.toml",".env.example","docker-compose.yml","Dockerfile"]},_o=class{static{l(this,"StalenessChecker")}projectPath;config;constructor(e,t={}){this.projectPath=e,this.config={...Kk,...t}}async check(e){let t={isStale:!1,reason:null,lastSyncCommit:null,currentCommit:null,commitsSinceSync:0,daysSinceSync:0,changedFiles:[],significantChanges:[]};try{let n={};try{let c=$.getDoc(e,"project");if(!c)return t.isStale=!0,t.reason="No sync history found. Run `prjct sync` to initialize.",t;n=c}catch{return t.isStale=!0,t.reason="No sync history found. Run `prjct sync` to initialize.",t}t.lastSyncCommit=n.lastSyncCommit||null;let s=n.lastSync;try{let{stdout:c}=await bc("git rev-parse --short HEAD",{cwd:this.projectPath});t.currentCommit=c.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;let o=this.projectPath,[i,a]=await Promise.all([bc(`git rev-list --count ${t.lastSyncCommit}..HEAD`,{cwd:o}).catch(()=>null),bc(`git diff --name-only ${t.lastSyncCommit}..HEAD`,{cwd:o}).catch(()=>null)]);if(!i)return t.isStale=!0,t.reason="Sync commit no longer exists (history changed). Run `prjct sync`.",t;if(t.commitsSinceSync=parseInt(i.stdout.trim(),10)||0,t.changedFiles=a?a.stdout.trim().split(`
|
|
797
|
+
`).filter(Boolean):[],s){let c=new Date(s),u=new Date;t.daysSinceSync=Math.floor((u.getTime()-c.getTime())/(1e3*60*60*24))}return t.significantChanges=t.changedFiles.filter(c=>this.config.significantFiles.some(u=>c.endsWith(u)||c.includes(u))),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: ${y(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(`
|
|
798
|
+
`)}async getSessionInfo(e){return Hp.getInfo(e)}formatSessionInfo(e){let t=[];if(!e.active)return t.push("Session: \u25CB No active session"),t.join(`
|
|
935
799
|
`);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(`
|
|
936
|
-
`)}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}},
|
|
937
|
-
`)){let i=o.trim();i==="---COMMIT---"?(s&&s.size>0&&s.size<=
|
|
800
|
+
`)}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}},tr=l((r,e)=>new _o(r,e),"createStalenessChecker")});import Wp from"node:fs/promises";import No from"node:path";function nr(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 Zk(r,e){let t=[],n=e.replace(/\.[^.]+$/,"").split(/[/\\]/).filter(Boolean);for(let p of n)t.push(...nr(p));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 p of s){let g;for(;(g=p.exec(r))!==null;)g[1]&&t.push(...nr(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 p of o){let g;for(;(g=p.exec(r))!==null;)g[1]&&t.push(...nr(g[1]))}let i=/(?:from|import)\s+['"]([^'"]+)['"]/g,a;for(;(a=i.exec(r))!==null;){let p=a[1];if(p.startsWith(".")||p.startsWith("@/"))t.push(...nr(p));else{let g=p.startsWith("@")?p.split("/").slice(0,2).join("/"):p.split("/")[0];t.push(...nr(g))}}let c=/\/\/\s*(.+)/g,u;for(;(u=c.exec(r))!==null;){let p=u[1].toLowerCase().split(/\s+/).filter(g=>g.length>2);t.push(...p)}let d=/\/\*\*?([\s\S]*?)\*\//g,m;for(;(m=d.exec(r))!==null;){let p=m[1].replace(/@\w+/g,"").replace(/\*/g,"").toLowerCase().split(/\s+/).filter(g=>g.length>2&&/^[a-z]+$/.test(g));t.push(...p)}return t.filter(p=>p.length>1&&!Xk.has(p)&&/^[a-z][a-z0-9]*$/.test(p))}async function Bp(r,e){let t=[],n=await Wp.readdir(r,{withFileTypes:!0});for(let s of n){if(Qk.has(s.name))continue;let o=No.join(r,s.name);if(s.isDirectory())t.push(...await Bp(o,e));else if(s.isFile()){let i=No.extname(s.name).toLowerCase();Yk.has(i)&&t.push(No.relative(e,o))}}return t}async function eb(r){let e=await Bp(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 d=>{try{let m=await Wp.readFile(No.join(r,d),"utf-8"),p=Zk(m,d);return{filePath:d,tokens:p}}catch{return{filePath:d,tokens:[]}}}));for(let{filePath:d,tokens:m}of u){if(m.length===0)continue;t[d]={tokens:m,length:m.length},s+=m.length;let p=new Map;for(let g of m)p.set(g,(p.get(g)||0)+1);for(let[g,f]of p)n[g]||(n[g]=[]),n[g].push({path:d,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 nb(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]))};z.setDoc(r,tb,t)}async function Vp(r,e){let t=await eb(r);return nb(e,t),t}var Yk,Xk,Qk,tb,Jp=w(()=>{"use strict";le();Yk=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".cs",".rb",".php",".vue",".svelte"]),Xk=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"]),Qk=new Set(["node_modules",".git","dist","build","out",".next","coverage",".cache",".turbo",".vercel","__pycache__","vendor","target"]);l(nr,"splitIdentifier");l(Zk,"tokenizeFile");l(Bp,"listFiles");l(eb,"buildIndex");tb="bm25-index";l(nb,"saveIndex");l(Vp,"indexProject")});import Pc from"node:fs/promises";import Ht from"node:path";function ab(r){let e=[],t,n=new RegExp(ib.source,"g");for(;(t=n.exec(r))!==null;){let s=t[1];(s.startsWith(".")||s.startsWith("@/"))&&e.push(s)}return e}async function cb(r,e,t){let n;if(r.startsWith("@/"))n=Ht.join(t,"src",r.slice(2));else{let s=Ht.dirname(Ht.join(t,e));n=Ht.resolve(s,r)}for(let s of ob){let o=n+s;try{if((await Pc.stat(o)).isFile())return Ht.relative(t,o)}catch{}}return null}async function qp(r,e){let t=[],n=await Pc.readdir(r,{withFileTypes:!0});for(let s of n){if(rb.has(s.name))continue;let o=Ht.join(r,s.name);if(s.isDirectory())t.push(...await qp(o,e));else if(s.isFile()){let i=Ht.extname(s.name).toLowerCase();sb.has(i)&&t.push(Ht.relative(e,o))}}return t}async function lb(r){let e=await qp(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 d=await Pc.readFile(Ht.join(r,u),"utf-8"),m=ab(d),p=[];for(let g of m){let f=await cb(g,u,r);f&&f!==u&&p.push(f)}return{filePath:u,imports:p}}catch{return{filePath:u,imports:[]}}}));for(let{filePath:u,imports:d}of c)if(d.length!==0){t[u]=d,s+=d.length;for(let m of d)n[m]||(n[m]=[]),n[m].push(u)}}return{forward:t,reverse:n,fileCount:e.length,edgeCount:s,builtAt:new Date().toISOString()}}function ub(r,e){z.setDoc(r,Kp,e)}function Yp(r){return z.getDoc(r,Kp)}async function Xp(r,e){let t=await lb(r);return ub(e,t),t}var sb,rb,ob,ib,Kp,Cc=w(()=>{"use strict";le();sb=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),rb=new Set(["node_modules",".git","dist","build","out",".next","coverage",".cache",".turbo",".vercel"]),ob=["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"],ib=/(?:import|from)\s+['"]([^'"]+)['"]/g;l(ab,"extractImportSources");l(cb,"resolveImport");l(qp,"listFiles");l(lb,"buildGraph");Kp="import-graph";l(ub,"saveGraph");l(Yp,"loadGraph");l(Xp,"indexImports")});function Qp(r,e){let t=[...r.added,...r.modified],n=new Set(t),s=new Set,o=Yp(e);if(o)for(let c of t){let u=o.reverse[c];if(u)for(let d of u)n.has(d)||s.add(d)}let i=Array.from(s),a=[...t,...i];return{directlyChanged:t,affectedByImports:i,deleted:r.deleted,allAffected:a}}function Zp(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 em=w(()=>{"use strict";Cc();l(Qp,"propagateChanges");l(Zp,"affectedDomains")});import xc from"node:fs/promises";import Lo from"node:path";async function tm(r,e){let t=[],n=await xc.readdir(r,{withFileTypes:!0}).catch(()=>[]);for(let s of n){let o=String(s.name);if(pb.has(o)||o.startsWith(".")&&o!==".env.example")continue;let i=Lo.join(r,o);if(s.isDirectory())t.push(...await tm(i,e));else if(s.isFile()){let a=Lo.extname(o).toLowerCase();db.has(a)&&t.push(Lo.relative(e,i))}}return t}function mb(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 gb(r){let e=await tm(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=Lo.join(r,a),[u,d]=await Promise.all([xc.readFile(c,"utf-8"),xc.stat(c)]);return{path:a,hash:mb(u),size:d.size,mtime:d.mtime.toISOString()}}catch{return null}}));for(let a of i)a&&t.set(a.path,a)}return t}function fb(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 vc(r,e){let t=z.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)})(),z.setDoc(r,"file-hashes-meta",{fileCount:e.size,builtAt:new Date().toISOString()})}function hb(r){let e=new Map;try{let t=z.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 Tc(r,e){let[t,n]=await Promise.all([gb(r),Promise.resolve(hb(e))]);return{diff:fb(t,n),currentHashes:t}}function nm(r){return z.hasDoc(r,"file-hashes-meta")}var db,pb,sm=w(()=>{"use strict";le();db=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".css",".scss",".html",".vue",".svelte",".py",".go",".rs",".yaml",".yml",".toml"]),pb=new Set(["node_modules",".git","dist","build","out",".next","coverage",".cache",".turbo",".vercel",".prjct"]);l(tm,"listProjectFiles");l(mb,"hashContent");l(gb,"computeHashes");l(fb,"diffHashes");l(vc,"saveHashes");l(hb,"loadHashes");l(Tc,"detectChanges");l(nm,"hasHashRegistry")});import{exec as yb}from"node:child_process";import{promisify as wb}from"node:util";async function bb(r,e=100){try{let{stdout:t}=await Sb(`git log --name-only --pretty=format:'---COMMIT---' -${e}`,{cwd:r,maxBuffer:10485760}),n=[],s=null;for(let o of t.split(`
|
|
801
|
+
`)){let i=o.trim();i==="---COMMIT---"?(s&&s.size>0&&s.size<=om&&n.push(s),s=new Set):i&&s&&Pb(i)&&s.add(i)}return s&&s.size>0&&s.size<=om&&n.push(s),n}catch{return[]}}function Pb(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 Cb(r,e=100){let t=await bb(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 d=xb(a[c],a[u]);s.set(d,(s.get(d)||0)+1)}}let o={};for(let[i,a]of s){let[c,u]=i.split("\0"),d=n.get(c)||0,m=n.get(u)||0;if(d<rm||m<rm)continue;let p=d+m-a,g=p>0?a/p:0;g<kb||(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 xb(r,e){return r<e?`${r}\0${e}`:`${e}\0${r}`}function Tb(r,e){z.setDoc(r,vb,e)}async function im(r,e,t=100){let n=await Cb(r,t);return Tb(e,n),n}var Sb,kb,rm,om,vb,am=w(()=>{"use strict";le();Sb=wb(yb),kb=.1,rm=2,om=30;l(bb,"parseGitLog");l(Pb,"isSourceFile");l(Cb,"buildMatrix");l(xb,"pairKey");vb="cochange-index";l(Tb,"saveMatrix");l(im,"indexCoChanges")});function ut(r){return`<!-- source: ${r.file}, ${r.type} -->`}function In(){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 Ec=w(()=>{"use strict";l(ut,"cite");l(In,"defaultSources")});function Eb(r,e){let t=r.sources||In();return`# ${r.name} - Project Rules
|
|
938
802
|
<!-- projectId: ${r.projectId} -->
|
|
939
803
|
<!-- Generated: ${new Date().toISOString()} -->
|
|
940
804
|
<!-- Ecosystem: ${r.ecosystem} | Type: ${r.projectType} -->
|
|
941
805
|
|
|
942
806
|
## THIS PROJECT (${r.ecosystem})
|
|
943
807
|
|
|
944
|
-
${
|
|
808
|
+
${ut(t.ecosystem)}
|
|
945
809
|
**Type:** ${r.projectType}
|
|
946
810
|
**Path:** ${r.repoPath}
|
|
947
811
|
|
|
948
812
|
### Commands (USE THESE, NOT OTHERS)
|
|
949
813
|
|
|
950
|
-
${
|
|
814
|
+
${ut(t.commands)}
|
|
951
815
|
| Action | Command |
|
|
952
816
|
|--------|---------|
|
|
953
817
|
| Install dependencies | \`${r.commands.install}\` |
|
|
@@ -959,9 +823,9 @@ ${$e(t.commands)}
|
|
|
959
823
|
|
|
960
824
|
### Code Conventions
|
|
961
825
|
|
|
962
|
-
${
|
|
826
|
+
${ut(t.languages)}
|
|
963
827
|
- **Languages**: ${r.languages.join(", ")||"Not detected"}
|
|
964
|
-
${
|
|
828
|
+
${ut(t.frameworks)}
|
|
965
829
|
- **Frameworks**: ${r.frameworks.join(", ")||"Not detected"}
|
|
966
830
|
|
|
967
831
|
---
|
|
@@ -989,7 +853,7 @@ p. sync \u2192 p. task "desc" \u2192 [work] \u2192 p. done \u2192 p. ship
|
|
|
989
853
|
|
|
990
854
|
## PROJECT STATE
|
|
991
855
|
|
|
992
|
-
${
|
|
856
|
+
${ut(t.name)}
|
|
993
857
|
| Field | Value |
|
|
994
858
|
|-------|-------|
|
|
995
859
|
| Name | ${r.name} |
|
|
@@ -1007,163 +871,12 @@ Load from \`~/.prjct-cli/projects/${r.projectId}/agents/\`:
|
|
|
1007
871
|
|
|
1008
872
|
**Workflow**: ${r.agents.workflow.join(", ")}
|
|
1009
873
|
**Domain**: ${r.agents.domain.join(", ")||"none"}
|
|
1010
|
-
`}function
|
|
1011
|
-
`)}function
|
|
1012
|
-
`)}function
|
|
1013
|
-
`)}function
|
|
1014
|
-
`),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
|
|
1015
|
-
|
|
1016
|
-
<!-- Generated: ${b()} -->
|
|
1017
|
-
<!-- Ecosystem: ${n.ecosystem} | Type: ${n.projectType} -->
|
|
1018
|
-
|
|
1019
|
-
## THIS PROJECT (${n.ecosystem})
|
|
1020
|
-
|
|
1021
|
-
${$e(u.ecosystem)}
|
|
1022
|
-
**Type:** ${n.projectType}
|
|
1023
|
-
**Path:** ${this.config.projectPath}
|
|
1024
|
-
|
|
1025
|
-
### Commands (USE THESE, NOT OTHERS)
|
|
1026
|
-
|
|
1027
|
-
${$e(u.commands)}
|
|
1028
|
-
| Action | Command |
|
|
1029
|
-
|--------|---------|
|
|
1030
|
-
| Install dependencies | \`${s.install}\` |
|
|
1031
|
-
| Run dev server | \`${s.dev}\` |
|
|
1032
|
-
| Run tests | \`${s.test}\` |
|
|
1033
|
-
| Build | \`${s.build}\` |
|
|
1034
|
-
| Lint | \`${s.lint}\` |
|
|
1035
|
-
| Format | \`${s.format}\` |
|
|
1036
|
-
|
|
1037
|
-
### Code Conventions
|
|
1038
|
-
|
|
1039
|
-
${$e(u.languages)}
|
|
1040
|
-
- **Languages**: ${n.languages.join(", ")||"Not detected"}
|
|
1041
|
-
${$e(u.frameworks)}
|
|
1042
|
-
- **Frameworks**: ${n.frameworks.join(", ")||"Not detected"}
|
|
1043
|
-
|
|
1044
|
-
---
|
|
1045
|
-
|
|
1046
|
-
## PRJCT RULES
|
|
1047
|
-
|
|
1048
|
-
### Path Resolution
|
|
1049
|
-
**ALL prjct writes go to**: \`~/.prjct-cli/projects/${this.config.projectId}/\`
|
|
1050
|
-
- NEVER write to \`.prjct/\`
|
|
1051
|
-
- NEVER write to \`./\` for prjct data
|
|
1052
|
-
|
|
1053
|
-
### Workflow
|
|
1054
|
-
\`\`\`
|
|
1055
|
-
p. sync \u2192 p. task "desc" \u2192 [work] \u2192 p. done \u2192 p. ship
|
|
1056
|
-
\`\`\`
|
|
1057
|
-
|
|
1058
|
-
| Command | Action |
|
|
1059
|
-
|---------|--------|
|
|
1060
|
-
| \`p. sync\` | Re-analyze project |
|
|
1061
|
-
| \`p. task X\` | Start task |
|
|
1062
|
-
| \`p. done\` | Complete subtask |
|
|
1063
|
-
| \`p. ship X\` | Ship feature |
|
|
1064
|
-
|
|
1065
|
-
---
|
|
1066
|
-
|
|
1067
|
-
## PROJECT STATE
|
|
1068
|
-
|
|
1069
|
-
${$e(u.name)}
|
|
1070
|
-
| Field | Value |
|
|
1071
|
-
|-------|-------|
|
|
1072
|
-
| Name | ${n.name} |
|
|
1073
|
-
| Version | ${n.version} |
|
|
1074
|
-
| Ecosystem | ${n.ecosystem} |
|
|
1075
|
-
| Branch | ${t.branch} |
|
|
1076
|
-
| Files | ~${n.fileCount} |
|
|
1077
|
-
| Commits | ${t.commits} |
|
|
1078
|
-
|
|
1079
|
-
---
|
|
1080
|
-
|
|
1081
|
-
## AGENTS
|
|
1082
|
-
|
|
1083
|
-
Load from \`~/.prjct-cli/projects/${this.config.projectId}/agents/\`:
|
|
1084
|
-
|
|
1085
|
-
**Workflow**: ${a.join(", ")}
|
|
1086
|
-
**Domain**: ${c.join(", ")||"none"}
|
|
1087
|
-
`,m=Ut.join(e,"CLAUDE.md");await this.writeWithPreservation(m,d)}async generateNowMd(e){let t=null;try{t=(await O.read(this.config.projectId)).currentTask}catch{}let n=t?.branch,s=typeof n=="string"?n:n?.name,o=t?`# NOW
|
|
1088
|
-
|
|
1089
|
-
**${t.description}**
|
|
1090
|
-
|
|
1091
|
-
Started: ${t.startedAt}
|
|
1092
|
-
${s?`Branch: ${s}`:""}
|
|
1093
|
-
`:`# NOW
|
|
1094
|
-
|
|
1095
|
-
_No active task_
|
|
1096
|
-
|
|
1097
|
-
Use \`p. task "description"\` to start working.
|
|
1098
|
-
`;await this.writeWithPreservation(Ut.join(e,"now.md"),o)}async generateNextMd(e){let t={tasks:[]};try{t={tasks:(await ce.read(this.config.projectId)).tasks||[]}}catch{}let n=`# NEXT
|
|
1099
|
-
|
|
1100
|
-
${t.tasks.length>0?t.tasks.map((s,o)=>`${o+1}. ${s.description}${s.priority?` [${s.priority}]`:""}`).join(`
|
|
1101
|
-
`):"_Empty queue_"}
|
|
1102
|
-
`;await this.writeWithPreservation(Ut.join(e,"next.md"),n)}async generateIdeasMd(e){let t={ideas:[]};try{t={ideas:(await Ee.read(this.config.projectId)).ideas||[]}}catch{}let n=`# IDEAS
|
|
1103
|
-
|
|
1104
|
-
${t.ideas.length>0?t.ideas.map(s=>`- ${s.text}${s.priority?` [${s.priority}]`:""}`).join(`
|
|
1105
|
-
`):"_No ideas captured yet_"}
|
|
1106
|
-
`;await this.writeWithPreservation(Ut.join(e,"ideas.md"),n)}async generateShippedMd(e){let t={shipped:[]};try{t={shipped:(await He.read(this.config.projectId)).shipped||[]}}catch{}let n=`# SHIPPED \u{1F680}
|
|
1107
|
-
|
|
1108
|
-
${t.shipped.length>0?t.shipped.slice(-10).map(s=>`- **${s.name}**${s.version?` v${s.version}`:""} - ${s.shippedAt}`).join(`
|
|
1109
|
-
`):"_Nothing shipped yet_"}
|
|
1110
|
-
|
|
1111
|
-
**Total shipped:** ${t.shipped.length}
|
|
1112
|
-
`;await this.writeWithPreservation(Ut.join(e,"shipped.md"),n)}async generateMonorepoContexts(e,t,n,s){let o=await T.detectMonorepo(this.config.projectPath);if(!o.isMonorepo)return[];let i=[],a=new sr(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 d=await this.generatePackageClaudeMd(c,u,e,t,n,s),m=Ut.join(c.path,"CLAUDE.md");await this.writeWithPreservation(m,d),i.push(Ut.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,d=e.name;try{let m=Ut.join(e.path,"package.json"),p=JSON.parse(await qc.readFile(m,"utf-8"));u=p.version||s.version,d=p.name||e.name}catch{}return`# ${d} - Package Rules
|
|
1113
|
-
<!-- package: ${e.relativePath} -->
|
|
1114
|
-
<!-- monorepo: ${s.name} -->
|
|
1115
|
-
<!-- Generated: ${b()} -->
|
|
1116
|
-
<!-- Sources: ${t.sources.join(" \u2192 ")} -->
|
|
1117
|
-
|
|
1118
|
-
## THIS PACKAGE
|
|
1119
|
-
|
|
1120
|
-
**Name:** ${d}
|
|
1121
|
-
**Path:** ${e.relativePath}
|
|
1122
|
-
**Version:** ${u}
|
|
1123
|
-
**Monorepo:** ${s.name}
|
|
1124
|
-
|
|
1125
|
-
---
|
|
1126
|
-
|
|
1127
|
-
## INHERITED CONTEXT
|
|
1128
|
-
|
|
1129
|
-
${t.content||"_No PRJCT.md rules defined_"}
|
|
1130
|
-
|
|
1131
|
-
${t.overrides.length>0?`
|
|
1132
|
-
**Overrides:** ${t.overrides.join(", ")}
|
|
1133
|
-
`:""}
|
|
1134
|
-
|
|
1135
|
-
---
|
|
1136
|
-
|
|
1137
|
-
## COMMANDS
|
|
1138
|
-
|
|
1139
|
-
| Action | Command |
|
|
1140
|
-
|--------|---------|
|
|
1141
|
-
| Install | \`${o.install}\` |
|
|
1142
|
-
| Dev | \`${o.dev}\` |
|
|
1143
|
-
| Test | \`${o.test}\` |
|
|
1144
|
-
| Build | \`${o.build}\` |
|
|
1145
|
-
|
|
1146
|
-
---
|
|
1147
|
-
|
|
1148
|
-
## PROJECT STATE
|
|
1149
|
-
|
|
1150
|
-
| Field | Value |
|
|
1151
|
-
|-------|-------|
|
|
1152
|
-
| Package | ${d} |
|
|
1153
|
-
| Monorepo | ${s.name} |
|
|
1154
|
-
| Branch | ${n.branch} |
|
|
1155
|
-
| Ecosystem | ${s.ecosystem} |
|
|
1156
|
-
|
|
1157
|
-
---
|
|
1158
|
-
|
|
1159
|
-
## AGENTS
|
|
1160
|
-
|
|
1161
|
-
Load from \`~/.prjct-cli/projects/${this.config.projectId}/agents/\`:
|
|
1162
|
-
|
|
1163
|
-
**Workflow**: ${a.join(", ")}
|
|
1164
|
-
**Domain**: ${c.join(", ")||"none"}
|
|
1165
|
-
`}}});import Kc from"node:fs/promises";import Yc from"node:path";var Xc,Qc,Fm,Om=y(()=>{"use strict";F();Xc=".prjct-state.md",Qc=class{static{l(this,"LocalStateGenerator")}async generate(e,t){let n=Yc.join(e,Xc),s=this.toMarkdown(t);await Kc.writeFile(n,s,"utf-8")}async remove(e){let t=Yc.join(e,Xc);try{await Kc.unlink(t)}catch(n){if(!C(n))throw n}}async exists(e){let t=Yc.join(e,Xc);try{return await Kc.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",d=c===n.currentSubtaskIndex?" \u2190 **Active**":"";t.push(`${c+1}. ${u} ${a.description}${d}`)}),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(`
|
|
1166
|
-
`)}},Fm=new Qc});import Zc from"node:fs/promises";import mP from"node:os";import _m from"node:path";function el(){return _m.join(mP.homedir(),".prjct-cli","skills",gP)}function fP(){return{version:1,generatedAt:new Date().toISOString(),skills:{}}}async function hr(){try{let r=await Zc.readFile(el(),"utf-8");return JSON.parse(r)}catch{return fP()}}async function tl(r){let e=el();await Zc.mkdir(_m.dirname(e),{recursive:!0}),r.generatedAt=new Date().toISOString(),await Zc.writeFile(e,JSON.stringify(r,null,2),"utf-8")}async function hP(r){let e=await hr();e.skills[r.name]=r,await tl(e)}async function yP(r){let e=await hr();return r in e.skills?(delete e.skills[r],await tl(e),!0):!1}async function wP(r){return(await hr()).skills[r]||null}async function SP(){return(await hr()).skills}function kP(){return el()}var gP,yr,Nm=y(()=>{"use strict";gP=".skill-lock.json";l(el,"getLockFilePath");l(fP,"createEmptyLockFile");l(hr,"read");l(tl,"write");l(hP,"addEntry");l(yP,"removeEntry");l(wP,"getEntry");l(SP,"getAll");l(kP,"getPath");yr={read:hr,write:tl,addEntry:hP,removeEntry:yP,getEntry:wP,getAll:SP,getPath:kP}});import{exec as bP}from"node:child_process";import Jt from"node:fs/promises";import sl from"node:os";import Be from"node:path";import{promisify as PP}from"node:util";import{glob as Lm}from"glob";function Hm(r){if(r.startsWith("./")||r.startsWith("/")||r.startsWith("~")){let n=r.startsWith("~")?Be.join(sl.homedir(),r.slice(1)):Be.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 Gm(r){let e=[];try{let s=Be.join(r,"SKILL.md");await Jt.access(s);let o=Be.basename(r);e.push({name:o,filePath:s})}catch{}let t=await Lm("*/SKILL.md",{cwd:r,absolute:!0});for(let s of t){let o=Be.basename(Be.dirname(s));e.some(i=>i.name===o)||e.push({name:o,filePath:s})}let n=await Lm("skills/*/SKILL.md",{cwd:r,absolute:!0});for(let s of n){let o=Be.basename(Be.dirname(s));e.some(i=>i.name===o)||e.push({name:o,filePath:s})}return e}function CP(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()}
|
|
874
|
+
`}function Ab(r,e){let t=r.sources||In(),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(ut(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(ut(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(`
|
|
875
|
+
`)}function Ib(r,e){let t=r.sources||In(),n=[];return n.push("# Copilot Instructions"),n.push(""),n.push(`This is ${r.name}, a ${r.ecosystem} project.`),n.push(""),n.push(ut(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(ut(t.commands)),n.push("## Commands"),n.push(`- Test: \`${r.commands.test}\``),n.push(`- Build: \`${r.commands.build}\``),n.join(`
|
|
876
|
+
`)}function Db(r,e){let t=r.sources||In(),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(ut(t.languages)),n.push("## Stack"),n.push(`- ${r.languages.join(", ")}`),r.frameworks.length>0&&n.push(`- ${r.frameworks.join(", ")}`),n.push(""),n.push(ut(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(`
|
|
877
|
+
`)}function Rb(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(`
|
|
878
|
+
`),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 cm(r){return{claude:Eb,cursor:Ab,copilot:Ib,windsurf:Db,continue:Rb}[r]||null}var Ac=w(()=>{"use strict";Ec();l(Eb,"formatForClaude");l(Ab,"formatForCursor");l(Ib,"formatForCopilot");l(Db,"formatForWindsurf");l(Rb,"formatForContinue");l(cm,"getFormatter")});import{exec as jb}from"node:child_process";import $b from"node:os";import sr from"node:path";import{promisify as Mb}from"node:util";function lm(r){return Uo[r]||null}async function Ic(r){try{return await Ob(`which ${r}`),!0}catch{return!1}}async function Ho(r=process.cwd()){let e=[];return await Ic("claude")&&e.push("claude"),(await Ic("cursor")||await M(sr.join(r,".cursor")))&&e.push("cursor"),await M(sr.join(r,".github"))&&e.push("copilot"),(await Ic("windsurf")||await M(sr.join(r,".windsurf")))&&e.push("windsurf"),(await M(sr.join(r,".continue"))||await M(sr.join($b.homedir(),".continue")))&&e.push("continue"),e}async function um(r,e=process.cwd()){if(r==="auto"){let t=await Ho(e);return t.length>0?t:["claude"]}return r==="all"?Fb:r.filter(t=>Uo[t])}var Ob,Uo,rr,Fb,Dc=w(()=>{"use strict";je();Ob=Mb(jb),Uo={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"}},rr=["claude"],Fb=Object.keys(Uo);l(lm,"getAIToolConfig");l(Ic,"commandExists");l(Ho,"detectInstalledTools");l(um,"resolveToolIds")});import Rc from"node:fs/promises";import jc from"node:path";async function dm(r,e,t,n=rr){let s=[];for(let o of n){let i=lm(o);if(!i){s.push({toolId:o,outputFile:"",outputPath:"",success:!1,error:`Unknown tool: ${o}`});continue}let a=await _b(r,i,e,t);s.push(a)}return s}async function _b(r,e,t,n){let s=cm(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=jc.join(n,e.outputFile):i=jc.join(t,"context",e.outputFile),await Rc.mkdir(jc.dirname(i),{recursive:!0});try{let a=await Rc.readFile(i,"utf-8"),c=Ki(a);if(!c.valid){console.warn(`\u26A0\uFE0F ${e.outputFile} has invalid preserve blocks:`);for(let u of c.errors)console.warn(` ${u}`)}o=qi(o,a)}catch{}return await Rc.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:y(o)}}}var pm=w(()=>{"use strict";O();Yi();Ac();Dc();l(dm,"generateAIToolContexts");l(_b,"generateForTool")});var mm=w(()=>{"use strict";Ac();pm();Dc()});import $c from"node:fs/promises";import Mc from"node:path";var Oc,Fc,gm,fm=w(()=>{"use strict";O();Oc=".prjct-state.md",Fc=class{static{l(this,"LocalStateGenerator")}async generate(e,t){let n=Mc.join(e,Oc),s=this.toMarkdown(t);await $c.writeFile(n,s,"utf-8")}async remove(e){let t=Mc.join(e,Oc);try{await $c.unlink(t)}catch(n){if(!C(n))throw n}}async exists(e){let t=Mc.join(e,Oc);try{return await $c.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",d=c===n.currentSubtaskIndex?" \u2190 **Active**":"";t.push(`${c+1}. ${u} ${a.description}${d}`)}),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(`
|
|
879
|
+
`)}},gm=new Fc});import _c from"node:fs/promises";import Nb from"node:os";import hm from"node:path";function Nc(){return hm.join(Nb.homedir(),".prjct-cli","skills",Lb)}function Ub(){return{version:1,generatedAt:new Date().toISOString(),skills:{}}}async function or(){try{let r=await _c.readFile(Nc(),"utf-8");return JSON.parse(r)}catch{return Ub()}}async function Lc(r){let e=Nc();await _c.mkdir(hm.dirname(e),{recursive:!0}),r.generatedAt=new Date().toISOString(),await _c.writeFile(e,JSON.stringify(r,null,2),"utf-8")}async function Hb(r){let e=await or();e.skills[r.name]=r,await Lc(e)}async function zb(r){let e=await or();return r in e.skills?(delete e.skills[r],await Lc(e),!0):!1}async function Gb(r){return(await or()).skills[r]||null}async function Wb(){return(await or()).skills}function Bb(){return Nc()}var Lb,ir,ym=w(()=>{"use strict";Lb=".skill-lock.json";l(Nc,"getLockFilePath");l(Ub,"createEmptyLockFile");l(or,"read");l(Lc,"write");l(Hb,"addEntry");l(zb,"removeEntry");l(Gb,"getEntry");l(Wb,"getAll");l(Bb,"getPath");ir={read:or,write:Lc,addEntry:Hb,removeEntry:zb,getEntry:Gb,getAll:Wb,getPath:Bb}});import{exec as Vb}from"node:child_process";import zt from"node:fs/promises";import Hc from"node:os";import ze from"node:path";import{promisify as Jb}from"node:util";import{glob as wm}from"glob";function km(r){if(r.startsWith("./")||r.startsWith("/")||r.startsWith("~")){let n=r.startsWith("~")?ze.join(Hc.homedir(),r.slice(1)):ze.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 bm(r){let e=[];try{let s=ze.join(r,"SKILL.md");await zt.access(s);let o=ze.basename(r);e.push({name:o,filePath:s})}catch{}let t=await wm("*/SKILL.md",{cwd:r,absolute:!0});for(let s of t){let o=ze.basename(ze.dirname(s));e.some(i=>i.name===o)||e.push({name:o,filePath:s})}let n=await wm("skills/*/SKILL.md",{cwd:r,absolute:!0});for(let s of n){let o=ze.basename(ze.dirname(s));e.some(i=>i.name===o)||e.push({name:o,filePath:s})}return e}function qb(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()}
|
|
1167
880
|
${s.join(`
|
|
1168
881
|
`)}`;return r.replace(o,`---
|
|
1169
882
|
${c}
|
|
@@ -1172,10 +885,10 @@ ${s.join(`
|
|
|
1172
885
|
`)}
|
|
1173
886
|
---
|
|
1174
887
|
|
|
1175
|
-
${r}`}function
|
|
888
|
+
${r}`}function zc(){return ze.join(Hc.homedir(),".claude","skills")}async function Uc(r,e,t,n){let s=zc(),o=ze.join(s,e),i=ze.join(o,"SKILL.md"),a=await zt.readFile(r,"utf-8"),c=qb(a,t,n);return await zt.mkdir(o,{recursive:!0}),await zt.writeFile(i,c,"utf-8"),{name:e,filePath:i,source:t,sha:n}}async function Kb(r){let e={installed:[],skipped:[],errors:[]};if(!so.isAvailable("git")){let n=so.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=ze.join(Hc.tmpdir(),`prjct-skill-${Date.now()}`);try{let n=`https://github.com/${r.owner}/${r.repo}.git`;await Sm(`git clone --depth 1 ${n} ${t}`,{timeout:Qr("GIT_CLONE")});let s;try{let{stdout:a}=await Sm("git rev-parse HEAD",{cwd:t,timeout:Qr("TOOL_CHECK")});s=a.trim()}catch{}let o=await bm(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 Uc(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 ir.addEntry(u),e.installed.push(c)}catch(c){e.errors.push(`Failed to install ${a.name}: ${y(c)}`)}}finally{try{await zt.rm(t,{recursive:!0,force:!0})}catch{}}return e}async function Yb(r){let e={installed:[],skipped:[],errors:[]},t=r.localPath;try{await zt.access(t)}catch{return e.errors.push(`Local path not found: ${t}`),e}if((await zt.stat(t)).isFile()){let s=ze.basename(ze.dirname(t));try{let o=await Uc(t,s,r),i={name:s,source:{type:"local",url:t},installedAt:new Date().toISOString(),filePath:o.filePath};await ir.addEntry(i),e.installed.push(o)}catch(o){e.errors.push(`Failed to install from ${t}: ${y(o)}`)}}else{let s=await bm(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 Uc(o.filePath,o.name,r),a={name:o.name,source:{type:"local",url:t},installedAt:new Date().toISOString(),filePath:i.filePath};await ir.addEntry(a),e.installed.push(i)}catch(i){e.errors.push(`Failed to install ${o.name}: ${y(i)}`)}}return e}async function Xb(r){let e=zc(),t=ze.join(e,r);try{await zt.rm(t,{recursive:!0,force:!0})}catch{}let n=ze.join(e,`${r}.md`);try{await zt.rm(n,{force:!0})}catch{}return ir.removeEntry(r)}async function Qb(r){let e=km(r);switch(e.type){case"github":return Kb(e);case"local":return Yb(e);default:return{installed:[],skipped:[],errors:[`Unsupported source type: ${e.type}`]}}}var Sm,Pm,Cm=w(()=>{"use strict";O();Yt();ma();ym();Sm=Jb(Vb);l(km,"parseSource");l(bm,"discoverSkills");l(qb,"injectSourceMetadata");l(zc,"getInstallDir");l(Uc,"installSkillFile");l(Kb,"installFromGitHub");l(Yb,"installFromLocal");l(Xb,"remove");l(Qb,"install");Pm={install:Qb,remove:Xb,parseSource:km,getInstallDir:zc}});import dt from"node:fs/promises";import Zb from"node:os";import it from"node:path";async function xm(r,e,t,n){let s=[],o=it.join(r,"agents");try{let c=await dt.readdir(o);for(let u of c)u.endsWith(".md")&&await dt.unlink(it.join(o,u))}catch(c){B.debug("Failed to purge old agents",{path:o,error:K(c)})}let i=["prjct-workflow","prjct-planner","prjct-shipper"];await Promise.all(i.map(c=>eP(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=>tP(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 vm(r){let e=it.join(r,"agents"),t=[];try{let n=await dt.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 Tm(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=ve(`subagents/${o}.md`);if(!i){let a=it.join(__dirname,"..","..","templates","subagents",`${o}.md`);try{i=await dt.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 eP(r,e){let t="";try{let n=it.join(__dirname,"..","..","templates","subagents","workflow",`${r}.md`);t=await dt.readFile(n,"utf-8"),t=await Tm(t)}catch(n){B.debug("Workflow agent template not found, generating minimal",{name:r,error:K(n)}),t=sP(r)}await dt.writeFile(it.join(e,`${r}.md`),t,"utf-8")}async function tP(r,e,t,n,s){let o="";try{let i=it.join(__dirname,"..","..","templates","subagents","domain",`${r}.md`);o=await dt.readFile(i,"utf-8"),o=await Tm(o),o=o.replace("{projectName}",t.name),o=o.replace("{frameworks}",n.frameworks.join(", ")||"None detected"),o=o.replace("{ecosystem}",t.ecosystem)}catch(i){B.debug("Domain agent template not found, generating minimal",{name:r,error:K(i)}),o=rP(r,t,n)}o=nP(o,r,s),await dt.writeFile(it.join(e,`${r}.md`),o,"utf-8")}function nP(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=[`
|
|
1176
889
|
## Recent Learnings (from completed tasks)
|
|
1177
890
|
`];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 d=u.note?` \u2014 ${u.note}`:"";c.push(`- ${u.rating}${d}`)}c.push("")}return r+c.join(`
|
|
1178
|
-
`)}function
|
|
891
|
+
`)}function sP(r){return`---
|
|
1179
892
|
name: ${r}
|
|
1180
893
|
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"}
|
|
1181
894
|
tools: Read, Write, Glob
|
|
@@ -1191,7 +904,7 @@ When invoked:
|
|
|
1191
904
|
1. Read \`.prjct/prjct.config.json\` \u2192 extract \`projectId\`
|
|
1192
905
|
2. Read \`~/.prjct-cli/projects/{projectId}/storage/state.json\`
|
|
1193
906
|
3. Execute requested operation
|
|
1194
|
-
`}function
|
|
907
|
+
`}function rP(r,e,t){return`---
|
|
1195
908
|
name: ${r}
|
|
1196
909
|
description: ${r.charAt(0).toUpperCase()+r.slice(1)} specialist for ${e.name}
|
|
1197
910
|
tools: Read, Write, Glob, Grep
|
|
@@ -1211,17 +924,17 @@ Domain specialist for ${r} tasks.
|
|
|
1211
924
|
## Your Role
|
|
1212
925
|
|
|
1213
926
|
You are the ${r} expert for this project. Apply best practices for the detected stack.
|
|
1214
|
-
`}function
|
|
1215
|
-
`).filter(Boolean);e.hasChanges=i.length>0;for(let u of i){let d=u.substring(0,2),m=u.substring(3);d.startsWith("A")||d.startsWith("M ")?e.stagedFiles.push(m):d.includes("M")?e.modifiedFiles.push(m):d.startsWith("??")&&e.untrackedFiles.push(m)}let{stdout:a}=await
|
|
1216
|
-
`).filter(Boolean).map(u=>{let[d,m,p]=u.split("|");return{hash:d,message:m,date:p}});let{stdout:c}=await Fn('git log --oneline --since="1 week ago" | wc -l',{cwd:r});e.weeklyCommits=parseInt(c.trim(),10)||0}catch(t){B.debug("Git analysis failed (not a git repo?)",{error:K(t)})}return e}async function Ht(r,e){try{return await eg.access(ol.join(r,e)),!0}catch(t){return B.debug("File not found",{filename:e,error:K(t)}),!1}}async function ng(r){let e={fileCount:0,version:"0.0.0",name:ol.basename(r),ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]};try{let{stdout:t}=await Fn('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){B.debug("File count failed",{path:r,error:K(t)}),e.fileCount=0}try{let t=ol.join(r,"package.json"),n=JSON.parse(await eg.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 Ht(r,"tsconfig.json")?e.languages.push("TypeScript"):e.languages.push("JavaScript")}catch(t){B.debug("No package.json found",{path:r,error:K(t)})}return await Ht(r,"Cargo.toml")&&(e.ecosystem="Rust",e.languages.push("Rust")),await Ht(r,"go.mod")&&(e.ecosystem="Go",e.languages.push("Go")),(await Ht(r,"requirements.txt")||await Ht(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 sg(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 Ht(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 Ht(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 Ht(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 Ht(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 Ht(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 rg(r,e){let t=Vt(),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 og(r){return new ni(r).detect()}var Fn,ig=y(()=>{"use strict";zt();Qo();qn();Zm();Fn=FP(MP);l(tg,"analyzeGit");l(Ht,"fileExists");l(ng,"gatherStats");l(sg,"detectCommands");l(rg,"buildSources");l(og,"detectStack")});import{exec as OP}from"node:child_process";import il from"node:fs/promises";import si from"node:path";import{promisify as _P}from"node:util";var NP,al,cl,ag,cg=y(()=>{"use strict";Ct();F();NP=_P(OP),al={async contextFilesExist(r){let e=Date.now(),t=["context/CLAUDE.md"],n=[];for(let s of t){let o=si.join(r,s);try{await il.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=[],n=si.basename(r);try{await O.read(n)}catch(s){C(s)||t.push(`state: ${w(s)}`)}return{name:"State data valid",passed:t.length===0,output:t.length===0?"1 store validated":void 0,error:t.length>0?t.join("; "):void 0,durationMs:Date.now()-e}},async noSensitiveData(r){let e=Date.now(),t=si.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 il.readdir(t);for(let i of o){if(!i.endsWith(".md"))continue;let a=await il.readFile(si.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(!C(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}}},cl=class{static{l(this,"SyncVerifier")}async verify(e,t,n){let s=Date.now(),o=[],i=n?.failFast??!1,a=0,c=[al.contextFilesExist(t),al.jsonFilesValid(t),al.noSensitiveData(t)];for(let p of c){let g=await p;if(o.push(g),!g.passed&&i){a=n?.checks?.filter(f=>f.enabled!==!1).length??0;break}}if((!i||o.every(p=>p.passed))&&n?.checks)for(let p of n.checks){if(p.enabled===!1){a++;continue}let g=await this.runCustomCheck(p,e);if(o.push(g),!g.passed&&i){let f=n.checks.slice(n.checks.indexOf(p)+1);a+=f.filter(S=>S.enabled!==!1).length;break}}let d=o.filter(p=>!p.passed).length,m=o.filter(p=>p.passed).length;return{passed:d===0,checks:o,totalMs:Date.now()-s,failedCount:d,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 NP(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}}}},ag=new cl});import ri from"node:fs/promises";import oi from"node:path";var ii,wr,lg=y(()=>{"use strict";rs();mm();km();Cm();Em();Lc();zt();Pn();it();re();Gr();tn();de();Xn();Yr();Qr();Zn();es();ts();$m();te();qn();tc();nc();Mm();Om();Ba();Ym();ig();cg();ii=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 ei(e)).filter(i=>!fr.includes(i));s=[...fr,...o]}else t.aiTools[0]==="auto"?(s=await ei(e),s.length===0&&(s=["claude"])):t.aiTools[0]==="all"?s=await Dm("all",e):s=t.aiTools;try{if(this.projectId=await R.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=T.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await this.ensureDirectories(),await Bs(this.projectId);try{let H=await Xr(this.projectId);H>0&&B.info("Swept legacy JSON files into SQLite",{swept:H})}catch(H){B.debug("Legacy JSON sweep failed (non-critical)",{error:K(H)})}let[i,a,c,u]=await Promise.all([tg(this.projectPath),ng(this.projectPath),sg(this.projectPath),og(this.projectPath)]),d=t.full===!0,m,p=!0,g=!0,f=new Set;if(!d&&Pm(this.projectId))try{let{diff:H,currentHashes:Zg}=await Gc(this.projectPath,this.projectId),Rl=H.added.length+H.modified.length+H.deleted.length;if(Rl===0&&!t.changedFiles?.length)p=!1,g=!1,m={isIncremental:!0,filesChanged:0,filesUnchanged:H.unchanged.length,indexesRebuilt:!1,agentsRegenerated:!1,affectedDomains:[]};else{let vi=wm(H,this.projectId);f=Sm(vi.allAffected);let ef=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);p=vi.allAffected.some(dn=>{let tf=dn.substring(dn.lastIndexOf("."));return ef.has(tf)}),g=vi.directlyChanged.some(dn=>dn==="package.json"||dn==="tsconfig.json"||dn.includes("Dockerfile")||dn.includes("docker-compose")),m={isIncremental:!0,filesChanged:Rl,filesUnchanged:H.unchanged.length,indexesRebuilt:p,agentsRegenerated:g,affectedDomains:Array.from(f)}}Hc(this.projectId,Zg)}catch(H){B.debug("Incremental detection failed, falling back to full sync",{error:K(H)})}else try{let{currentHashes:H}=await Gc(this.projectPath,this.projectId);Hc(this.projectId,H)}catch(H){B.debug("Hash computation failed (non-critical)",{error:K(H)})}if(p)try{await Promise.all([pm(this.projectPath,this.projectId),ym(this.projectPath,this.projectId),Tm(this.projectPath,this.projectId)])}catch(H){B.debug("File ranking index build failed (non-critical)",{error:K(H)})}let S;if(g)try{let H=await O.getAggregatedFeedback(this.projectId);(H.patternsDiscovered.length>0||H.knownGotchas.length>0||H.agentAccuracy.length>0)&&(S=H)}catch{}let k=g?await Bm(this.globalPath,u,a,S):await Vm(this.globalPath),v=qm(k,this.projectId,this.globalPath),D=g?await Km(k):[],q=rg(a,c),Me=await this.generateContextFiles(i,a,c,k,q),qe={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:k.filter(H=>H.type==="workflow").map(H=>H.name),domain:k.filter(H=>H.type==="domain").map(H=>H.name)},sources:q},ht=await jm(qe,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 P=Date.now()-n,I=await this.recordSyncMetrics(a,Me,k,P);await this.archiveStaleData(),await this.autoLearnFromHistory(),await Ge.installGlobalConfig(),await Ge.syncCommands();let ke;try{let H=await R.readConfig(this.projectPath);ke=await ag.verify(this.projectPath,this.globalPath,H?.verification)}catch(H){B.debug("Verification failed (non-critical)",{error:K(H)})}return{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:i,stats:a,commands:c,stack:u,agents:k,skills:v,skillsInstalled:D,contextFiles:Me,aiTools:ht.map(H=>({toolId:H.toolId,outputFile:H.outputFile,success:H.success})),syncMetrics:I,verification:ke,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:K(o)}}}async ensureDirectories(){let e=["storage","context","agents","memory","analysis","config","sync"];await Promise.all(e.map(t=>ri.mkdir(oi.join(this.globalPath,t),{recursive:!0})))}async generateContextFiles(e,t,n,s,o){return new ti({projectId:this.projectId,projectPath:this.projectPath,globalPath:this.globalPath}).generate(e,t,n,s,o)}async updateProjectJson(e,t){let n=M.getDoc(this.projectId,"project")||{},s={...n,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:n.createdAt||b(),lastSync:b(),lastSyncCommit:e.recentCommits[0]?.hash||null,lastSyncBranch:e.branch};M.setDoc(this.projectId,"project",s)}async updateStateJson(e,t){let s={...await O.read(this.projectId)};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 O.write(this.projectId,s);try{await Fm.generate(this.projectPath,s)}catch(o){B.debug("Local state generation failed (optional)",{error:K(o)})}}async logToMemory(e,t){M.appendEvent(this.projectId,"sync",{branch:e.branch,uncommitted:e.hasChanges,fileCount:t.fileCount,commitCount:e.commits})}async recordSyncMetrics(e,t,n,s){let i=0;for(let m of t)try{let p=oi.join(this.globalPath,m),g=await ri.readFile(p,"utf-8");i+=g.length}catch(p){B.debug("Context file not found for metrics",{file:m,error:K(p)})}for(let m of n)try{let p=oi.join(this.globalPath,"agents",`${m.name}.md`),g=await ri.readFile(p,"utf-8");i+=g.length}catch(p){B.debug("Agent file not found for metrics",{agent:m.name,error:K(p)})}let a=Math.floor(i/4),u=e.fileCount*500,d=u>0?Math.max(0,(u-a)/u):0;try{await mn.recordSync(this.projectId,{originalSize:u,filteredSize:a,duration:s,isWatch:!1,agents:n.filter(m=>m.type==="domain").map(m=>m.name)})}catch(m){B.debug("Failed to record sync metrics",{error:K(m)})}return{duration:s,originalSize:u,filteredSize:a,compressionRate:d}}async saveDraftAnalysis(e,t,n){try{let s=e.recentCommits[0]?.hash||null,o=[],i=[];try{let a=await O.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 Ft.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){B.debug("Failed to save draft analysis (non-critical)",{error:K(s)})}}async archiveStaleData(){if(this.projectId)try{let[e,t,n,s,o]=await Promise.all([He.archiveOldShipped(this.projectId).catch(()=>0),Ee.markDormantIdeas(this.projectId).catch(()=>0),ce.removeStaleCompleted(this.projectId).catch(()=>0),O.archiveStalePausedTasks(this.projectId).catch(()=>[]),Ye.capEntries(this.projectId).catch(()=>0)]),i=e+t+n+s.length+o;if(i>0){B.info("Archived stale data",{shipped:e,dormant:t,staleQueue:n,stalePaused:s.length,memoryCapped:o,total:i});let a=rt.getStats(this.projectId);B.debug("Archive stats",a)}}catch(e){B.debug("Archival failed (non-critical)",{error:K(e)})}}async autoLearnFromHistory(){if(this.projectId)try{let e=await O.getTaskHistory(this.projectId);if(e.length===0)return;let t=new wn,n=await ec.learnFromTaskHistory(this.projectId,e,t);try{let s=await _d.getFeatureOutcomes(this.projectId);s.length>0&&await ec.learnFromOutcomes(this.projectId,s,t)}catch{}n.memoriesInjected>0&&B.info("Auto-learned from task history",{patternsExtracted:n.patternsExtracted,memoriesInjected:n.memoriesInjected,patternsSkipped:n.patternsSkipped})}catch(e){B.debug("Auto-learning failed (non-critical)",{error:K(e)})}}async getCliVersion(){try{let e=oi.join(__dirname,"..","..","package.json");return JSON.parse(await ri.readFile(e,"utf-8")).version||"0.0.0"}catch(e){return B.debug("Failed to read CLI version",{error:K(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:[]}}},wr=new ii});var cn=y(()=>{"use strict";md();kd();bd();Cd();xd();Ua();Ed();Ba();Va();Ad();rm();lm();lg()});import qt from"chalk";function ug(r){return Math.ceil(r.length/LP)}function dg(r){let e=r.split(`
|
|
927
|
+
`}function Em(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:k(),skills:n.map(o=>({name:o.skill,linkedAgents:[o.agent]})),agentSkillMap:Object.fromEntries(n.map(o=>[o.agent,o.skill]))};return dt.writeFile(it.join(t,"config","skills.json"),JSON.stringify(s,null,2),"utf-8").catch(o=>{B.debug("Failed to write skills.json",{error:K(o)})}),n}async function Am(r){let e=[];try{let t=it.join(__dirname,"..","..","templates","config","skill-mappings.json"),n=await dt.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 d of u.packages)i.push({pkg:d,agent:c.name})}if(i.length===0)return e;let a=it.join(Zb.homedir(),".claude","skills");for(let{pkg:c,agent:u}of i){let d=c.split("/").pop()||c,m=it.join(a,d,"SKILL.md"),p=it.join(a,`${d}.md`),g=!1;try{await dt.access(m),g=!0}catch{try{await dt.access(p),g=!0}catch{}}if(g){e.push({name:d,agent:u,status:"skipped"});continue}try{let f=c.split("/"),S;f.length===3?S=`${f[0]}/${f[1]}@${f[2]}`:S=c;let b=await Pm.install(S);b.installed.length>0?(e.push({name:d,agent:u,status:"installed"}),B.info(`Installed skill: ${d} for agent: ${u}`)):b.errors.length>0?(e.push({name:d,agent:u,status:"error"}),B.debug(`Failed to install skill ${d}`,{errors:b.errors})):e.push({name:d,agent:u,status:"skipped"})}catch(f){e.push({name:d,agent:u,status:"error"}),B.debug(`Skill install error for ${d}`,{error:K(f)})}}}catch(t){B.debug("Skill auto-installation failed (non-critical)",{error:K(t)})}return e}var Im=w(()=>{"use strict";Jn();Ut();se();Qn();Cm();l(xm,"generateAgents");l(vm,"loadExistingAgents");l(Tm,"resolveTemplateIncludes");l(eP,"generateWorkflowAgent");l(tP,"generateDomainAgent");l(nP,"injectFeedbackSection");l(sP,"generateMinimalWorkflowAgent");l(rP,"generateMinimalDomainAgent");l(Em,"configureSkills");l(Am,"autoInstallSkills")});import Dm from"node:fs/promises";import Rm from"node:path";var zo,jm=w(()=>{"use strict";zo=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=Rm.join(this.projectPath,"package.json"),t=await Dm.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async fileExists(e){try{return await Dm.access(Rm.join(this.projectPath,e)),!0}catch{return!1}}}});import{exec as oP}from"node:child_process";import $m from"node:fs/promises";import Gc from"node:path";import{promisify as iP}from"node:util";async function Mm(r){let e={branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0};try{let{stdout:t}=await Dn("git branch --show-current",{cwd:r});e.branch=t.trim()||"main";let{stdout:n}=await Dn("git rev-list --count HEAD",{cwd:r});e.commits=parseInt(n.trim(),10)||0;let{stdout:s}=await Dn("git shortlog -sn --all | wc -l",{cwd:r});e.contributors=parseInt(s.trim(),10)||0;let{stdout:o}=await Dn("git status --porcelain",{cwd:r}),i=o.trim().split(`
|
|
928
|
+
`).filter(Boolean);e.hasChanges=i.length>0;for(let u of i){let d=u.substring(0,2),m=u.substring(3);d.startsWith("A")||d.startsWith("M ")?e.stagedFiles.push(m):d.includes("M")?e.modifiedFiles.push(m):d.startsWith("??")&&e.untrackedFiles.push(m)}let{stdout:a}=await Dn('git log --oneline -20 --pretty=format:"%h|%s|%ad" --date=short',{cwd:r});e.recentCommits=a.split(`
|
|
929
|
+
`).filter(Boolean).map(u=>{let[d,m,p]=u.split("|");return{hash:d,message:m,date:p}});let{stdout:c}=await Dn('git log --oneline --since="1 week ago" | wc -l',{cwd:r});e.weeklyCommits=parseInt(c.trim(),10)||0}catch(t){B.debug("Git analysis failed (not a git repo?)",{error:K(t)})}return e}async function Nt(r,e){try{return await $m.access(Gc.join(r,e)),!0}catch(t){return B.debug("File not found",{filename:e,error:K(t)}),!1}}async function Om(r){let e={fileCount:0,version:"0.0.0",name:Gc.basename(r),ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]};try{let{stdout:t}=await Dn('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){B.debug("File count failed",{path:r,error:K(t)}),e.fileCount=0}try{let t=Gc.join(r,"package.json"),n=JSON.parse(await $m.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 Nt(r,"tsconfig.json")?e.languages.push("TypeScript"):e.languages.push("JavaScript")}catch(t){B.debug("No package.json found",{path:r,error:K(t)})}return await Nt(r,"Cargo.toml")&&(e.ecosystem="Rust",e.languages.push("Rust")),await Nt(r,"go.mod")&&(e.ecosystem="Go",e.languages.push("Go")),(await Nt(r,"requirements.txt")||await Nt(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 Fm(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 Nt(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 Nt(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 Nt(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 Nt(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 Nt(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 _m(r,e){let t=In(),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 Nm(r){return new zo(r).detect()}var Dn,Lm=w(()=>{"use strict";Ut();Ec();Qn();jm();Dn=iP(oP);l(Mm,"analyzeGit");l(Nt,"fileExists");l(Om,"gatherStats");l(Fm,"detectCommands");l(_m,"buildSources");l(Nm,"detectStack")});import{exec as aP}from"node:child_process";import Wc from"node:fs/promises";import Go from"node:path";import{promisify as cP}from"node:util";var lP,Bc,Vc,Um,Hm=w(()=>{"use strict";Mt();O();lP=cP(aP),Bc={async contextFilesExist(r){let e=Date.now(),t=["context/CLAUDE.md"],n=[];for(let s of t){let o=Go.join(r,s);try{await Wc.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=[],n=Go.basename(r);try{await F.read(n)}catch(s){C(s)||t.push(`state: ${y(s)}`)}return{name:"State data valid",passed:t.length===0,output:t.length===0?"1 store validated":void 0,error:t.length>0?t.join("; "):void 0,durationMs:Date.now()-e}},async noSensitiveData(r){let e=Date.now(),t=Go.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 Wc.readdir(t);for(let i of o){if(!i.endsWith(".md"))continue;let a=await Wc.readFile(Go.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(!C(o))return{name:"No sensitive data",passed:!1,error:`Could not scan: ${y(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}}},Vc=class{static{l(this,"SyncVerifier")}async verify(e,t,n){let s=Date.now(),o=[],i=n?.failFast??!1,a=0,c=[Bc.contextFilesExist(t),Bc.jsonFilesValid(t),Bc.noSensitiveData(t)];for(let p of c){let g=await p;if(o.push(g),!g.passed&&i){a=n?.checks?.filter(f=>f.enabled!==!1).length??0;break}}if((!i||o.every(p=>p.passed))&&n?.checks)for(let p of n.checks){if(p.enabled===!1){a++;continue}let g=await this.runCustomCheck(p,e);if(o.push(g),!g.passed&&i){let f=n.checks.slice(n.checks.indexOf(p)+1);a+=f.filter(S=>S.enabled!==!1).length;break}}let d=o.filter(p=>!p.passed).length,m=o.filter(p=>p.passed).length;return{passed:d===0,checks:o,totalMs:Date.now()-s,failedCount:d,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 lP(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}}}},Um=new Vc});import Wo from"node:fs/promises";import Bo from"node:path";var Vo,ar,zm=w(()=>{"use strict";Hn();Jp();em();sm();am();Cc();Ut();mn();nt();ue();uo();Xt();le();Hs();po();go();Gs();Ws();Vs();mm();se();Qn();La();Ua();fm();fa();Im();Lm();Hm();Vo=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 Ho(e)).filter(i=>!rr.includes(i));s=[...rr,...o]}else t.aiTools[0]==="auto"?(s=await Ho(e),s.length===0&&(s=["claude"])):t.aiTools[0]==="all"?s=await um("all",e):s=t.aiTools;try{if(this.projectId=await R.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=E.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await this.ensureDirectories(),await zs(this.projectId);try{let U=await mo(this.projectId);U>0&&B.info("Swept legacy JSON files into SQLite",{swept:U})}catch(U){B.debug("Legacy JSON sweep failed (non-critical)",{error:K(U)})}let[i,a,c,u]=await Promise.all([Mm(this.projectPath),Om(this.projectPath),Fm(this.projectPath),Nm(this.projectPath)]),d=t.full===!0,m,p=!0,g=!0,f=new Set;if(!d&&nm(this.projectId))try{let{diff:U,currentHashes:jg}=await Tc(this.projectPath,this.projectId),fl=U.added.length+U.modified.length+U.deleted.length;if(fl===0&&!t.changedFiles?.length)p=!1,g=!1,m={isIncremental:!0,filesChanged:0,filesUnchanged:U.unchanged.length,indexesRebuilt:!1,agentsRegenerated:!1,affectedDomains:[]};else{let ui=Qp(U,this.projectId);f=Zp(ui.allAffected);let $g=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);p=ui.allAffected.some(on=>{let Mg=on.substring(on.lastIndexOf("."));return $g.has(Mg)}),g=ui.directlyChanged.some(on=>on==="package.json"||on==="tsconfig.json"||on.includes("Dockerfile")||on.includes("docker-compose")),m={isIncremental:!0,filesChanged:fl,filesUnchanged:U.unchanged.length,indexesRebuilt:p,agentsRegenerated:g,affectedDomains:Array.from(f)}}vc(this.projectId,jg)}catch(U){B.debug("Incremental detection failed, falling back to full sync",{error:K(U)})}else try{let{currentHashes:U}=await Tc(this.projectPath,this.projectId);vc(this.projectId,U)}catch(U){B.debug("Hash computation failed (non-critical)",{error:K(U)})}if(p)try{await Promise.all([Vp(this.projectPath,this.projectId),Xp(this.projectPath,this.projectId),im(this.projectPath,this.projectId)])}catch(U){B.debug("File ranking index build failed (non-critical)",{error:K(U)})}let S;if(g)try{let U=await F.getAggregatedFeedback(this.projectId);(U.patternsDiscovered.length>0||U.knownGotchas.length>0||U.agentAccuracy.length>0)&&(S=U)}catch{}let b=g?await xm(this.globalPath,u,a,S):await vm(this.globalPath),D=Em(b,this.projectId,this.globalPath),j=g?await Am(b):[],q=_m(a,c),Re=[],Be={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:b.filter(U=>U.type==="workflow").map(U=>U.name),domain:b.filter(U=>U.type==="domain").map(U=>U.name)},sources:q},gt=await dm(Be,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 P=Date.now()-n,A=await this.recordSyncMetrics(a,Re,b,P);await this.archiveStaleData(),await this.autoLearnFromHistory(),await Le.installGlobalConfig(),await Le.syncCommands();let Se;try{let U=await R.readConfig(this.projectPath);Se=await Um.verify(this.projectPath,this.globalPath,U?.verification)}catch(U){B.debug("Verification failed (non-critical)",{error:K(U)})}return{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:i,stats:a,commands:c,stack:u,agents:b,skills:D,skillsInstalled:j,contextFiles:Re,aiTools:gt.map(U=>({toolId:U.toolId,outputFile:U.outputFile,success:U.success})),syncMetrics:A,verification:Se,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:K(o)}}}async ensureDirectories(){let e=["storage","context","agents","memory","analysis","config","sync"];await Promise.all(e.map(t=>Wo.mkdir(Bo.join(this.globalPath,t),{recursive:!0})))}async updateProjectJson(e,t){let n=$.getDoc(this.projectId,"project")||{},s={...n,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:n.createdAt||k(),lastSync:k(),lastSyncCommit:e.recentCommits[0]?.hash||null,lastSyncBranch:e.branch};$.setDoc(this.projectId,"project",s)}async updateStateJson(e,t){let s={...await F.read(this.projectId)};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=k(),s.lastUpdated=k(),s.context={...s.context||{},lastSession:k(),lastAction:"Synced project",nextAction:'Run `p. task "description"` to start working'},await F.write(this.projectId,s);try{await gm.generate(this.projectPath,s)}catch(o){B.debug("Local state generation failed (optional)",{error:K(o)})}}async logToMemory(e,t){$.appendEvent(this.projectId,"sync",{branch:e.branch,uncommitted:e.hasChanges,fileCount:t.fileCount,commitCount:e.commits})}async recordSyncMetrics(e,t,n,s){let i=0;for(let m of t)try{let p=Bo.join(this.globalPath,m),g=await Wo.readFile(p,"utf-8");i+=g.length}catch(p){B.debug("Context file not found for metrics",{file:m,error:K(p)})}for(let m of n)try{let p=Bo.join(this.globalPath,"agents",`${m.name}.md`),g=await Wo.readFile(p,"utf-8");i+=g.length}catch(p){B.debug("Agent file not found for metrics",{agent:m.name,error:K(p)})}let a=Math.floor(i/4),u=e.fileCount*500,d=u>0?Math.max(0,(u-a)/u):0;try{await wn.recordSync(this.projectId,{originalSize:u,filteredSize:a,duration:s,isWatch:!1,agents:n.filter(m=>m.type==="domain").map(m=>m.name)})}catch(m){B.debug("Failed to record sync metrics",{error:K(m)})}return{duration:s,originalSize:u,filteredSize:a,compressionRate:d}}async saveDraftAnalysis(e,t,n){try{let s=e.recentCommits[0]?.hash||null,o=[],i=[];try{let a=await F.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 $t.saveDraft(this.projectId,{projectId:this.projectId,languages:t.languages,frameworks:t.frameworks,configFiles:[],fileCount:t.fileCount,patterns:o,antiPatterns:i,analyzedAt:k(),status:"draft",commitHash:s??void 0})}catch(s){B.debug("Failed to save draft analysis (non-critical)",{error:K(s)})}}async archiveStaleData(){if(this.projectId)try{let[e,t,n,s,o]=await Promise.all([qe.archiveOldShipped(this.projectId).catch(()=>0),Me.markDormantIdeas(this.projectId).catch(()=>0),pe.removeStaleCompleted(this.projectId).catch(()=>0),F.archiveStalePausedTasks(this.projectId).catch(()=>[]),Je.capEntries(this.projectId).catch(()=>0)]),i=e+t+n+s.length+o;if(i>0){B.info("Archived stale data",{shipped:e,dormant:t,staleQueue:n,stalePaused:s.length,memoryCapped:o,total:i});let a=st.getStats(this.projectId);B.debug("Archive stats",a)}}catch(e){B.debug("Archival failed (non-critical)",{error:K(e)})}}async autoLearnFromHistory(){if(this.projectId)try{let e=await F.getTaskHistory(this.projectId);if(e.length===0)return;let t=new ln,n=await Na.learnFromTaskHistory(this.projectId,e,t);try{let s=await yd.getFeatureOutcomes(this.projectId);s.length>0&&await Na.learnFromOutcomes(this.projectId,s,t)}catch{}n.memoriesInjected>0&&B.info("Auto-learned from task history",{patternsExtracted:n.patternsExtracted,memoriesInjected:n.memoriesInjected,patternsSkipped:n.patternsSkipped})}catch(e){B.debug("Auto-learning failed (non-critical)",{error:K(e)})}}async getCliVersion(){try{let e=Bo.join(__dirname,"..","..","package.json");return JSON.parse(await Wo.readFile(e,"utf-8")).version||"0.0.0"}catch(e){return B.debug("Failed to read CLI version",{error:K(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:[]}}},ar=new Vo});var nn=w(()=>{"use strict";_u();Wu();Bu();Ku();Xu();aa();ed();fa();td();nd();Np();Gp();zm()});import Gt from"chalk";function Gm(r){return Math.ceil(r.length/uP)}function Wm(r){let e=r.split(`
|
|
1217
930
|
`),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+=`
|
|
1218
|
-
${o}`)}return n&&(n.endLine=e.length-1,t.push(n)),t}function
|
|
1219
|
-
`).length});for(let a of n){let c=a.name.toLowerCase(),u=o.get(c);u?u.content.trim()!==a.content.trim()&&(
|
|
931
|
+
${o}`)}return n&&(n.endLine=e.length-1,t.push(n)),t}function Jc(r){return r.includes("<!-- prjct:preserve")}function Bm(r,e){let t=Wm(r),n=Wm(e),s={hasChanges:!1,added:[],modified:[],removed:[],preserved:[],tokensBefore:Gm(r),tokensAfter:Gm(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)Jc(a.content)&&s.preserved.push({name:a.name,lineCount:a.content.split(`
|
|
932
|
+
`).length});for(let a of n){let c=a.name.toLowerCase(),u=o.get(c);u?u.content.trim()!==a.content.trim()&&(Jc(u.content)||(s.modified.push({name:a.name,type:"modified",before:u.content,after:a.content,lineCount:a.content.split(`
|
|
1220
933
|
`).length}),s.hasChanges=!0)):(s.added.push({name:a.name,type:"added",after:a.content,lineCount:a.content.split(`
|
|
1221
|
-
`).length}),s.hasChanges=!0)}for(let a of t){let c=a.name.toLowerCase();!i.has(c)&&!
|
|
1222
|
-
`).length}),s.hasChanges=!0)}return s}function
|
|
934
|
+
`).length}),s.hasChanges=!0)}for(let a of t){let c=a.name.toLowerCase();!i.has(c)&&!Jc(a.content)&&(s.removed.push({name:a.name,type:"removed",before:a.content,lineCount:a.content.split(`
|
|
935
|
+
`).length}),s.hasChanges=!0)}return s}function Vm(r,e={}){let{colorize:t=!0}=e,n=[],s=t?Gt.green:p=>p,o=t?Gt.red:p=>p,i=t?Gt.yellow:p=>p,a=t?Gt.dim:p=>p,c=t?Gt.bold:p=>p;if(!r.hasChanges)return n.push(a("No changes detected (context is up to date)")),n.join(`
|
|
1223
936
|
`);if(n.push(""),n.push(c("\u{1F4CB} Changes to context files:")),n.push(""),r.added.length>0)for(let p of r.added)n.push(s(`+ \u2502 + ${p.name} (new)`));if(r.modified.length>0)for(let p of r.modified)n.push(i(`~ \u2502 ${p.name} (modified)`));if(r.removed.length>0)for(let p of r.removed)n.push(o(`- \u2502 - ${p.name} (removed)`));if(r.preserved.length>0){n.push(""),n.push(a(" ## Your Customizations"));for(let p of r.preserved)n.push(a(` \u2502 \u2713 ${p.name} (${p.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 d=r.tokenDelta>=0?"+":"",m=r.tokenDelta>=0?s:o;return n.push(`Tokens: ${r.tokensBefore.toLocaleString()} \u2192 ${r.tokensAfter.toLocaleString()} (${m(d+r.tokenDelta.toLocaleString())})`),n.push(""),n.join(`
|
|
1224
|
-
`)}function
|
|
937
|
+
`)}function Jm(r,e={}){let{colorize:t=!0}=e,n=[],s=t?Gt.green:c=>c,o=t?Gt.red:c=>c,i=t?Gt.cyan:c=>c,a=t?Gt.dim:c=>c;for(let c of r.added){if(n.push(i(`@@ +${c.name} @@`)),c.after)for(let u of c.after.split(`
|
|
1225
938
|
`))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(`
|
|
1226
939
|
`).slice(0,5))n.push(o(`- ${u}`));c.before.split(`
|
|
1227
940
|
`).length>5&&n.push(a(` ... ${c.before.split(`
|
|
@@ -1232,11 +945,11 @@ ${o}`)}return n&&(n.endLine=e.length-1,t.push(n)),t}function ll(r){return r.incl
|
|
|
1232
945
|
`).slice(0,5))n.push(o(`- ${u}`));c.before.split(`
|
|
1233
946
|
`).length>5&&n.push(a(` ... ${c.before.split(`
|
|
1234
947
|
`).length-5} more lines`))}n.push("")}return n.join(`
|
|
1235
|
-
`)}var
|
|
1236
|
-
`));let u=[];r.contextFiles.length>0&&u.push(`${r.contextFiles.length} context files`);let d=r.aiTools?.filter(p=>p.success)||[];if(d.length>0&&u.push(`AI tools: ${d.map(p=>p.toolId).join(", ")}`),s>0){let p=o>0?`${s} agents (${o} domain)`:`${s} agents`;u.push(p)}if(r.skills.length>0){let p=r.skills.length===1?"skill":"skills";u.push(`${r.skills.length} ${p}`)}let m=r.skillsInstalled?.filter(p=>p.status==="installed")||[];if(m.length>0){let p=m.length===1?"skill":"skills";u.push(`${m.length} ${p} 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 p=r.verification;if(p.passed){let g=p.checks.map(f=>`${f.name} (${f.durationMs}ms)`);h.section("Verified"),h.list(g,{bullet:"\u2713"})}else{h.section("Verification");let g=p.checks.map(f=>f.passed?`\u2713 ${f.name}`:`\u2717 ${f.name}${f.error?` \u2014 ${f.error}`:""}`);h.list(g),p.skippedCount>0&&h.warn(`${p.skippedCount} check(s) skipped (fail-fast)`)}console.log("")}return
|
|
1237
|
-
`)}function
|
|
948
|
+
`)}var uP,qm=w(()=>{"use strict";uP=4;l(Gm,"estimateTokens");l(Wm,"parseMarkdownSections");l(Jc,"isPreservedSection");l(Bm,"generateSyncDiff");l(Vm,"formatDiffPreview");l(Jm,"formatFullDiff")});import dP from"node:path";async function qc(r,e){let t=Date.now()-e,n=r.contextFiles.length+(r.aiTools?.filter(p=>p.success).length||0),s=r.agents.length,o=r.agents.filter(p=>p.type==="domain").length;await Le.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(`
|
|
949
|
+
`));let u=[];r.contextFiles.length>0&&u.push(`${r.contextFiles.length} context files`);let d=r.aiTools?.filter(p=>p.success)||[];if(d.length>0&&u.push(`AI tools: ${d.map(p=>p.toolId).join(", ")}`),s>0){let p=o>0?`${s} agents (${o} domain)`:`${s} agents`;u.push(p)}if(r.skills.length>0){let p=r.skills.length===1?"skill":"skills";u.push(`${r.skills.length} ${p}`)}let m=r.skillsInstalled?.filter(p=>p.status==="installed")||[];if(m.length>0){let p=m.length===1?"skill":"skills";u.push(`${m.length} ${p} 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 p=r.verification;if(p.passed){let g=p.checks.map(f=>`${f.name} (${f.durationMs}ms)`);h.section("Verified"),h.list(g,{bullet:"\u2713"})}else{h.section("Verification");let g=p.checks.map(f=>f.passed?`\u2713 ${f.name}`:`\u2717 ${f.name}${f.error?` \u2014 ${f.error}`:""}`);h.list(g),p.skippedCount>0&&h.warn(`${p.skippedCount} check(s) skipped (fail-fast)`)}console.log("")}return ot("sync"),{success:!0,data:r,metrics:{elapsed:t,contextFilesCount:n,agentCount:s,fileCount:r.stats.fileCount}}}async function Km(r){try{let e=await Je.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(d=>new Date(d.timestamp||d.ts).getTime()).filter(d=>!Number.isNaN(d)).sort((d,m)=>d-m);if(u.length>=2){let d=u[u.length-1]-u[0];s=H.formatDuration(d)}}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 d of u.subagents)a.set(d,(a.get(d)||0)+1);let c=Array.from(a.entries()).map(([u,d])=>({name:u,count:d})).sort((u,d)=>d.count-u.count);return{sessionDuration:s,tasksCompleted:o,featuresShipped:i,agentsUsed:c}}catch{return{sessionDuration:null,tasksCompleted:0,featuresShipped:0,agentsUsed:[]}}}function cr(r){return r>=1e6?`${(r/1e6).toFixed(1)}M`:r>=1e3?`${(r/1e3).toFixed(1)}K`:r.toLocaleString()}function Kc(r){return r<1e3?`${Math.round(r)}ms`:`${(r/1e3).toFixed(1)}s`}function Ym(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 Xm(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 | ${cr(r.totalTokensSaved)} tokens |`),i.push(`| Compression | ${(r.compressionRate*100).toFixed(0)}% |`),i.push(`| Cost saved | ${Mr(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 | ${Kc(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: ${cr(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(`
|
|
950
|
+
`)}function Qm(r,e){let t=[];t.push(`# Repository Analysis
|
|
1238
951
|
`),t.push(`Generated: ${new Date().toLocaleString()}
|
|
1239
|
-
`);let n=
|
|
952
|
+
`);let n=dP.basename(e);if(t.push(`## Project: ${n}
|
|
1240
953
|
`),t.push(`## Stack Detected
|
|
1241
954
|
`),r.packageJson){let i=r.packageJson;if(t.push(`### JavaScript/TypeScript
|
|
1242
955
|
`),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
|
|
@@ -1252,34 +965,34 @@ ${o}`)}return n&&(n.endLine=e.length-1,t.push(n)),t}function ll(r){return r.incl
|
|
|
1252
965
|
`).slice(0,5).forEach(a=>{if(a.trim()){let[c,,u,d]=a.split("|");t.push(`- \`${c}\` ${d} (${u})`)}}),t.push("")),t.push(`## Recommendations
|
|
1253
966
|
`),t.push("Based on detected stack, consider generating specialized agents using `/p:sync`.\n"),t.push(`---
|
|
1254
967
|
`),t.push("*This analysis was generated automatically. For updated information, run `/p:analyze` again.*\n"),t.join(`
|
|
1255
|
-
`)}var
|
|
1256
|
-
`),
|
|
968
|
+
`)}var Zm=w(()=>{"use strict";mn();Or();nn();es();yn();He();l(qc,"showSyncResult");l(Km,"getSessionActivity");l(cr,"formatTokens");l(Kc,"formatDuration");l(Ym,"generateSparkline");l(Xm,"generateStatsMarkdown");l(Qm,"generateAnalysisSummary")});var _p={};Mn(_p,{AnalysisCommands:()=>Rn});import Yc from"node:fs/promises";import eg from"node:path";import tg from"prompts";var Rn,Oo=w(()=>{"use strict";Hn();vu();mn();Or();nn();qm();uo();le();po();O();Zn();es();yn();Zm();He();Rn=class extends ae{static{l(this,"AnalysisCommands")}async analyze(e={},t=process.cwd()){try{await this.initializeAgent(),console.log(`\u{1F50D} Analyzing repository...
|
|
969
|
+
`),Ie.init(t);let n=await Ye.build(t,e),s={packageJson:await Ie.readPackageJson(),cargoToml:await Ie.readCargoToml(),goMod:await Ie.readGoMod(),requirements:await Ie.readRequirements(),directories:await Ie.listDirectories(),fileCount:await Ie.countFiles(),gitStats:await Ie.getGitStats(),gitLog:await Ie.getGitLog(20),hasDockerfile:await Ie.fileExists("Dockerfile"),hasDockerCompose:await Ie.fileExists("docker-compose.yml"),hasReadme:await Ie.fileExists("README.md"),hasTsconfig:await Ie.fileExists("tsconfig.json"),hasViteConfig:await Ie.fileExists("vite.config.ts")||await Ie.fileExists("vite.config.js"),hasNextConfig:await Ie.fileExists("next.config.js")||await Ie.fileExists("next.config.mjs")},o=Qm(s,t),i=await R.getProjectId(t),a=n.paths.analysis||E.getFilePath(i,"analysis","repo-summary.md");await De.get("Write")(a,o),await this.logToMemory(t,"repository_analyzed",{timestamp:H.getTimestamp(),fileCount:s.fileCount,gitCommits:s.gitStats.totalCommits});let u=await(Ve(),at(et)).getActiveProvider(),d=await Le.installGlobalConfig();return d.success&&console.log(`\u{1F4DD} Updated ${E.getDisplayPath(d.path)}`),console.log(`\u2705 Analysis complete!
|
|
1257
970
|
`),console.log("\u{1F4C4} Full report: analysis/repo-summary.md"),console.log(`\u{1F4DD} Context: ~/.prjct-cli/projects/${i}/${u.contextFile}
|
|
1258
|
-
`),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:",
|
|
1259
|
-
${gg(g)}`),!(await Pg({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"),ul(m,i))}t.md||h.spin("Syncing project...");let d=await wr.sync(e,{aiTools:t.aiTools,full:t.full});if(!d.success)return t.md?console.log(me("## Sync Failed",`> ${d.error||"Unknown error"}`)):h.fail(d.error||"Sync failed"),{success:!1,error:d.error};if(t.md||h.stop(),t.md){let m=Date.now()-i,p=d.contextFiles.length+(d.aiTools?.filter(k=>k.success).length||0),g=d.agents.length,f=Eo("sync"),S=me(_t("Sync Complete",Et({Duration:`${(m/1e3).toFixed(1)}s`,Agents:`${g} generated`,"Files indexed":d.stats.fileCount,"Context files":p})),d.git.hasChanges?rn("Uncommitted changes detected"):null,_e(f.map(k=>({label:k.desc,command:k.cmd}))));return console.log(S),{success:!0,data:d,metrics:{elapsed:m,contextFilesCount:p,agentCount:g,fileCount:d.stats.fileCount}}}return ul(d,i)}catch(n){return t.md?console.log(me("## Sync Failed",`> ${w(n)}`)):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 R.getProjectId(e);if(!s)return{success:!1,error:"No project ID found"};let o=await mn.getSummary(s),i=await mn.getDailyStats(s,30),a=await hg(s),c=await pe.getPatternsSummary(s);if(t.json){let p={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(p,null,2)),{success:!0,data:p}}let u="Unknown";try{u=M.getDoc(s,"project")?.name||"Unknown"}catch{}let d=await mn.read(s),m=d.firstSync?new Date(d.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: ${u.padEnd(20).slice(0,20)} | Since: ${m.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 p=a.agentsUsed.slice(0,3).map(g=>`${g.name} (${g.count}\xD7)`).join(", ");console.log(` Agents used: ${p}`)}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: ${Sr(o.totalTokensSaved)} tokens`),console.log(` Compression: ${(o.compressionRate*100).toFixed(0)}% average reduction`),console.log(` Estimated cost: ${Qn(o.estimatedCostSaved)} saved`),console.log(""),console.log("\u26A1 PERFORMANCE"),console.log(` Syncs completed: ${o.syncCount.toLocaleString()}`),console.log(` Avg sync time: ${dl(o.avgSyncDuration)}`),console.log(""),o.topAgents.length>0){console.log("\u{1F916} AGENT USAGE (all time)");let p=o.topAgents.reduce((g,f)=>g+f.usageCount,0);for(let g of o.topAgents){let f=p>0?(g.usageCount/p*100).toFixed(0):0;console.log(` ${g.agentName.padEnd(12)}: ${f}% (${g.usageCount} uses)`)}console.log("")}if(i.length>0){console.log("\u{1F4C8} TREND (last 30 days)");let p=yg(i);if(console.log(` ${p} ${Sr(o.last30DaysTokens)} tokens saved`),o.trend!==0){let g=o.trend>0?"\u2191":"\u2193",f=o.trend>0?"+":"";console.log(` ${g} ${f}${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 p=wg(o,i,u,m,a,c);return console.log(p),{success:!0,data:{markdown:p}}}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 R.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=pr(e),i=await o.check(s),a=await o.getSessionInfo(s),c=await Ft.getStatus(s);if(t.json)return console.log(JSON.stringify({success:!0,...i,session:a,analysis:c})),{success:!0,data:{...i,session:a,analysis:c}};if(t.md){let u=bg.basename(e),d=i.isStale?"stale":"fresh",m=i.daysSinceSync>0?`${i.daysSinceSync} day${i.daysSinceSync!==1?"s":""} ago`:"today",p=[];c.hasSealed&&p.push(`Sealed: ${c.sealedCommit} (${c.sealedAt})`),c.hasDraft&&p.push(`Draft: ${c.draftCommit} (pending seal)`);let g=me(`## Status: ${u}`,Et({Staleness:d,"Last sync":m,"Commits since sync":i.commitsSinceSync,Reason:i.reason}),p.length>0?ze("Analysis",Tt(p),3):null);return console.log(g),{success:!0,data:{...i,session:a,analysis:c}}}return 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 R.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 Ft.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 R.getProjectId(e);if(!s)return{success:!1,error:"No project ID found"};let o=await Ft.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 R.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=e;try{o=M.getDoc(s,"project")?.repoPath||e}catch{}let i=await Ft.semanticVerify(s,o);if(t.json)return console.log(JSON.stringify(i)),{success:i.passed,data:i};console.log(""),i.passed?(h.done("Semantic verification passed"),console.log(` ${i.passedCount}/${i.checks.length} checks passed (${i.totalMs}ms)`)):(h.fail("Semantic verification failed"),console.log(` ${i.failedCount}/${i.checks.length} checks failed`)),console.log(""),console.log("Check Results:");for(let a of i.checks){let c=a.passed?"\u2713":"\u2717",u=a.passed?`${a.output} (${a.durationMs}ms)`:a.error||"Failed";console.log(` ${c} ${a.name}: ${u}`)}return console.log(""),{success:i.passed,data:i}}catch(n){let s=w(n);return t.json?console.log(JSON.stringify({success:!1,error:s})):h.fail(s),{success:!1,error:s}}}}});import{exec as nC}from"node:child_process";import{promisify as sC}from"node:util";async function gi(r){if(process.platform!=="darwin")return $g(r);try{let{stdout:e}=await rC(`security find-generic-password -s "${oC}" -a "${r}" -w 2>/dev/null`);return e.trim()||null}catch{return $g(r)}}function $g(r){let t={"linear-api-key":"LINEAR_API_KEY","jira-api-token":"JIRA_API_TOKEN"}[r];return process.env[t]||null}var rC,oC,xl=y(()=>{"use strict";F();rC=sC(nC),oC="prjct-cli";l(gi,"getCredential");l($g,"getEnvFallback")});import ft from"node:fs";import{createServer as BC}from"node:net";Ei();Jo();cn();Ct();F();ps();We();import HP from"node:path";it();re();F();te();var ai=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 R.getProjectId(e);if(!t)throw new Error("No prjct project found. Run /p:init first.");return{projectId:t,projectPath:e,globalPath:T.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()}},U=new ai;var hs=class extends le{static{l(this,"AnalyticsCommands")}async dash(e="default",t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;let o=await R.getProjectId(t);if(!o)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let i=HP.basename(t),a=await O.getCurrentTask(o),c=await ce.getActiveTasks(o),u=await He.getRecent(o,5),d=await Ee.getPending(o);if(e==="compact"){let m=a?`\u{1F3AF} ${a.description.slice(0,30)}`:"\u{1F4A4} idle",p=`\u{1F4CB} ${c.length}`,g=`\u{1F680} ${u.length}`;return h.done(`${m} | ${p} | ${g}`),{success:!0,view:"compact"}}if(e==="week"||e==="month"){let m=e==="week"?7:30,p=L.getDaysAgo(m),g=[];try{let k=p.toISOString();g=M.query(o,"SELECT data, timestamp FROM events WHERE type LIKE ? AND timestamp >= ? ORDER BY id DESC","memory.%",k).map(D=>({...JSON.parse(D.data),timestamp:D.timestamp}))}catch{g=[]}let f={tasksCompleted:g.filter(k=>k.action==="task_completed").length,featuresShipped:g.filter(k=>k.action==="feature_shipped").length,totalActions:g.length};console.log(`
|
|
971
|
+
`),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:",y(n)),{success:!1,error:y(n)}}}async sync(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await R.getProjectId(e);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=E.getGlobalProjectPath(s),i=Date.now();if(t.package){let m=await E.detectMonorepo(e);if(!m.isMonorepo)return{success:!1,error:"Not a monorepo. --package flag only works in monorepos."};let p=m.packages.find(f=>f.name===t.package||f.relativePath===t.package);if(!p){let f=m.packages.map(S=>S.name).join(", ");return{success:!1,error:`Package "${t.package}" not found. Available: ${f}`}}let g=await ar.sync(e,{aiTools:t.aiTools,packagePath:p.path,packageName:p.name});return t.json?console.log(JSON.stringify({success:g.success,package:p.name,path:p.relativePath})):t.md?console.log(Ot(`Synced package: ${p.name}`)):h.done(`Synced package: ${p.name}`),{success:g.success}}let a=eg.join(o,"context","CLAUDE.md"),c=null;try{c=await Yc.readFile(a,"utf-8")}catch{}let u=!process.stdin.isTTY||t.json||t.md;if(c&&!t.yes){u||h.spin("Analyzing changes...");let m=await ar.sync(e,{aiTools:t.aiTools,full:t.full});if(!m.success)return t.md?(console.log(me("## Sync Failed",`> ${m.error||"Unknown error"}`)),{success:!1,error:m.error}):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 p;try{p=await Yc.readFile(a,"utf-8")}catch{p=""}let g=Bm(c,p);if(u||h.stop(),!g.hasChanges)return t.md?(console.log(Ot("No changes detected","Context is up to date.")),{success:!0,message:"No changes"}):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 Yc.writeFile(a,c,"utf-8")},"restoreOriginal");if(t.md){await f();let b=[];for(let j of g.added)b.push(`Added: ${j.name} (${j.lineCount} lines)`);for(let j of g.modified)b.push(`Modified: ${j.name} (${j.lineCount} lines)`);for(let j of g.removed)b.push(`Removed: ${j.name} (${j.lineCount} lines)`);let D=me("## Sync Preview",b.length>0?Ue("Changes",Ct(b),3):"No section changes.",xt({"Tokens before":g.tokensBefore,"Tokens after":g.tokensAfter,"Token delta":g.tokenDelta>0?`+${g.tokenDelta}`:String(g.tokenDelta)}),"> Run `prjct sync --yes` to apply changes.");return console.log(D),{success:!0,isPreview:!0,diff:g,message:"Preview complete (awaiting confirmation)"}}if(u){await f();let b={added:g.added.map(D=>({name:D.name,lineCount:D.lineCount})),modified:g.modified.map(D=>({name:D.name,lineCount:D.lineCount})),removed:g.removed.map(D=>({name:D.name,lineCount:D.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:b,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(Vm(g)),t.preview)return await f(),{success:!0,isPreview:!0,diff:g,message:"Preview complete (no changes applied)"};let S=await tg({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(`
|
|
972
|
+
${Jm(g)}`),!(await tg({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"),qc(m,i))}t.md||h.spin("Syncing project...");let d=await ar.sync(e,{aiTools:t.aiTools,full:t.full});if(!d.success)return t.md?console.log(me("## Sync Failed",`> ${d.error||"Unknown error"}`)):h.fail(d.error||"Sync failed"),{success:!1,error:d.error};if(t.md||h.stop(),t.md){let m=Date.now()-i,p=d.contextFiles.length+(d.aiTools?.filter(b=>b.success).length||0),g=d.agents.length,f=fo("sync"),S=me(Ot("Sync Complete",xt({Duration:`${(m/1e3).toFixed(1)}s`,Agents:`${g} generated`,"Files indexed":d.stats.fileCount,"Context files":p})),d.git.hasChanges?Zt("Uncommitted changes detected"):null,Oe(f.map(b=>({label:b.desc,command:b.cmd}))));return console.log(S),{success:!0,data:d,metrics:{elapsed:m,contextFilesCount:p,agentCount:g,fileCount:d.stats.fileCount}}}return qc(d,i)}catch(n){return t.md?console.log(me("## Sync Failed",`> ${y(n)}`)):h.fail(y(n)),{success:!1,error:y(n)}}}async stats(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await R.getProjectId(e);if(!s)return{success:!1,error:"No project ID found"};let o=await wn.getSummary(s),i=await wn.getDailyStats(s,30),a=await Km(s),c=await de.getPatternsSummary(s);if(t.json){let p={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(p,null,2)),{success:!0,data:p}}let u="Unknown";try{u=$.getDoc(s,"project")?.name||"Unknown"}catch{}let d=await wn.read(s),m=d.firstSync?new Date(d.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: ${u.padEnd(20).slice(0,20)} | Since: ${m.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 p=a.agentsUsed.slice(0,3).map(g=>`${g.name} (${g.count}\xD7)`).join(", ");console.log(` Agents used: ${p}`)}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: ${cr(o.totalTokensSaved)} tokens`),console.log(` Compression: ${(o.compressionRate*100).toFixed(0)}% average reduction`),console.log(` Estimated cost: ${Mr(o.estimatedCostSaved)} saved`),console.log(""),console.log("\u26A1 PERFORMANCE"),console.log(` Syncs completed: ${o.syncCount.toLocaleString()}`),console.log(` Avg sync time: ${Kc(o.avgSyncDuration)}`),console.log(""),o.topAgents.length>0){console.log("\u{1F916} AGENT USAGE (all time)");let p=o.topAgents.reduce((g,f)=>g+f.usageCount,0);for(let g of o.topAgents){let f=p>0?(g.usageCount/p*100).toFixed(0):0;console.log(` ${g.agentName.padEnd(12)}: ${f}% (${g.usageCount} uses)`)}console.log("")}if(i.length>0){console.log("\u{1F4C8} TREND (last 30 days)");let p=Ym(i);if(console.log(` ${p} ${cr(o.last30DaysTokens)} tokens saved`),o.trend!==0){let g=o.trend>0?"\u2191":"\u2193",f=o.trend>0?"+":"";console.log(` ${g} ${f}${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 p=Xm(o,i,u,m,a,c);return console.log(p),{success:!0,data:{markdown:p}}}return{success:!0,data:{...o,session:a,patterns:c}}}catch(n){return console.error("\u274C Error:",y(n)),{success:!1,error:y(n)}}}async status(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await R.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=tr(e),i=await o.check(s),a=await o.getSessionInfo(s),c=await $t.getStatus(s);if(t.json)return console.log(JSON.stringify({success:!0,...i,session:a,analysis:c})),{success:!0,data:{...i,session:a,analysis:c}};if(t.md){let u=eg.basename(e),d=i.isStale?"stale":"fresh",m=i.daysSinceSync>0?`${i.daysSinceSync} day${i.daysSinceSync!==1?"s":""} ago`:"today",p=[];c.hasSealed&&p.push(`Sealed: ${c.sealedCommit} (${c.sealedAt})`),c.hasDraft&&p.push(`Draft: ${c.draftCommit} (pending seal)`);let g=me(`## Status: ${u}`,xt({Staleness:d,"Last sync":m,"Commits since sync":i.commitsSinceSync,Reason:i.reason}),p.length>0?Ue("Analysis",Ct(p),3):null);return console.log(g),{success:!0,data:{...i,session:a,analysis:c}}}return 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=y(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 R.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 $t.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=y(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 R.getProjectId(e);if(!s)return{success:!1,error:"No project ID found"};let o=await $t.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=y(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 R.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=e;try{o=$.getDoc(s,"project")?.repoPath||e}catch{}let i=await $t.semanticVerify(s,o);if(t.json)return console.log(JSON.stringify(i)),{success:i.passed,data:i};console.log(""),i.passed?(h.done("Semantic verification passed"),console.log(` ${i.passedCount}/${i.checks.length} checks passed (${i.totalMs}ms)`)):(h.fail("Semantic verification failed"),console.log(` ${i.failedCount}/${i.checks.length} checks failed`)),console.log(""),console.log("Check Results:");for(let a of i.checks){let c=a.passed?"\u2713":"\u2717",u=a.passed?`${a.output} (${a.durationMs}ms)`:a.error||"Failed";console.log(` ${c} ${a.name}: ${u}`)}return console.log(""),{success:i.passed,data:i}}catch(n){let s=y(n);return t.json?console.log(JSON.stringify({success:!1,error:s})):h.fail(s),{success:!1,error:s}}}}});import{exec as EP}from"node:child_process";import{promisify as AP}from"node:util";async function ei(r){if(process.platform!=="darwin")return pg(r);try{let{stdout:e}=await IP(`security find-generic-password -s "${DP}" -a "${r}" -w 2>/dev/null`);return e.trim()||null}catch{return pg(r)}}function pg(r){let t={"linear-api-key":"LINEAR_API_KEY","jira-api-token":"JIRA_API_TOKEN"}[r];return process.env[t]||null}var IP,DP,ll=w(()=>{"use strict";O();IP=AP(EP),DP="prjct-cli";l(ei,"getCredential");l(pg,"getEnvFallback")});import mt from"node:fs";import{createServer as fC}from"node:net";pi();Oo();nn();Mt();O();Zn();He();import pP from"node:path";nt();ue();O();se();var Jo=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 R.getProjectId(e);if(!t)throw new Error("No prjct project found. Run /p:init first.");return{projectId:t,projectPath:e,globalPath:E.getGlobalProjectPath(t),timestamp:k()}}async execute(e,t,n=process.cwd()){let s=this.metadata.get(e),o;if(s?.requiresProject===!1)o={projectId:"",projectPath:n,globalPath:"",timestamp:k()};else try{o=await this.buildContext(n)}catch(c){return{success:!1,error:y(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:k()};return s.execute(t,i)}let o=this.handlerFns.get(e);if(o){let i={projectId:"",projectPath:n,globalPath:"",timestamp:k()};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()}},L=new Jo;var ss=class extends ae{static{l(this,"AnalyticsCommands")}async dash(e="default",t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;let o=await R.getProjectId(t);if(!o)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let i=pP.basename(t),a=await F.getCurrentTask(o),c=await pe.getActiveTasks(o),u=await qe.getRecent(o,5),d=await Me.getPending(o);if(e==="compact"){let m=a?`\u{1F3AF} ${a.description.slice(0,30)}`:"\u{1F4A4} idle",p=`\u{1F4CB} ${c.length}`,g=`\u{1F680} ${u.length}`;return h.done(`${m} | ${p} | ${g}`),{success:!0,view:"compact"}}if(e==="week"||e==="month"){let m=e==="week"?7:30,p=H.getDaysAgo(m),g=[];try{let b=p.toISOString();g=$.query(o,"SELECT data, timestamp FROM events WHERE type LIKE ? AND timestamp >= ? ORDER BY id DESC","memory.%",b).map(j=>({...JSON.parse(j.data),timestamp:j.timestamp}))}catch{g=[]}let f={tasksCompleted:g.filter(b=>b.action==="task_completed").length,featuresShipped:g.filter(b=>b.action==="feature_shipped").length,totalActions:g.length};console.log(`
|
|
1260
973
|
\u{1F4CA} ${e.toUpperCase()} PROGRESS - ${i}
|
|
1261
974
|
`),console.log("\u2550".repeat(50)),console.log(` Tasks completed: ${f.tasksCompleted}`),console.log(` Features shipped: ${f.featuresShipped}`),console.log(` Total actions: ${f.totalActions}`),console.log("\u2550".repeat(50));let S=this._generateSparkline(g,m);return console.log(`
|
|
1262
975
|
Activity: ${S}
|
|
1263
|
-
`),{success:!0,view:e,metrics:f}}if(e==="roadmap"){let m=await
|
|
976
|
+
`),{success:!0,view:e,metrics:f}}if(e==="roadmap"){let m=await Ye.build(t),p=await De.get("Read")(m.paths.roadmap);if(console.log(`
|
|
1264
977
|
\u{1F5FA}\uFE0F ROADMAP - ${i}
|
|
1265
978
|
`),console.log("\u2550".repeat(50)),!p||p.trim()==="# ROADMAP")console.log(" No features planned yet."),console.log(` Use /p:feature to add features.
|
|
1266
|
-
`);else{let g=p.split("##").filter(f=>f.trim()&&!f.includes("ROADMAP"));g.slice(0,5).forEach((f,S)=>{let
|
|
1267
|
-
`)[0].trim();console.log(` ${S+1}. ${
|
|
1268
|
-
`),{success:!0,view:"roadmap"}}if(n.md){let m=a?`${a.description}${a.startedAt?` (started ${
|
|
979
|
+
`);else{let g=p.split("##").filter(f=>f.trim()&&!f.includes("ROADMAP"));g.slice(0,5).forEach((f,S)=>{let b=f.split(`
|
|
980
|
+
`)[0].trim();console.log(` ${S+1}. ${b}`)}),g.length>5&&console.log(` ... and ${g.length-5} more`)}return console.log(`${"\u2550".repeat(50)}
|
|
981
|
+
`),{success:!0,view:"roadmap"}}if(n.md){let m=a?`${a.description}${a.startedAt?` (started ${H.calculateDuration(new Date(a.startedAt))} ago)`:""}`:"No active task",p=c.length>0?c.slice(0,5).map(S=>{let b=S.priority?` [${S.priority}]`:"";return`${S.description}${b}`}):["Queue is empty"],g=u.length>0?u.slice(0,5).map(S=>{let b=S.shippedAt?new Date(S.shippedAt).toLocaleDateString():"";return`${S.name}${b?` (${b})`:""}`}):["Nothing shipped yet"],f=me(`## Dashboard: ${i}`,Ue("Current Focus",m,3),Ue(`Queue (${c.length})`,Ct(p,!0),3),Ue("Recent Ships",Ct(g),3),Ue("Ideas",`${d.length} pending`,3),Oe([{label:"Start task",command:"p. task"},{label:"Complete",command:"p. done"},{label:"Ship",command:"p. ship"}]));console.log(f)}else{console.log(`
|
|
1269
982
|
\u{1F4CA} DASHBOARD - ${i}
|
|
1270
|
-
`),console.log("\u2550".repeat(50));let m=
|
|
983
|
+
`),console.log("\u2550".repeat(50));let m=tr(t),p=await m.check(o),g=m.getWarning(p);if(g&&console.log(`
|
|
1271
984
|
${g}`),console.log(`
|
|
1272
|
-
\u{1F3AF} CURRENT FOCUS`),a){if(console.log(` ${a.description}`),a.startedAt){let f=
|
|
1273
|
-
\u{1F4CB} QUEUE`),c.length===0?console.log(" Queue is empty"):(c.slice(0,3).forEach((f,S)=>{let
|
|
985
|
+
\u{1F3AF} CURRENT FOCUS`),a){if(console.log(` ${a.description}`),a.startedAt){let f=H.calculateDuration(new Date(a.startedAt));console.log(` Started: ${f} ago`)}}else console.log(" No active task. Use /p:work to start.");console.log(`
|
|
986
|
+
\u{1F4CB} QUEUE`),c.length===0?console.log(" Queue is empty"):(c.slice(0,3).forEach((f,S)=>{let b=f.priority?`[${f.priority}]`:"";console.log(` ${S+1}. ${f.description.slice(0,40)} ${b}`)}),c.length>3&&console.log(` ... and ${c.length-3} more`)),console.log(`
|
|
1274
987
|
\u{1F680} RECENT SHIPS`),u.length===0?console.log(" Nothing shipped yet"):u.slice(0,3).forEach(f=>{let S=f.shippedAt?new Date(f.shippedAt).toLocaleDateString():"";console.log(` \u2022 ${f.name} ${S?`(${S})`:""}`)}),console.log(`
|
|
1275
988
|
\u{1F4A1} IDEAS`),console.log(` ${d.length} pending ideas`),console.log(`
|
|
1276
989
|
${"\u2550".repeat(50)}`),console.log(`\u{1F4A1} /p:work to start | /p:done to complete | /p:ship to ship
|
|
1277
|
-
`)}return await this.logToMemory(t,"dash_viewed",{view:e,timestamp:
|
|
990
|
+
`)}return await this.logToMemory(t,"dash_viewed",{view:e,timestamp:H.getTimestamp()}),{success:!0,view:"default",stats:{currentTask:a?.description||null,queueCount:c.length,shippedCount:u.length,ideasCount:d.length}}}catch(s){return h.fail(y(s)),{success:!1,error:y(s)}}}async help(e="",t=process.cwd()){try{if(!e){console.log(`
|
|
1278
991
|
PRJCT COMMANDS
|
|
1279
|
-
`),console.log("=".repeat(50));let i=
|
|
992
|
+
`),console.log("=".repeat(50));let i=L.getAllCategories(),a=L.getAll(),c={};return a.forEach(u=>{u.deprecated||(c[u.group]||(c[u.group]=[]),c[u.group].push(u))}),Object.entries(c).forEach(([u,d])=>{let m=i.get(u);console.log(`
|
|
1280
993
|
${m?.title||u}:`),d.forEach(p=>{let g=p.params?` ${p.params}`:"";console.log(` ${p.name}${g}`),console.log(` ${p.description}`)})}),console.log(`
|
|
1281
994
|
${"\u2550".repeat(50)}`),console.log(`\u{1F4A1} Use /p:help <command> for detailed help
|
|
1282
|
-
`),{success:!0,topic:"overview"}}let n=
|
|
995
|
+
`),{success:!0,topic:"overview"}}let n=L.getByName(e);if(n){if(console.log(`
|
|
1283
996
|
\u{1F4DA} HELP: /p:${n.name}
|
|
1284
997
|
`),console.log("\u2550".repeat(50)),console.log(`Description: ${n.description}`),n.params&&console.log(`Parameters: ${n.params}`),n.usage&&(console.log(`
|
|
1285
998
|
Usage:`),n.usage.claude&&console.log(` Claude: ${n.usage.claude}`),n.usage.terminal&&console.log(` Terminal: ${n.usage.terminal}`)),n.features){console.log(`
|
|
@@ -1289,7 +1002,7 @@ ${"\u2550".repeat(50)}
|
|
|
1289
1002
|
\u{1F4A1} Did you mean /p:${a.command}?`),console.log(` ${a.hint}
|
|
1290
1003
|
`),{success:!0,topic:e,suggestion:a.command};return console.log(`
|
|
1291
1004
|
\u2753 Unknown topic: ${e}`),console.log(` Use /p:help to see all commands
|
|
1292
|
-
`),{success:!1,error:`Unknown topic: ${e}`}}catch(n){return h.fail(
|
|
1005
|
+
`),{success:!1,error:`Unknown topic: ${e}`}}catch(n){return h.fail(y(n)),{success:!1,error:y(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)),d=new Date(c.setHours(23,59,59,999)),m=e.filter(p=>{let g=new Date(p.timestamp);return g>=u&&g<=d}).length;o.push(m)}let i=Math.max(...o,1);return o.map(a=>n[Math.floor(a/i*(n.length-1))]).join("")}};sc();nt();ue();Mt();O();import mP from"node:fs/promises";import gP from"node:path";var jn=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 R.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=E.getGlobalProjectPath(a),u=await F.read(a),d=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 vo.execute(s,o,t)}catch(f){console.error(`Warning: Orchestrator failed: ${y(f)}`)}let p=await this.loadRepoAnalysis(c),g={projectId:a,globalPath:c,currentTask:d,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:p?.ecosystem||"unknown",frameworks:p?.frameworks||[],hasTests:p?.hasTests||!1,technologies:p?.technologies||[]}};return console.log(JSON.stringify(g,null,2)),{success:!0,message:""}}catch(n){return{success:!1,message:`Context error: ${y(n)}`}}}async loadRepoAnalysis(e){try{let t=gP.join(e,"analysis","repo-analysis.json"),n=await mP.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 C(t),null}}},MN=new jn;He();nn();Mt();le();O();He();async function qo(r){let e=await R.getProjectId(r),t={rotated:[],totalSize:0,freedSpace:0};if(!e)return{success:!0,results:t};let s=z.get(e,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(s>500){let o=s-500;z.run(e,"DELETE FROM events WHERE id IN (SELECT id FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?)",o),t.rotated.push("memory-events"),t.freedSpace=o}return{success:!0,results:t}}l(qo,"cleanupMemory");async function Ko(r){let e=await R.getProjectId(r);if(!e)return;let n=z.get(e,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(n>500){let s=n-500;z.run(e,"DELETE FROM events WHERE id IN (SELECT id FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?)",s)}}l(Ko,"cleanupMemoryInternal");async function Xc(r={},e=process.cwd()){try{if(r.memory===!0||r.type==="memory"){h.spin("cleaning memory...");let a=await qo(e);return h.done("memory cleaned"),a}h.spin("cleaning up...");let n=await R.getProjectId(e);if(!n)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let s=[],i=z.get(n,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(i>100){let a=i-100;z.run(n,"DELETE FROM events WHERE id IN (SELECT id FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?)",a),s.push(`Memory: ${a} old entries removed`)}else s.push("Memory: No cleanup needed");try{let a=await Me.cleanup(n);a.removed>0?s.push(`Ideas: ${a.removed} old archived ideas removed`):s.push("Ideas: No cleanup needed")}catch(a){s.push(`Ideas: Error - ${y(a)}`)}try{let c=(await pe.getActiveTasks(n)).filter(u=>u.completed).length;c>0?s.push(`Queue: ${c} completed tasks found (not removed - use /p:done to clear)`):s.push("Queue: No completed tasks")}catch(a){s.push(`Queue: Error - ${y(a)}`)}return await Ko(e),await Je.log(e,"cleanup_performed",{items:s.length,timestamp:H.getTimestamp()}),h.done(`${s.length} items cleaned`),{success:!0,cleaned:s}}catch(t){return h.fail(y(t)),{success:!1,error:y(t)}}}l(Xc,"cleanup");nn();O();He();import ng from"node:path";async function Qc(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 R.getProjectId(t),a=ng.join(E.getGlobalProjectPath(i),"planning","designs");await te.ensureDir(a);let c="";switch(n){case"architecture":c=`# Architecture Design: ${o}
|
|
1293
1006
|
|
|
1294
1007
|
*Use templates/design/architecture.md for full design*
|
|
1295
1008
|
`;break;case"api":c=`# API Design: ${o}
|
|
@@ -1304,12 +1017,12 @@ ${"\u2550".repeat(50)}
|
|
|
1304
1017
|
`;break;case"flow":c=`# Flow Design: ${o}
|
|
1305
1018
|
|
|
1306
1019
|
*Use templates/design/flow.md for full design*
|
|
1307
|
-
`;break}let u=`${n}-${o.toLowerCase().replace(/\s+/g,"-")}.md`,d=
|
|
1020
|
+
`;break}let u=`${n}-${o.toLowerCase().replace(/\s+/g,"-")}.md`,d=ng.join(a,u);return await te.writeFile(d,c),await Je.log(t,"design_created",{type:n,target:o,timestamp:H.getTimestamp()}),h.done(`${n} design created`),{success:!0,designPath:d,type:n,target:o}}catch(n){return h.fail(y(n)),{success:!1,error:y(n)}}}l(Qc,"design");nn();O();He();import rs from"node:path";async function Zc(r=process.cwd()){try{let e=await R.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=E.getFilePath(e,"progress","sessions/current.json"),n=null;try{let s=await te.readFile(t);n=JSON.parse(s)}catch(s){if(C(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(`
|
|
1308
1021
|
Found abandoned session:
|
|
1309
|
-
`),console.log(` Task: ${n.task}`),n.startedAt){let s=
|
|
1022
|
+
`),console.log(` Task: ${n.task}`),n.startedAt){let s=H.calculateDuration(new Date(n.startedAt));console.log(` Started: ${s} ago`)}return n.context&&console.log(` Context: ${n.context.slice(0,100)}...`),console.log(`
|
|
1310
1023
|
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
|
|
1311
|
-
`),{success:!0,session:n}}catch(e){return h.fail(
|
|
1312
|
-
`).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
|
|
1024
|
+
`),{success:!0,session:n}}catch(e){return h.fail(y(e)),{success:!1,error:y(e)}}}l(Zc,"recover");async function el(r=process.cwd()){try{h.spin("creating undo point...");let e=await R.getProjectId(r);if(!e)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let t=rs.join(E.getGlobalProjectPath(e),"snapshots");await te.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=rs.join(t,"history.json"),c={snapshots:[],current:-1};try{let u=await te.readFile(a);c=JSON.parse(u)}catch(u){if(!C(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 te.writeFile(a,JSON.stringify(c,null,2)),await Je.log(r,"undo_performed",{snapshotId:i,timestamp:H.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:y(s)}}}catch(e){return h.fail(y(e)),{success:!1,error:y(e)}}}l(el,"undo");async function tl(r=process.cwd()){try{h.spin("restoring changes...");let e=await R.getProjectId(r);if(!e)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let t=rs.join(E.getGlobalProjectPath(e),"snapshots"),n=rs.join(t,"history.json"),s;try{let i=await te.readFile(n);s=JSON.parse(i)}catch(i){if(C(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(`
|
|
1025
|
+
`).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 te.writeFile(n,JSON.stringify(s,null,2)),await Je.log(r,"redo_performed",{timestamp:H.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:y(i)}}}catch(e){return h.fail(y(e)),{success:!1,error:y(e)}}}l(tl,"redo");async function nl(r=process.cwd()){try{let e=await R.getProjectId(r);if(!e)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let t=rs.join(E.getGlobalProjectPath(e),"snapshots"),n=rs.join(t,"history.json"),s;try{let o=await te.readFile(n);s=JSON.parse(o)}catch(o){if(C(o)||o instanceof SyntaxError)return console.log(`
|
|
1313
1026
|
SNAPSHOT HISTORY
|
|
1314
1027
|
`),console.log("=".repeat(50)),console.log(" No snapshots yet."),console.log(` Use /p:undo to create a snapshot.
|
|
1315
1028
|
`),{success:!0,snapshots:[]};throw o}return console.log(`
|
|
@@ -1317,32 +1030,32 @@ ${"\u2550".repeat(50)}
|
|
|
1317
1030
|
`),console.log("=".repeat(50)),s.snapshots.length===0?(console.log(" No snapshots yet."),console.log(` Use /p:undo to create a snapshot.
|
|
1318
1031
|
`)):(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
|
|
1319
1032
|
`)),console.log(`${"=".repeat(50)}
|
|
1320
|
-
`),{success:!0,snapshots:s.snapshots,current:s.current}}catch(e){return h.fail(
|
|
1033
|
+
`),{success:!0,snapshots:s.snapshots,current:s.current}}catch(e){return h.fail(y(e)),{success:!1,error:y(e)}}}l(nl,"history");var os=class extends ae{static{l(this,"MaintenanceCommands")}_cleanupMemory=qo;_cleanupMemoryInternal=Ko;async cleanup(e={},t=process.cwd()){let n=await this.ensureProjectInit(t);return n.success?Xc(e,t):n}async design(e=null,t={},n=process.cwd()){let s=await this.ensureProjectInit(n);return s.success?Qc(e,t,n):s}async recover(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?Zc(e):t}async undo(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?el(e):t}async redo(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?tl(e):t}async history(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?nl(e):t}};import fe from"chalk";le();var sl=class{static{l(this,"PerformanceTracker")}marks=new Map;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}recordTiming(e,t,n,s){z.appendEvent(e,`perf.${t}`,{metric:t,value:Math.round(n*100)/100,unit:"ms",context:s})}snapshotMemory(){let e=process.memoryUsage();return{heapUsed:e.heapUsed,heapTotal:e.heapTotal,rss:e.rss,external:e.external}}recordMemory(e,t){let n=this.snapshotMemory(),s=[{metric:"heap_used",value:n.heapUsed,unit:"bytes"},{metric:"heap_total",value:n.heapTotal,unit:"bytes"},{metric:"rss",value:n.rss,unit:"bytes"},{metric:"external_memory",value:n.external,unit:"bytes"}];for(let o of s)z.appendEvent(e,`perf.${o.metric}`,{metric:o.metric,value:o.value,unit:o.unit,context:t});return n}recordContextCorrectness(e,t){z.appendEvent(e,"perf.context_correctness",{metric:"context_correctness",...t})}recordSubtaskHandoff(e,t){z.appendEvent(e,"perf.subtask_handoff",{metric:"subtask_handoff",...t})}getMetrics(e,t){t||(t=new Date,t.setDate(t.getDate()-7));let n=t.toISOString();return z.query(e,"SELECT data, timestamp FROM events WHERE type LIKE ? AND timestamp >= ? ORDER BY id DESC","perf.%",n).map(o=>({...JSON.parse(o.data),timestamp:o.timestamp}))}getReport(e,t=7){let n=new Date;n.setDate(n.getDate()-t),n.setHours(0,0,0,0);let s=this.getMetrics(e,n),o={period:`${t}d`},i=s.filter(p=>"metric"in p&&p.metric==="startup_time");if(i.length>0){let p=i.map(g=>g.value);o.startup={avg:Math.round(p.reduce((g,f)=>g+f,0)/p.length),min:Math.min(...p),max:Math.max(...p),count:p.length,unit:"ms"}}let a=s.filter(p=>"metric"in p&&p.metric==="heap_used"),c=s.filter(p=>"metric"in p&&p.metric==="rss");if(a.length>0){let p=l(S=>Math.round(S/1048576*10)/10,"toMB"),g=a.map(S=>S.value),f=c.map(S=>S.value);o.memory={avgHeapMB:p(g.reduce((S,b)=>S+b,0)/g.length),peakHeapMB:p(Math.max(...g)),avgRssMB:f.length>0?p(f.reduce((S,b)=>S+b,0)/f.length):0}}let u=s.filter(p=>"metric"in p&&p.metric==="context_correctness");if(u.length>0){let p=u.filter(g=>g.receivedSync).length;o.contextCorrectness={total:u.length,receivedSync:p,rate:Math.round(p/u.length*100)}}let d=s.filter(p=>"metric"in p&&p.metric==="subtask_handoff");if(d.length>0){let p=d.filter(g=>g.outputPopulated).length;o.subtaskHandoff={total:d.length,outputPopulated:p,rate:Math.round(p/d.length*100)}}let m=s.filter(p=>"metric"in p&&p.metric==="command_duration");if(m.length>0){let p={};for(let g of m){let f=g.context?.command||"unknown";p[f]||(p[f]=[]),p[f].push(g.value)}o.commandDurations={};for(let[g,f]of Object.entries(p))o.commandDurations[g]={avg:Math.round(f.reduce((S,b)=>S+b,0)/f.length),min:Math.min(...f),max:Math.max(...f),count:f.length,unit:"ms"}}return o}},fP=new sl,sg=fP;O();He();var sn={startup:{max:500,unit:"ms"},heapMB:{max:80,unit:"MB"},contextRate:{min:100,unit:"%"},handoffRate:{min:100,unit:"%"}};function Yo(r,e,t){return t==="below"?r<=e?fe.green("\u2713"):fe.yellow("\u26A0"):r>=e?fe.green("\u2713"):fe.yellow("\u26A0")}l(Yo,"statusIcon");var is=class extends ae{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 R.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 sg.getReport(s,o);if(!(i.startup||i.memory||i.contextCorrectness||i.subtaskHandoff||i.commandDurations))return console.log(`
|
|
1321
1034
|
${fe.dim("No performance data yet.")}`),console.log(`${fe.dim("Metrics are collected automatically as you use the CLI.")}
|
|
1322
1035
|
`),{success:!0,message:"No data"};if(console.log(`
|
|
1323
|
-
${fe.cyan("Performance Report")} ${fe.dim(`(last ${o} days)`)}`),console.log("\u2550".repeat(55)),i.startup){let c=
|
|
1324
|
-
${fe.dim("Command Durations:")}`);for(let[c,u]of Object.entries(i.commandDurations))console.log(` ${c.padEnd(12)} avg ${fe.bold(`${u.avg}ms`)} ${fe.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(
|
|
1325
|
-
`),!(await
|
|
1036
|
+
${fe.cyan("Performance Report")} ${fe.dim(`(last ${o} days)`)}`),console.log("\u2550".repeat(55)),i.startup){let c=Yo(i.startup.avg,sn.startup.max,"below");console.log(` Startup: avg ${fe.bold(`${i.startup.avg}ms`)} ${fe.dim(`(min ${i.startup.min}, max ${i.startup.max}, n=${i.startup.count})`)} ${c} ${fe.dim(`target: <${sn.startup.max}ms`)}`)}if(i.memory){let c=Yo(i.memory.peakHeapMB,sn.heapMB.max,"below");console.log(` Memory: avg ${fe.bold(`${i.memory.avgHeapMB}MB`)} heap, peak ${i.memory.peakHeapMB}MB, rss ${i.memory.avgRssMB}MB ${c} ${fe.dim(`target: <${sn.heapMB.max}MB`)}`)}if(i.contextCorrectness){let c=Yo(i.contextCorrectness.rate,sn.contextRate.min,"above");console.log(` Context: ${fe.bold(`${i.contextCorrectness.rate}%`)} tasks received sync ${fe.dim(`(${i.contextCorrectness.receivedSync}/${i.contextCorrectness.total})`)} ${c} ${fe.dim(`target: ${sn.contextRate.min}%`)}`)}if(i.subtaskHandoff){let c=Yo(i.subtaskHandoff.rate,sn.handoffRate.min,"above");console.log(` Handoff: ${fe.bold(`${i.subtaskHandoff.rate}%`)} subtasks with output ${fe.dim(`(${i.subtaskHandoff.outputPopulated}/${i.subtaskHandoff.total})`)} ${c} ${fe.dim(`target: ${sn.handoffRate.min}%`)}`)}if(i.commandDurations&&Object.keys(i.commandDurations).length>0){console.log(`
|
|
1037
|
+
${fe.dim("Command Durations:")}`);for(let[c,u]of Object.entries(i.commandDurations))console.log(` ${c.padEnd(12)} avg ${fe.bold(`${u.avg}ms`)} ${fe.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(y(n)),{success:!1,error:y(n)}}}};Mo();mn();ue();O();je();dn();He();import rl from"node:fs/promises";import hP from"node:path";import Z from"chalk";var as=class extends ae{static{l(this,"SetupCommands")}async start(){let t=await(Ve(),at(et)).getActiveProvider();if(console.log(`\u{1F680} Setting up prjct for ${t.displayName}...
|
|
1038
|
+
`),!(await Le.checkInstallation()).claudeDetected)return{success:!1,message:`\u274C ${t.displayName} not detected.
|
|
1326
1039
|
|
|
1327
1040
|
Please install it first:
|
|
1328
|
-
- ${t.displayName}: ${t.docsUrl}`};console.log("\u{1F4E6} Installing /p:* commands...");let s=await
|
|
1041
|
+
- ${t.displayName}: ${t.docsUrl}`};console.log("\u{1F4E6} Installing /p:* commands...");let s=await Le.installCommands();if(!s.success)return{success:!1,message:`\u274C Installation failed: ${s.error}`};if(console.log(`
|
|
1329
1042
|
\u2705 Installed ${s.installed?.length??0} commands to:
|
|
1330
|
-
${
|
|
1043
|
+
${E.getDisplayPath(s.path||"")}`),(s.errors?.length??0)>0){console.log(`
|
|
1331
1044
|
\u26A0\uFE0F ${s.errors?.length??0} errors:`);for(let o of s.errors??[])console.log(` - ${o.file}: ${o.error}`)}return console.log(`
|
|
1332
1045
|
\u{1F389} Setup complete!`),console.log(`
|
|
1333
1046
|
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...
|
|
1334
|
-
`),e.force&&(console.log("\u{1F5D1}\uFE0F Removing existing installation..."),await
|
|
1047
|
+
`),e.force&&(console.log("\u{1F5D1}\uFE0F Removing existing installation..."),await Le.uninstallCommands()),console.log("\u{1F4E6} Installing /p:* commands...");let t=await Le.updateCommands();if(!t.success)return{success:!1,message:`\u274C Setup failed: ${t.error}`};if(console.log(`
|
|
1335
1048
|
\u2705 Installed ${t.installed?.length??0} commands`),(t.errors?.length??0)>0){console.log(`
|
|
1336
1049
|
\u26A0\uFE0F ${t.errors?.length??0} errors:`);for(let a of t.errors??[])console.log(` - ${a.file}: ${a.error}`)}console.log(`
|
|
1337
|
-
\u{1F4DD} Installing global configuration...`);let n=await
|
|
1050
|
+
\u{1F4DD} Installing global configuration...`);let n=await Le.installGlobalConfig(),s=n.path?E.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(Ve(),at(et)).getActiveProvider()).name==="claude"){console.log(`
|
|
1338
1051
|
\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(`
|
|
1339
1052
|
\u{1F389} Setup complete!
|
|
1340
|
-
`),this.showAsciiArt(),{success:!0,message:""}}async installStatusLine(){try{let e=
|
|
1053
|
+
`),this.showAsciiArt(),{success:!0,message:""}}async installStatusLine(){try{let e=E.getClaudeDir(),t=E.getClaudeSettingsPath(),n=hP.join(e,"prjct-statusline.sh"),s=`#!/bin/bash
|
|
1341
1054
|
# prjct Status Line for Claude Code
|
|
1342
1055
|
# Shows version update notifications and current task
|
|
1343
1056
|
|
|
1344
1057
|
# Current CLI version (embedded at install time)
|
|
1345
|
-
CLI_VERSION="${
|
|
1058
|
+
CLI_VERSION="${Wn}"
|
|
1346
1059
|
|
|
1347
1060
|
# Read JSON context from stdin (provided by Claude Code)
|
|
1348
1061
|
read -r json
|
|
@@ -1393,18 +1106,18 @@ fi
|
|
|
1393
1106
|
|
|
1394
1107
|
# Default: show prjct branding
|
|
1395
1108
|
echo "\u26A1 prjct"
|
|
1396
|
-
`;await
|
|
1397
|
-
${
|
|
1398
|
-
`)[0])),{success:!1,failed:o,output:c}}}l(
|
|
1109
|
+
`;await rl.writeFile(n,s,{mode:493});let o={};if(await M(t))try{o=JSON.parse(await rl.readFile(t,"utf8"))}catch{}return o.statusLine={type:"command",command:n},await rl.writeFile(t,JSON.stringify(o,null,2)),{success:!0}}catch(e){return{success:!1,error:y(e)}}}showAsciiArt(){console.log(Z.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(Z.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(Z.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(Z.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(Z.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(Z.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(Z.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(` ${Z.bold.cyan("prjct")}${Z.magenta("/")}${Z.green("cli")} ${Z.dim.white(`v${Wn} installed`)}`),console.log(""),console.log(` ${Z.yellow("\u26A1")} Ship faster with zero friction`),console.log(` ${Z.green("\u{1F4DD}")} From idea to technical tasks in minutes`),console.log(` ${Z.cyan("\u{1F916}")} Perfect context for AI agents`),console.log(""),console.log(Z.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(Z.bold.cyan("\u{1F680} Quick Start")),console.log(Z.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(` ${Z.bold("1.")} Initialize your project:`),console.log(` ${Z.green("cd your-project && prjct init")}`),console.log(""),console.log(` ${Z.bold("2.")} Start your first task:`),console.log(` ${Z.green('prjct task "build auth"')}`),console.log(""),console.log(` ${Z.bold("3.")} Ship & celebrate:`),console.log(` ${Z.green('prjct ship "user login"')}`),console.log(""),console.log(Z.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(` ${Z.dim("Documentation:")} ${Z.cyan("https://prjct.app")}`),console.log(` ${Z.dim("Report issues:")} ${Z.cyan("https://github.com/jlopezlira/prjct-cli/issues")}`),console.log(""),console.log(Z.bold.magenta("Happy shipping! \u{1F680}")),console.log("")}};Hn();Mt();O();Zn();es();import cg from"node:path";je();import Xe from"node:path";async function yP(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 M(Xe.join(r,"pnpm-lock.yaml"))?"pnpm":await M(Xe.join(r,"yarn.lock"))?"yarn":await M(Xe.join(r,"bun.lockb"))||await M(Xe.join(r,"bun.lock"))?"bun":(await M(Xe.join(r,"package-lock.json")),"npm")}l(yP,"detectPackageManager");function rg(r,e){return r==="yarn"?`yarn ${e}`:r==="pnpm"?`pnpm run ${e}`:r==="bun"?`bun run ${e}`:`npm run ${e}`}l(rg,"pmRun");function wP(r){return r==="yarn"?"yarn test":r==="pnpm"?"pnpm test":r==="bun"?"bun test":"npm test"}l(wP,"pmTest");async function ol(r){let e=Xe.join(r,"package.json"),t=await an(e,null);if(t){let o=await yP(r,t),i=t.scripts||{},a={stack:"js",packageManager:o};return i.lint&&(a.lint={tool:o,command:rg(o,"lint")}),i.typecheck&&(a.typecheck={tool:o,command:rg(o,"typecheck")}),i.test&&(a.test={tool:o,command:wP(o)}),a}if(await M(Xe.join(r,"pytest.ini")))return{stack:"python",test:{tool:"pytest",command:"pytest"}};let n=await _n(Xe.join(r,"pyproject.toml"),"");return n.includes("[tool.pytest")||n.includes("pytest")?{stack:"python",test:{tool:"pytest",command:"pytest"}}:await M(Xe.join(r,"Cargo.toml"))?{stack:"rust",test:{tool:"cargo",command:"cargo test"}}:await M(Xe.join(r,"go.mod"))?{stack:"go",test:{tool:"go",command:"go test ./..."}}:(await Nn(r)).some(o=>o.endsWith(".sln")||o.endsWith(".csproj")||o.endsWith(".fsproj"))?{stack:"dotnet",test:{tool:"dotnet",command:"dotnet test"}}:await M(Xe.join(r,"pom.xml"))?{stack:"java",test:{tool:"maven",command:"mvn test"}}:await M(Xe.join(r,"gradlew"))&&(await M(Xe.join(r,"build.gradle"))||await M(Xe.join(r,"build.gradle.kts")))?{stack:"java",test:{tool:"gradle",command:"./gradlew test"}}:{stack:"unknown"}}l(ol,"detectProjectCommands");Hn();O();Yt();import{exec as SP}from"node:child_process";import{promisify as kP}from"node:util";import Et from"chalk";var bP=kP(SP),Xo=new Map,cs=new Map;function lr(r,e){return`workflow:${r}_${e}`}l(lr,"prefKey");async function og(r,e){let t=lr(e.hook,e.command);switch(e.scope){case"permanent":await de.recordDecision(r,t,e.action,"workflow");break;case"session":Xo.set(t,e);break;case"once":cs.set(t,e);break}}l(og,"setWorkflowPreference");async function PP(r,e){let t={};for(let n of["before","after","skip"]){let s=lr(n,e),o=cs.get(s);if(o){n==="skip"?t.skip=o.action==="true":t[n]=o.action;continue}let i=Xo.get(s);if(i){n==="skip"?t.skip=i.action==="true":t[n]=i.action;continue}let a=await de.getSmartDecision(r,s);a&&(n==="skip"?t.skip=a==="true":t[n]=a)}return t}l(PP,"getWorkflowPreferences");async function rn(r,e,t,n={}){if(n.skipHooks)return{success:!0};let s=await PP(r,t);if(s.skip)return{success:!0,skipped:[t]};let o=s[e];if(!o)return{success:!0};let i=lr(e,t);cs.has(i)&&cs.delete(i),console.log(`
|
|
1110
|
+
${Et.dim(`Running ${e}-${t}: ${o}`)}`);try{let a=Date.now();await bP(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(`${Et.green("\u2713")} ${Et.dim(`(${u})`)}`),{success:!0}}catch(a){console.log(Et.red("\u2717 failed"));let c=y(a)||"Unknown error";return console.log(Et.dim(c.split(`
|
|
1111
|
+
`)[0])),{success:!1,failed:o,output:c}}}l(rn,"runWorkflowHooks");async function il(r){let e=[],t=["task","done","ship","sync"],n=["before","after","skip"];for(let s of t)for(let o of n){let i=lr(o,s),a=cs.get(i);if(a){e.push({key:`${o} ${s}`,action:a.action,scope:"once"});continue}let c=Xo.get(i);if(c){e.push({key:`${o} ${s}`,action:c.action,scope:"session"});continue}let u=await de.getSmartDecision(r,i);u&&e.push({key:`${o} ${s}`,action:u,scope:"permanent"})}return e}l(il,"listWorkflowPreferences");async function ig(r,e,t){let n=lr(e,t);return cs.delete(n),Xo.delete(n),await de.recordDecision(r,n,"","workflow:remove"),!0}l(ig,"removeWorkflowPreference");function ag(r){if(r.length===0)return`${Et.dim(Us.NO_PREFERENCES)}
|
|
1399
1112
|
|
|
1400
|
-
Set one: "${
|
|
1401
|
-
`)}l(
|
|
1113
|
+
Set one: "${Us.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"?Et.green("permanent"):t.scope==="session"?Et.yellow("session"):Et.dim("once");e.push(` [${n}] ${t.key.padEnd(15)} \u2192 ${t.action}`)}return e.push(""),e.push(Et.dim(`Modify: "${Us.MODIFY_EXAMPLE}"`)),e.push(Et.dim(`Remove: "${Us.REMOVE_EXAMPLE}"`)),e.join(`
|
|
1114
|
+
`)}l(ag,"formatWorkflowPreferences");He();var ls=class extends ae{static{l(this,"ShippingCommands")}async _runWithExitCode(e){let t=De.get("Bash"),s=`bash -lc "set +e; ${e.replace(/"/g,'\\"')} 2>&1; echo __EXIT:$?"`,o=await t(s),i=`${o.stdout}
|
|
1402
1115
|
${o.stderr}`.trim(),a=i.split(`
|
|
1403
1116
|
`),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,d=i.split(`
|
|
1404
1117
|
`).filter(m=>!m.startsWith("__EXIT:")).join(`
|
|
1405
|
-
`).trim();return{exitCode:Number.isFinite(u)?u:1,output:d}}async ship(e,t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;let o=await R.getProjectId(t);if(!o)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let i=e;i||(i=(await
|
|
1118
|
+
`).trim();return{exitCode:Number.isFinite(u)?u:1,output:d}}async ship(e,t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;let o=await R.getProjectId(t);if(!o)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let i=e;i||(i=(await F.getCurrentTask(o))?.description||"current work");let a=await rn(o,"before","ship",{projectPath:t,skipHooks:n.skipHooks});if(!a.success)return{success:!1,error:`Hook failed: ${a.failed}`};n.md||h.step(1,5,`Linting ${i}...`);let c=await this._runLint(t);n.md||h.step(2,5,"Running tests...");let u=await this._runTests(t);n.md||h.step(3,5,"Updating version...");let d=await this._bumpVersion(t);await this._updateChangelog(i,d,t),n.md||h.step(4,5,"Committing...");let m=await this._createShipCommit(i,t),p="skipped";if(m.success){n.md||h.step(5,5,"Pushing...");let f=await this._gitPush(t);p=f.success?"pushed":f.message}if(await qe.addShipped(o,{name:i,version:d}),await this.logToMemory(t,"feature_shipped",{feature:i,version:d,timestamp:H.getTimestamp()}),await de.learnDecision(o,"commit_footer","prjct","ship"),u.success&&await de.recordDecision(o,"test_before_ship","true","ship"),(!c.success||!u.success)&&await de.recordWorkflow(o,"quick_ship",{description:"Ship without full checks",feature_type:i.toLowerCase().includes("doc")?"docs":"other"}),await rn(o,"after","ship",{projectPath:t,skipHooks:n.skipHooks}),n.md){let f=fo("ship"),S=me(Ot(`Shipped: ${i}`,`Version: ${d}`),Ue("Results",Ct([`Lint: ${c.message}`,`Tests: ${u.message}`,`Commit: ${m.success?"created":m.message}`,`Push: ${p}`]),3),Oe(f.map(b=>({label:b.desc,command:b.cmd}))));console.log(S)}else h.done(`v${d} shipped`),ot("ship");return{success:!0,feature:i,version:d}}catch(s){return h.fail(y(s)),{success:!1,error:y(s)}}}async _runLint(e){try{let t=await ol(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 C(t)?{success:!0,message:"skipped (lint not found)"}:{success:!0,message:"skipped (lint detection failed)"}}}async _runTests(e){try{let t=await ol(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 C(t)?{success:!0,message:"skipped (tests not found)"}:{success:!0,message:"skipped (test detection failed)"}}}async _bumpVersion(e){try{let t=cg.join(e,"package.json"),n=await te.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 te.writeJson(t,n)),c}catch(t){if(C(t)||t instanceof SyntaxError)return"0.0.1";throw t}}async _updateChangelog(e,t,n){try{let s=cg.join(n,"CHANGELOG.md"),o=await te.readFile(s,`# Changelog
|
|
1406
1119
|
|
|
1407
|
-
`),i=`## [${t}] - ${
|
|
1120
|
+
`),i=`## [${t}] - ${H.formatDate(new Date)}
|
|
1408
1121
|
|
|
1409
1122
|
### Added
|
|
1410
1123
|
- ${e}
|
|
@@ -1413,22 +1126,22 @@ ${o.stderr}`.trim(),a=i.split(`
|
|
|
1413
1126
|
|
|
1414
1127
|
`,`# Changelog
|
|
1415
1128
|
|
|
1416
|
-
${i}`);await
|
|
1129
|
+
${i}`);await te.writeFile(s,a)}catch(s){C(s)?console.error(" Warning: CHANGELOG.md not found"):console.error(" Warning: Could not update CHANGELOG")}}async _createShipCommit(e,t){try{await De.get("Bash")("git add .");let n=`feat: ${e}
|
|
1417
1130
|
|
|
1418
|
-
Generated with [p/](https://www.prjct.app/)`;return await
|
|
1419
|
-
`));let i=0,a=0,c=0;for(let d of o){let m=`${d.slice(0,8)}...`;if(n){console.log(` ${
|
|
1131
|
+
Generated with [p/](https://www.prjct.app/)`;return await De.get("Bash")(`git commit -m "${n.replace(/"/g,'\\"')}"`),{success:!0,message:"Committed"}}catch(n){return C(n)?{success:!1,message:"Git not found"}:{success:!1,message:"No changes to commit"}}}async _gitPush(e){try{return await De.get("Bash")("git push"),{success:!0,message:"Pushed to remote"}}catch(t){return C(t)?{success:!1,message:"Git not found"}:{success:!1,message:"Push failed (no remote or auth issue)"}}}};nt();ue();go();O();yn();He();import CP from"node:fs/promises";import xP from"node:path";import us from"chalk";var ds=class extends ae{static{l(this,"UpdateCommands")}async update(e={},t=process.cwd()){let n=e["dry-run"]===!0,s=e.all===!0;try{let o=s?await this.getAllProjectIds():await this.getCurrentProjectId(t);if(o.length===0)return h.warn("no projects found"),{success:!1,message:"No prjct projects found to update"};n&&console.log(us.dim(`[dry-run] Would update ${o.length} project(s)
|
|
1132
|
+
`));let i=0,a=0,c=0;for(let d of o){let m=`${d.slice(0,8)}...`;if(n){console.log(` ${us.dim("would update")} ${m}`);continue}try{let p=await zs(d),g=await mo(d),f=p.migratedFiles.length;if(i+=f,a+=g,f>0||g>0?console.log(` ${us.green("\u2713")} ${m}: migrated ${f} files, swept ${g} leftovers`):console.log(` ${us.green("\u2713")} ${m}: already up to date`),p.errors.length>0){for(let S of p.errors)console.log(` ${us.yellow("\u26A0")} ${S.file}: ${S.error}`);c+=p.errors.length}}catch(p){console.log(` ${us.red("\u2717")} ${m}: ${y(p)}`),c++}}if(n)return h.done(`dry run complete (${o.length} projects)`),{success:!0,message:`Would update ${o.length} project(s)`};let u=[];return i>0&&u.push(`${i} files migrated`),a>0&&u.push(`${a} leftovers swept`),c>0&&u.push(`${c} errors`),u.length===0?h.done(`${o.length} project(s) already up to date`):h.done(`${o.length} project(s) updated: ${u.join(", ")}`),{success:c===0,message:`Updated ${o.length} project(s)`}}catch(o){return h.fail(y(o)),{success:!1,error:y(o)}}}async getCurrentProjectId(e){let t=await R.getProjectId(e);return t?[t]:[]}async getAllProjectIds(){let e=xP.join(E.getGlobalBasePath(),"projects");try{return(await CP.readdir(e,{withFileTypes:!0})).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name)}catch{return[]}}};Ya();Un();ja();O();Pn();He();import he from"chalk";var ps=class extends ae{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 R.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 Ke.getAll(s);if(i.length===0)return console.log(`
|
|
1420
1133
|
${he.dim("No velocity data yet.")}`),console.log(`${he.dim("Complete tasks with estimates to build velocity history.")}
|
|
1421
|
-
`),{success:!0,message:"No data"};let a=
|
|
1134
|
+
`),{success:!0,message:"No data"};let a=Co(i,o);await Ra.saveMetrics(s,a),console.log(`
|
|
1422
1135
|
${he.cyan("Sprint Velocity")} ${he.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 p=m.estimationAccuracy>=80?he.green:m.estimationAccuracy>=60?he.yellow:he.red;console.log(` Sprint ${String(m.sprintNumber).padStart(2)}: ${he.bold(`${m.pointsCompleted} pts`)} | ${m.tasksCompleted} tasks | accuracy: ${p(`${m.estimationAccuracy}%`)}`)}console.log("");let u=a.velocityTrend==="improving"?he.green("\u2191"):a.velocityTrend==="declining"?he.red("\u2193"):he.dim("\u2192");if(console.log(` Average: ${he.bold(`${a.averageVelocity} pts/sprint`)} | Trend: ${u} ${a.velocityTrend}`),console.log(` Estimation accuracy: ${he.bold(`${a.estimationAccuracy}%`)} ${he.dim(`(\xB1${o.accuracyTolerance??20}% tolerance)`)}`),a.underEstimated.length>0||a.overEstimated.length>0){console.log(`
|
|
1423
|
-
${he.dim("Patterns:")}`);for(let m of a.underEstimated)console.log(` ${he.yellow("\u26A0")} ${m.category} tasks underestimated by avg ${he.bold(`${m.avgVariance}%`)}`);for(let m of a.overEstimated)console.log(` ${he.green("\u2713")} ${m.category} tasks estimated within ${he.bold(`${m.avgVariance}%`)}`)}let d=parseInt(e,10);if(d>0&&a.averageVelocity>0){let m=
|
|
1424
|
-
${he.dim("Projection:")}`),console.log(` Backlog: ${he.bold(`${d} pts`)} remaining`),console.log(` At current velocity: ~${m.sprints} sprints (${m.sprints*(o.sprintLengthDays??7)} days)`),console.log(` Estimated completion: ${he.bold(p)}`)}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 R.readConfig(e);if(n?.velocity&&typeof n.velocity=="object")return{...en,...n.velocity}}catch{}return en}};Rc();Ac();An();var eC=[1,2,3,5,8,13,21],tC={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}},jg=l(r=>eC.includes(r),"isValidPoint"),pi=l(r=>tC[r],"pointsToMinutes"),Dg=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"),Rg=l(r=>{let e=pi(r);return`${Dg(e.min)}\u2013${Dg(e.max)}`},"pointsToTimeRange");Hr();var mi=300*1e3,Le=new kt({ttl:mi,maxSize:100}),jt=new kt({ttl:mi,maxSize:10}),Ts=new kt({ttl:mi,maxSize:5}),Es=new kt({ttl:mi,maxSize:5});function Cl(){Le.clear(),jt.clear(),Ts.clear(),Es.clear()}l(Cl,"clearLinearCache");function vl(){return{issues:Le.stats(),assignedIssues:jt.stats(),teams:Ts.stats(),projects:Es.stats()}}l(vl,"getLinearCacheStats");F();xl();var iC={backlog:"backlog",unstarted:"todo",started:"in_progress",completed:"done",canceled:"cancelled",cancelled:"cancelled"},aC={0:"none",1:"urgent",2:"high",3:"medium",4:"low"},Mg={none:0,urgent:1,high:2,medium:3,low:4},fi=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 gi("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(d=>d.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?Mg[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=Mg[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:iC[t?.type||"backlog"]||"backlog",priority:aC[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):[]}},et=new fi;var hi=class{static{l(this,"LinearService")}initialized=!1;userId=null;isReady(){return this.initialized&&et.isConfigured()}async initialize(e){this.initialized||(await et.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 et.fetchAssignedIssues(e);jt.set(t,s);for(let o of s)Le.set(`issue:${o.id}`,o),Le.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 et.fetchTeamIssues(e,t);jt.set(n,o);for(let i of o)Le.set(`issue:${i.id}`,i),Le.set(`issue:${i.externalId}`,i);return o}async fetchIssue(e){this.ensureInitialized();let t=`issue:${e}`,n=Le.get(t);if(n)return n;let s=await et.fetchIssue(e);return s&&(Le.set(`issue:${s.id}`,s),Le.set(`issue:${s.externalId}`,s)),s}async createIssue(e){this.ensureInitialized();let t=await et.createIssue(e);return Le.set(`issue:${t.id}`,t),Le.set(`issue:${t.externalId}`,t),jt.clear(),t}async updateIssue(e,t){this.ensureInitialized();let n=await et.updateIssue(e,t);return Le.set(`issue:${n.id}`,n),Le.set(`issue:${n.externalId}`,n),n}async markInProgress(e){this.ensureInitialized(),await et.markInProgress(e),Le.delete(`issue:${e}`),jt.clear()}async markDone(e){this.ensureInitialized(),await et.markDone(e),Le.delete(`issue:${e}`),jt.clear()}async addComment(e,t){this.ensureInitialized(),await et.addComment(e,t)}async getTeams(){this.ensureInitialized();let e=Ts.get("teams");if(e)return e;let t=await et.getTeams();return Ts.set("teams",t),t}async getProjects(){this.ensureInitialized();let e=Es.get("projects");if(e)return e;let t=await et.getProjects();return Es.set("projects",t),t}clearCache(){Cl()}getCacheStats(){return vl()}ensureInitialized(){if(!this.initialized)throw new Error("Linear service not initialized. Call linearService.initialize() first or run `p. linear setup`.")}},gt=new hi;Vi();de();F();var Fg=1800*1e3,yi=class{static{l(this,"LinearSync")}async pullAll(e){let t=new Date().toISOString(),n=[];try{let s=await gt.fetchAssignedIssues({limit:100}),o={};for(let a of s)try{o[a.externalId]=this.toCachedIssue(a,t)}catch(c){n.push({issueId:a.externalId||a.id,error:w(c)})}let i={provider:"linear",lastSync:t,staleAfter:Fg,issues:o};return M.setDoc(e,"issues",i),{provider:"linear",fetched:s.length,updated:Object.keys(o).length,errors:n,timestamp:t}}catch(s){return n.push({issueId:"all",error:w(s)}),{provider:"linear",fetched:0,updated:0,errors:n,timestamp:t}}}async getIssue(e,t){let n=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 gt.fetchIssue(t);if(!s)return null;let o=new Date().toISOString(),i=this.toCachedIssue(s,o);return this.updateIssueInCache(e,t,i),i}catch{return n?.issues[t]?n.issues[t]:null}}async getIssueLocal(e,t){return this.loadIssues(e)?.issues[t]||null}async pushStatus(e,t,n){n==="in_progress"?await gt.markInProgress(t):n==="done"&&await gt.markDone(t);let s=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(),this.saveIssues(e,s)}}async isStale(e){let t=this.loadIssues(e);if(!t||!t.lastSync)return!0;let n=new Date(t.lastSync).getTime(),s=Date.now(),o=t.staleAfter||Fg;return s-n>o}async getSyncStatus(e){let t=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=this.loadIssues(e);return t?Object.values(t.issues):[]}loadIssues(e){try{return M.getDoc(e,"issues")}catch{return null}}saveIssues(e,t){M.setDoc(e,"issues",t)}updateIssueInCache(e,t,n){let s=this.loadIssues(e);s||(s=Su("linear")),s.issues[t]=n,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}}},cC=new yi;bt();Ct();F();ps();ms();F();Fe();xl();import lC from"node:fs/promises";import uC from"node:os";import dC from"node:path";function pC(r){return dC.join(uC.homedir(),".prjct-cli","projects",r,"config","credentials.json")}l(pC,"getCredentialsPath");async function wi(r){let e=pC(r);if(!await $(e))return{};try{return JSON.parse(await lC.readFile(e,"utf-8"))}catch(t){return console.error("[project-credentials] Failed to read credentials:",w(t)),{}}}l(wi,"getProjectCredentials");async function Tl(r){let e=await wi(r);return e.linear?.apiKey?e.linear.apiKey:gi("linear-api-key")}l(Tl,"getLinearApiKey");An();We();var As=class extends le{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 R.getProjectId(t);if(!o)return n.md?console.log("> No project ID found. Run `prjct init` first."):h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(e){let i=await un(o,"before","task",{projectPath:t,skipHooks:n.skipHooks});if(!i.success)return{success:!1,error:`Hook failed: ${i.failed}`};let a=await Wo.execute("task",{task:e},t);if(!a.success)return n.md||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 wi(o),S=await Tl(o);if(S&&f.linear?.teamId){await gt.initializeFromApiKey(S,f.linear.teamId);let k=await gt.fetchIssue(e);k&&(c=e,u=`${e}: ${k.title}`,await gt.markInProgress(e))}}catch{}await O.startTask(o,{id:ae(),description:u,sessionId:ae(),linearId:c});let m=await Ec.getAvailableAgents(t),p=m.length>0?m.join(", "):"none (run p. sync)",g=a.orchestratorContext?.agents?.length||m.length;if(n.md){let f=a.subtasks||[],S=Ka({description:u,branch:a.branch,linearId:c,type:a.type}),k=f.length>0?Ya(f,0):"",v=jd(["All commits must include footer: `Generated with [p/](https://www.prjct.app/)`","Never commit directly to main/master"]),D=_e([{label:"Find relevant files",command:`prjct context files "${e}"`},{label:"Complete subtask",command:"prjct done --md"},{label:"Pause task",command:"prjct pause --md"}]);console.log(me(S,k,v,D))}else h.done(`${e}`,{agents:g>0?g:void 0}),or("working"),ct("task");return await this.logToMemory(t,"task_started",{task:e,agenticMode:!0,availableAgents:m,orchestratorContext:a.orchestratorContext,timestamp:L.getTimestamp()}),await un(o,"after","task",{projectPath:t,skipHooks:n.skipHooks}),{...a,success:!0,task:e,agenticMode:!0,availableAgents:m,fibonacci:{isValidPoint:jg,pointsToMinutes:pi,pointsToTimeRange:Rg,storeEstimate:l(async f=>{let S=pi(f);return await O.updateCurrentTask(o,{estimatedPoints:f,estimatedMinutes:S.typical}),S},"storeEstimate")}}}else{let i=await O.getCurrentTask(o);if(!i)return n.md?console.log(rn("No active task")):h.warn("no active task"),{success:!0,message:"No active task"};if(n.md){let a=i.startedAt?L.calculateDuration(new Date(i.startedAt)):void 0,c=Ka({description:i.description,status:"active",branch:i.branch,linearId:i.linearId,type:i.type,duration:a}),u=i.subtasks||[],d=i.currentSubtaskIndex,m=u.length>0?Ya(u,d):"",p=_e([{label:"Complete subtask",command:"prjct done --md"},{label:"Pause task",command:"prjct pause --md"}]);console.log(me(c,m,p))}else h.done(`working on: ${i.description}`);return{success:!0,task:i.description,currentTask:i}}}catch(s){return n.md?console.log(`> Error: ${w(s)}`):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 R.getProjectId(e);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=await O.getCurrentTask(s);if(!o)return h.warn("no active task"),{success:!0,message:"No active task to complete"};let i=await un(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=L.calculateDuration(f),u=Math.round((Date.now()-f.getTime())/6e4)}let d=o.estimatedMinutes,m=o.estimatedPoints;try{await Xe.record(s,{sessionId:o.sessionId,command:"done",task:a,startedAt:o.startedAt,completedAt:L.getTimestamp(),estimatedDuration:d?Og(d):"0m",actualDuration:c||"0m",variance:d?mC(u-d):"+0m",completedAsPlanned:!0,qualityScore:3,tags:[o.linearId].filter(Boolean)})}catch{}let p="";if(m&&d){let f=u-d,S=d>0?Math.round((u-d)/d*100):0,k=f>=0?"+":"";p=` | est: ${m}pt (${Og(d)}) \u2192 ${k}${S}%`}await O.completeTask(s,t.feedback);let g=o.linearId;if(g)try{let f=await wi(s),S=await Tl(s);S&&f.linear?.teamId&&(await gt.initializeFromApiKey(S,f.linear.teamId),await gt.markDone(g))}catch{}if(t.md){let f=c?` (${c})`:"";console.log(me(_t("Subtask Complete",`**Completed:** ${a}${f}`),Et({Duration:c||"unknown",...p?{Variance:p.replace(" | ","")}:{}}),_e([{label:"Complete next subtask",command:"p. done"},{label:"Ship when ready",command:"p. ship"}])))}else{let f=c?` (${c}${p})`:"";g?h.done(`${a}${f} \u2192 Linear \u2713`):h.done(`${a}${f}`),or("completed"),ct("done")}return await this.logToMemory(e,"task_completed",{task:a,duration:c,estimatedPoints:m,estimatedMinutes:d,actualMinutes:u,timestamp:L.getTimestamp()}),await un(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(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await R.getProjectId(e);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=await ce.getActiveTasks(s);if(o.length===0)return t.md?console.log(rn("Queue is empty")):h.warn("queue empty"),{success:!0,message:"Queue is empty"};if(t.md){let i=o.map(a=>{let c=a.type?` [${a.type}]`:"",u=a.priority?` ${a.priority}`:"";return`${a.description}${c}${u}`});console.log(me(ze("Queue",`${o.length} task${o.length!==1?"s":""}`),Tt(i,!0),_e([{label:"Start working",command:`p. task "${o[0].description}"`}])))}else h.done(`${o.length} task${o.length!==1?"s":""} queued`),ct("next");return{success:!0,tasks:o,count:o.length}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}async pause(e="",t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;let o=await R.getProjectId(t);if(!o)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let i=await O.getCurrentTask(o);if(!i)return n.md?console.log(rn("No active task to pause")):h.warn("no active task to pause"),{success:!1,message:"No active task to pause"};let a="";if(i.startedAt&&(a=L.calculateDuration(new Date(i.startedAt))),await O.pauseTask(o,e),n.md)console.log(me(_t("Task Paused",`**Paused:** ${i.description}`),Et({Reason:e||void 0,"Duration worked":a||void 0}),_e([{label:"Resume this task",command:"p. resume"},{label:"Start something new",command:"p. task"}])));else{let c=i.description.slice(0,40);h.done(`paused: ${c}${e?` (${e})`:""}`),or("paused"),ct("pause")}return await this.logToMemory(t,"task_paused",{task:i.description,reason:e,timestamp:L.getTimestamp()}),{success:!0,task:i.description,reason:e}}catch(s){return h.fail(w(s)),{success:!1,error:w(s)}}}async resume(e=null,t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;let o=await R.getProjectId(t);if(!o)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let i=await O.getCurrentTask(o);if(i)return n.md?console.log(rn(`Already working on: ${i.description}`)):h.warn("already working on a task"),{success:!1,message:`Already working on: ${i.description}`};let a=await O.resumeTask(o);return a?(n.md?console.log(me(_t("Task Resumed",`**Resumed:** ${a.description}`),_e([{label:"Continue working, then finish",command:"p. done"}]))):(h.done(`resumed: ${a.description.slice(0,40)}`),or("working"),ct("resume")),await this.logToMemory(t,"task_resumed",{task:a.description,timestamp:L.getTimestamp()}),{success:!0,task:a.description}):(n.md?console.log(rn("No paused task found")):h.warn("no paused task to resume"),{success:!1,message:"No paused task found"})}catch(s){return h.fail(w(s)),{success:!1,error:w(s)}}}async workflow(e=null,t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await R.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(!e){let o=await Pl(s);return console.log(Ag(o)),{success:!0,preferences:o}}return{success:!0,projectId:s,input:e,setWorkflowPreference:l(async o=>{await Tg(s,{...o,createdAt:L.getTimestamp()})},"setWorkflowPreference"),removeWorkflowPreference:l(async(o,i)=>{await Eg(s,o,i)},"removeWorkflowPreference"),listWorkflowPreferences:l(async()=>Pl(s),"listWorkflowPreferences")}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}};function Og(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`}l(Og,"formatMinutesToDuration");function mC(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`}l(mC,"formatVariance");var Nn=class{static{l(this,"PrjctCommands")}workflow;planning;shipping;analytics;performanceCmds;maintenance;analysis;setupCmds;updateCmds;velocityCmds;contextCmds;agent;agentInfo;currentAuthor;prjctDir;constructor(){this.workflow=new As,this.planning=new Mn,this.shipping=new Ps,this.analytics=new hs,this.performanceCmds=new Ss,this.maintenance=new ws,this.analysis=new On,this.setupCmds=new ks,this.updateCmds=new vs,this.velocityCmds=new xs,this.contextCmds=new _n,this.agent=null,this.agentInfo=null,this.currentAuthor=null,this.prjctDir=".prjct"}async task(e=null,t=process.cwd(),n={}){return this.workflow.now(e,t,n)}async done(e=process.cwd(),t={}){return this.workflow.done(e,t)}async next(e=process.cwd(),t={}){return this.workflow.next(e,t)}async pause(e="",t=process.cwd(),n={}){return this.workflow.pause(e,t,n)}async resume(e=null,t=process.cwd(),n={}){return this.workflow.resume(e,t,n)}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(),n={}){return this.planning.bug(e,t,n)}async idea(e,t=process.cwd(),n={}){return this.planning.idea(e,t,n)}async spec(e=null,t=process.cwd()){return this.planning.spec(e,t)}async ship(e,t=process.cwd(),n={}){return this.shipping.ship(e,t,{...n})}async dash(e="default",t=process.cwd(),n={}){return this.analytics.dash(e,t,n)}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 update(e={},t=process.cwd()){return this.updateCmds.update(e,t)}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)}},MH=new Nn;Jo();var _g={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}},Ng=[{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:"update",group:"setup",description:"Migrate all projects from JSON to SQLite",usage:{claude:null,terminal:"prjct update [--all] [--dry-run]"},params:"[--all] [--dry-run]",implemented:!0,hasTemplate:!1,requiresProject:!1,features:["Migrates JSON storage files to SQLite","Sweeps leftover JSON files","--all flag processes all projects on machine","--dry-run to preview without changes"]},{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"]}];Vo();Pn();re();F();Fe();We();import{execSync as Si}from"node:child_process";import tt from"node:fs/promises";import gC from"node:os";import Kt from"node:path";import fC from"node:readline";import ue from"chalk";var ki="<!-- prjct:start - DO NOT REMOVE THIS MARKER -->",br="<!-- prjct:end - DO NOT REMOVE THIS MARKER -->";async function El(r){let e=0;try{let t=await tt.readdir(r,{withFileTypes:!0});for(let n of t){let s=Kt.join(r,n.name);if(n.isDirectory())e+=await El(s);else try{let o=await tt.stat(s);e+=o.size}catch{}}}catch{}return e}l(El,"getDirectorySize");function Lg(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]}`}l(Lg,"formatSize");async function hC(r){try{return(await tt.readdir(r,{withFileTypes:!0})).filter(t=>t.isDirectory()).length}catch{return 0}}l(hC,"countDirectoryItems");function yC(){let r={homebrew:!1,npm:!1};try{Si("brew list prjct-cli 2>/dev/null",{encoding:"utf-8"})&&(r.homebrew=!0,r.homebrewFormula="prjct-cli")}catch{}try{Si("npm list -g prjct-cli --depth=0 2>/dev/null",{encoding:"utf-8"}).includes("prjct-cli")&&(r.npm=!0)}catch{}return r}l(yC,"detectInstallation");async function wC(){let r=[],e=ld(),t=T.getGlobalBasePath(),n=await $(t),s=n?await hC(Kt.join(t,"projects")):0,o=n?await El(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=Kt.join(e.claude.config,"CLAUDE.md"),a=await $(i),c=!1;if(a)try{let qe=await tt.readFile(i,"utf-8");c=qe.includes(ki)&&qe.includes(br)}catch{}r.push({path:i,type:"section",description:"prjct section in CLAUDE.md",exists:a&&c});let u=e.claude.commands,d=await $(u),m=d?await El(u):0;r.push({path:u,type:"directory",description:"Claude commands",size:m,exists:d});let p=e.claude.router,g=await $(p);r.push({path:p,type:"file",description:"Claude router",exists:g});let f=Kt.join(e.claude.config,"prjct-statusline.sh"),S=await $(f);r.push({path:f,type:"file",description:"Status line script",exists:S});let k=e.gemini.router,v=await $(k);r.push({path:k,type:"file",description:"Gemini router",exists:v});let D=Kt.join(e.gemini.config,"GEMINI.md"),q=await $(D),Me=!1;if(q)try{let qe=await tt.readFile(D,"utf-8");Me=qe.includes(ki)&&qe.includes(br)}catch{}return q&&Me&&r.push({path:D,type:"section",description:"prjct section in GEMINI.md",exists:!0}),r}l(wC,"gatherUninstallItems");async function SC(r){try{let e=await tt.readFile(r,"utf-8");if(!e.includes(ki)||!e.includes(br))return!1;let t=e.indexOf(ki),n=e.indexOf(br)+br.length,s=e.substring(0,t)+e.substring(n);return s=s.replace(/\n{3,}/g,`
|
|
1425
|
-
|
|
1426
|
-
`).trim(),!s||s.trim().length===0?await
|
|
1427
|
-
`,"utf-8"),!0}catch{return!1}}l(
|
|
1428
|
-
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(
|
|
1429
|
-
Uninstall cancelled.`)),{success:!1,message:"Uninstall cancelled by user"};console.log(""),console.log(
|
|
1430
|
-
${a.length} errors:`));for(let c of a)console.log(ue.red(` - ${c}`))}return console.log(""),console.log(ue.green("prjct has been uninstalled.")),console.log(ue.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}}l(CC,"uninstall");var bi=class extends le{static{l(this,"UninstallCommands")}async uninstall(e={},t=process.cwd()){return CC(e,t)}};var Is=new As,Pi=new Mn,vC=new Ps,Hg=new hs,xC=new Ss,Ds=new ws,js=new On,Gg=new ks,TC=new _n,EC=new xs,AC=new bi,IC=new vs;function DC(){for(let[r,e]of Object.entries(_g))U.registerCategory(r,e)}l(DC,"registerCategories");function zg(){if(U.has("work"))return;DC();let r=l(e=>Ng.find(t=>t.name===e),"getMeta");U.registerMethod("task",Is,"now",r("task")),U.registerMethod("done",Is,"done",r("done")),U.registerMethod("next",Is,"next",r("next")),U.registerMethod("pause",Is,"pause",r("pause")),U.registerMethod("resume",Is,"resume",r("resume")),U.registerMethod("workflow",Is,"workflow",r("workflow")),U.registerMethod("init",Pi,"init",r("init")),U.registerMethod("bug",Pi,"bug",r("bug")),U.registerMethod("idea",Pi,"idea",r("idea")),U.registerMethod("spec",Pi,"spec",r("spec")),U.registerMethod("ship",vC,"ship",r("ship")),U.registerMethod("dash",Hg,"dash",r("dash")),U.registerMethod("help",Hg,"help",r("help")),U.registerMethod("perf",xC,"perf",r("perf")),U.registerMethod("velocity",EC,"velocity",r("velocity")),U.registerMethod("cleanup",Ds,"cleanup",r("cleanup")),U.registerMethod("design",Ds,"design",r("design")),U.registerMethod("recover",Ds,"recover",r("recover")),U.registerMethod("undo",Ds,"undo",r("undo")),U.registerMethod("redo",Ds,"redo",r("redo")),U.registerMethod("history",Ds,"history",r("history")),U.registerMethod("analyze",js,"analyze",r("analyze")),U.registerMethod("sync",js,"sync",r("sync")),U.registerMethod("stats",js,"stats",r("stats")),U.registerMethod("status",js,"status",r("status")),U.registerMethod("seal",js,"seal",r("seal")),U.registerMethod("verify",js,"verify",r("verify")),U.registerMethod("start",Gg,"start",r("start")),U.registerMethod("setup",Gg,"setup",r("setup")),U.registerMethod("uninstall",AC,"uninstall",r("uninstall")),U.registerMethod("update",IC,"update",r("update")),U.registerMethod("context",TC,"context",r("context"))}l(zg,"registerAllCommands");zg();it();import{Hono as GC}from"hono";import{cors as zC}from"hono/cors";import{logger as WC}from"hono/logger";function jC(){return typeof globalThis<"u"&&"Bun"in globalThis?"bun":"node"}l(jC,"detectRuntime");function Al(){return jC()==="bun"}l(Al,"isBun");re();de();Xn();Zn();es();ts();F();qn();import RC from"node:fs/promises";import $C from"node:path";import{Hono as MC}from"hono";function FC(r){return T.getGlobalProjectPath(r)}l(FC,"getProjectDataPath");function Wg(r,e){let t=new MC,n=FC(r);return t.get("/state",async s=>{let o=await O.read(r);return s.json(o)}),t.get("/queue",async s=>{let o=await ce.read(r);return s.json(o)}),t.get("/ideas",async s=>{let o=await Ee.read(r);return s.json(o)}),t.get("/roadmap",async s=>{let o=M.getDoc(r,"roadmap");return o?s.json(o):s.json({features:[],backlog:[],lastUpdated:""})}),t.get("/shipped",async s=>{let o=await He.read(r);return s.json(o)}),t.get("/dashboard",async s=>{let[o,i,a,c]=await Promise.all([O.read(r),ce.read(r),Ee.read(r),He.read(r)]),u=M.getDoc(r,"roadmap");return s.json({projectId:r,state:o,queue:i,ideas:a,roadmap:u||{features:[],backlog:[],lastUpdated:""},shipped:c,timestamp:new Date().toISOString()})}),t.post("/state",async s=>{try{let o=await s.req.json();return await O.write(r,o),s.json({success:!0})}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=$C.join(n,"context",`${o}.md`),c=await RC.readFile(a,"utf-8");return s.text(c,200,{"Content-Type":"text/markdown"})}catch(a){return C(a)||B.error(`Context read error: ${w(a)}`),s.text("",200,{"Content-Type":"text/markdown"})}}),t}l(Wg,"createRoutes");re();de();Xn();Zn();es();ts();import Rs from"node:fs/promises";import OC from"node:path";import{Hono as _C}from"hono";var NC=T.getGlobalBasePath(),$s=OC.join(NC,"projects");function Ci(r){return M.getDoc(r,"project")}l(Ci,"getProjectConfig");async function Il(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(Il,"calculateDuration");function Bg(){let r=new _C;return r.get("/projects",async e=>{try{await Rs.mkdir($s,{recursive:!0});let n=(await Rs.readdir($s,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name),s=await Promise.all(n.map(async o=>{let i=Ci(o),a=await O.read(o),c=await ce.read(o),u=await Ee.read(o),d=await He.read(o),m=a?.currentTask,p=await Il(m?.startedAt);return{id:o,name:i?.name||o.slice(0,8),path:i?.path||null,currentTask:m?{...m,duration:p}:null,pausedTask:a?.previousTask||null,stats:{queueCount:c?.tasks?.filter(g=>!g.completed)?.length||0,ideasCount:u?.ideas?.filter(g=>g.status==="pending")?.length||0,shippedCount:d?.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");try{let[n,s,o,i,a]=await Promise.all([Promise.resolve(Ci(t)),O.read(t),ce.read(t),Ee.read(t),He.read(t)]),c=M.getDoc(t,"roadmap");s?.currentTask?.startedAt&&(s.currentTask.duration=await Il(s.currentTask.startedAt));let u=new Date,d=new Date(u.getFullYear(),u.getMonth(),u.getDate()),m=new Date(d);m.setDate(m.getDate()-m.getDay());let p=o?.tasks?.filter(f=>!f.completed||!f.completedAt?!1:new Date(f.completedAt)>=d)?.length||0,g=o?.tasks?.filter(f=>!f.completed||!f.completedAt?!1:new Date(f.completedAt)>=m)?.length||0;return e.json({id:t,name:n?.name||t,path:n?.path,state:s||{currentTask:null,previousTask:null,lastUpdated:""},queue:o||{tasks:[],lastUpdated:""},ideas:i||{ideas:[],lastUpdated:""},shipped:a||{shipped:[],lastUpdated:""},roadmap:c||{features:[],backlog:[],lastUpdated:""},stats:{tasksToday:p,tasksThisWeek:g,queueCount:o?.tasks?.filter(f=>!f.completed)?.length||0,ideasCount:i?.ideas?.filter(f=>f.status==="pending")?.length||0,shippedCount:a?.shipped?.length||0},timestamp:new Date().toISOString()})}catch(n){return e.json({error:String(n)},500)}}),r.post("/projects/:id/task/complete",async e=>{let t=e.req.param("id");try{let n=await O.read(t);if(!n?.currentTask)return e.json({success:!1,error:"No active task"},400);let s=n.currentTask,o={currentTask:null,previousTask:null,lastUpdated:new Date().toISOString()};return await O.write(t,o),e.json({success:!0,completedTask:s,message:`Completed: ${s.description}`})}catch(n){return e.json({success:!1,error:String(n)},500)}}),r.post("/projects/:id/task/pause",async e=>{let t=e.req.param("id");try{let s=(await e.req.json().catch(()=>({}))).reason,o=await O.read(t);if(!o?.currentTask)return e.json({success:!1,error:"No active task"},400);let i={id:o.currentTask.id,description:o.currentTask.description,status:"paused",startedAt:o.currentTask.startedAt,pausedAt:new Date().toISOString(),pauseReason:s},a={currentTask:null,previousTask:i,lastUpdated:new Date().toISOString()};return await O.write(t,a),e.json({success:!0,pausedTask:i,message:`Paused: ${i.description}`})}catch(n){return e.json({success:!1,error:String(n)},500)}}),r.post("/projects/:id/task/resume",async e=>{let t=e.req.param("id");try{let n=await O.read(t);if(!n?.previousTask)return e.json({success:!1,error:"No paused task"},400);let s={id:n.previousTask.id,description:n.previousTask.description,status:"active",startedAt:new Date().toISOString(),sessionId:`sess_${Date.now().toString(36)}`},o={currentTask:s,previousTask:null,lastUpdated:new Date().toISOString()};return await O.write(t,o),e.json({success:!0,resumedTask:s,message:`Resumed: ${s.description}`})}catch(n){return e.json({success:!1,error:String(n)},500)}}),r.post("/projects/:id/queue/start",async e=>{let t=e.req.param("id");try{let n=await e.req.json(),{taskId:s}=n;if(!s)return e.json({success:!1,error:"taskId required"},400);let[o,i]=await Promise.all([O.read(t),ce.read(t)]);if(o?.currentTask)return e.json({success:!1,error:"Complete or pause current task first"},400);let a=i?.tasks?.find(d=>d.id===s);if(!a)return e.json({success:!1,error:"Task not found in queue"},404);let c={id:a.id,description:a.description,status:"active",startedAt:new Date().toISOString(),sessionId:`sess_${Date.now().toString(36)}`,featureId:a.featureId},u={currentTask:c,previousTask:null,lastUpdated:new Date().toISOString()};return await O.write(t,u),e.json({success:!0,task:c,message:`Started: ${c.description}`})}catch(n){return e.json({success:!1,error:String(n)},500)}}),r.post("/projects/:id/ideas",async e=>{let t=e.req.param("id");try{let n=await e.req.json(),{text:s,priority:o="medium",tags:i=[]}=n;if(!s)return e.json({success:!1,error:"text required"},400);let a=await Ee.addIdea(t,s,{priority:o||"medium",tags:i});return e.json({success:!0,idea:a,message:`Captured: ${s.slice(0,50)}...`})}catch(n){return e.json({success:!1,error:String(n)},500)}}),r.get("/stats/global",async e=>{try{await Rs.mkdir($s,{recursive:!0});let n=(await Rs.readdir($s,{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=await O.read(c),d=await ce.read(c),m=await Ee.read(c),p=await He.read(c);u?.currentTask&&a++,s+=d?.tasks?.filter(g=>!g.completed)?.length||0,o+=m?.ideas?.filter(g=>g.status==="pending")?.length||0,i+=p?.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 Rs.mkdir($s,{recursive:!0});let s=(await Rs.readdir($s,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name),o=null;if(t)for(let d of s){let m=Ci(d),p=m?.repoPath||m?.path;if(p&&t.startsWith(p)){o=d;break}}let i=null,a=null,c=null,u=o?[o]:s;for(let d of u){let m=await O.read(d),p=Ci(d);if(m?.currentTask){i={id:d,name:p?.name||d,path:p?.repoPath||p?.path},a={...m.currentTask,duration:await Il(m.currentTask.startedAt)};break}m?.previousTask&&!c&&(i={id:d,name:p?.name||d,path:p?.repoPath||p?.path},c=m.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(Bg,"createExtendedRoutes");Ti();import{streamSSE as LC}from"hono/streaming";var Vg=3600*1e3,UC=300*1e3,HC=3e4;function Jg(){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()>Vg&&t(i)},UC),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 LC(o,async i=>{let a=crypto.randomUUID(),c=new Date().toISOString(),u=new AbortController,d={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)}},HC),p=setTimeout(()=>{t(a)},Vg);typeof m=="object"&&"unref"in m&&m.unref(),typeof p=="object"&&"unref"in p&&p.unref(),r.set(a,{client:d,heartbeatInterval:m,ttlTimeout:p,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(Jg,"createSSEManager");function qg(r){let e=new GC,t=Jg();r.enableCors!==!1&&e.use("*",zC({origin:"*",allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization"]})),r.enableLogging!==!1&&e.use("*",WC()),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=Wg(r.projectId,r.projectPath);e.route("/api",n);let s=Bg();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(Al())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: ${Al()?"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(qg,"createServer");var Kg=3478;var Gt={runDir:l(()=>`${process.env.HOME||xi("node:os").homedir()}/.prjct-cli/run`,"runDir"),socket:l(()=>`${Gt.runDir()}/daemon.sock`,"socket"),pid:l(()=>`${Gt.runDir()}/daemon.pid`,"pid"),log:l(()=>`${Gt.runDir()}/daemon.log`,"log")},Yg=1800*1e3;function Dl(r){return Buffer.from(`${JSON.stringify(r)}
|
|
1431
|
-
`)}l(
|
|
1432
|
-
`))!==-1;){let s=e.slice(0,n);if(e=e.slice(n+1),!!s.trim())try{let o=JSON.parse(s),i=await
|
|
1136
|
+
${he.dim("Patterns:")}`);for(let m of a.underEstimated)console.log(` ${he.yellow("\u26A0")} ${m.category} tasks underestimated by avg ${he.bold(`${m.avgVariance}%`)}`);for(let m of a.overEstimated)console.log(` ${he.green("\u2713")} ${m.category} tasks estimated within ${he.bold(`${m.avgVariance}%`)}`)}let d=parseInt(e,10);if(d>0&&a.averageVelocity>0){let m=Ud(d,a.averageVelocity,o),p=m.estimatedDate?new Date(m.estimatedDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"unknown";console.log(`
|
|
1137
|
+
${he.dim("Projection:")}`),console.log(` Backlog: ${he.bold(`${d} pts`)} remaining`),console.log(` At current velocity: ~${m.sprints} sprints (${m.sprints*(o.sprintLengthDays??7)} days)`),console.log(` Estimated completion: ${he.bold(p)}`)}return console.log("\u2550".repeat(60)),console.log(""),{success:!0}}catch(n){return h.fail(y(n)),{success:!1,error:y(n)}}}async loadVelocityConfig(e){try{let n=await R.readConfig(e);if(n?.velocity&&typeof n.velocity=="object")return{...qt,...n.velocity}}catch{}return qt}};hc();pc();Pn();var vP=[1,2,3,5,8,13,21],TP={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}},ug=l(r=>vP.includes(r),"isValidPoint"),Qo=l(r=>TP[r],"pointsToMinutes"),lg=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"),dg=l(r=>{let e=Qo(r);return`${lg(e.min)}\u2013${lg(e.max)}`},"pointsToTimeRange");lo();var Zo=300*1e3,_e=new Pt({ttl:Zo,maxSize:100}),At=new Pt({ttl:Zo,maxSize:10}),ms=new Pt({ttl:Zo,maxSize:5}),gs=new Pt({ttl:Zo,maxSize:5});function al(){_e.clear(),At.clear(),ms.clear(),gs.clear()}l(al,"clearLinearCache");function cl(){return{issues:_e.stats(),assignedIssues:At.stats(),teams:ms.stats(),projects:gs.stats()}}l(cl,"getLinearCacheStats");O();ll();var RP={backlog:"backlog",unstarted:"todo",started:"in_progress",completed:"done",canceled:"cancelled",cancelled:"cancelled"},jP={0:"none",1:"urgent",2:"high",3:"medium",4:"low"},mg={none:0,urgent:1,high:2,medium:3,low:4},ti=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 ei("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: ${y(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(d=>d.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?mg[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=mg[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:RP[t?.type||"backlog"]||"backlog",priority:jP[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):[]}},Qe=new ti;var ni=class{static{l(this,"LinearService")}initialized=!1;userId=null;isReady(){return this.initialized&&Qe.isConfigured()}async initialize(e){this.initialized||(await Qe.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=At.get(t);if(n)return n;let s=await Qe.fetchAssignedIssues(e);At.set(t,s);for(let o of s)_e.set(`issue:${o.id}`,o),_e.set(`issue:${o.externalId}`,o);return s}async fetchTeamIssues(e,t){this.ensureInitialized();let n=`team:${e}`,s=At.get(n);if(s)return s;let o=await Qe.fetchTeamIssues(e,t);At.set(n,o);for(let i of o)_e.set(`issue:${i.id}`,i),_e.set(`issue:${i.externalId}`,i);return o}async fetchIssue(e){this.ensureInitialized();let t=`issue:${e}`,n=_e.get(t);if(n)return n;let s=await Qe.fetchIssue(e);return s&&(_e.set(`issue:${s.id}`,s),_e.set(`issue:${s.externalId}`,s)),s}async createIssue(e){this.ensureInitialized();let t=await Qe.createIssue(e);return _e.set(`issue:${t.id}`,t),_e.set(`issue:${t.externalId}`,t),At.clear(),t}async updateIssue(e,t){this.ensureInitialized();let n=await Qe.updateIssue(e,t);return _e.set(`issue:${n.id}`,n),_e.set(`issue:${n.externalId}`,n),n}async markInProgress(e){this.ensureInitialized(),await Qe.markInProgress(e),_e.delete(`issue:${e}`),At.clear()}async markDone(e){this.ensureInitialized(),await Qe.markDone(e),_e.delete(`issue:${e}`),At.clear()}async addComment(e,t){this.ensureInitialized(),await Qe.addComment(e,t)}async getTeams(){this.ensureInitialized();let e=ms.get("teams");if(e)return e;let t=await Qe.getTeams();return ms.set("teams",t),t}async getProjects(){this.ensureInitialized();let e=gs.get("projects");if(e)return e;let t=await Qe.getProjects();return gs.set("projects",t),t}clearCache(){al()}getCacheStats(){return cl()}ensureInitialized(){if(!this.initialized)throw new Error("Linear service not initialized. Call linearService.initialize() first or run `p. linear setup`.")}},pt=new ni;Ri();le();O();var gg=1800*1e3,si=class{static{l(this,"LinearSync")}async pullAll(e){let t=new Date().toISOString(),n=[];try{let s=await pt.fetchAssignedIssues({limit:100}),o={};for(let a of s)try{o[a.externalId]=this.toCachedIssue(a,t)}catch(c){n.push({issueId:a.externalId||a.id,error:y(c)})}let i={provider:"linear",lastSync:t,staleAfter:gg,issues:o};return $.setDoc(e,"issues",i),{provider:"linear",fetched:s.length,updated:Object.keys(o).length,errors:n,timestamp:t}}catch(s){return n.push({issueId:"all",error:y(s)}),{provider:"linear",fetched:0,updated:0,errors:n,timestamp:t}}}async getIssue(e,t){let n=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 pt.fetchIssue(t);if(!s)return null;let o=new Date().toISOString(),i=this.toCachedIssue(s,o);return this.updateIssueInCache(e,t,i),i}catch{return n?.issues[t]?n.issues[t]:null}}async getIssueLocal(e,t){return this.loadIssues(e)?.issues[t]||null}async pushStatus(e,t,n){n==="in_progress"?await pt.markInProgress(t):n==="done"&&await pt.markDone(t);let s=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(),this.saveIssues(e,s)}}async isStale(e){let t=this.loadIssues(e);if(!t||!t.lastSync)return!0;let n=new Date(t.lastSync).getTime(),s=Date.now(),o=t.staleAfter||gg;return s-n>o}async getSyncStatus(e){let t=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=this.loadIssues(e);return t?Object.values(t.issues):[]}loadIssues(e){try{return $.getDoc(e,"issues")}catch{return null}}saveIssues(e,t){$.setDoc(e,"issues",t)}updateIssueInCache(e,t,n){let s=this.loadIssues(e);s||(s=Xl("linear")),s.issues[t]=n,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}}},$P=new si;yt();Mt();O();Zn();es();O();je();ll();import MP from"node:fs/promises";import OP from"node:os";import FP from"node:path";function _P(r){return FP.join(OP.homedir(),".prjct-cli","projects",r,"config","credentials.json")}l(_P,"getCredentialsPath");async function ri(r){let e=_P(r);if(!await M(e))return{};try{return JSON.parse(await MP.readFile(e,"utf-8"))}catch(t){return console.error("[project-credentials] Failed to read credentials:",y(t)),{}}}l(ri,"getProjectCredentials");async function ul(r){let e=await ri(r);return e.linear?.apiKey?e.linear.apiKey:ei("linear-api-key")}l(ul,"getLinearApiKey");Pn();He();var fs=class extends ae{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 R.getProjectId(t);if(!o)return n.md?console.log("> No project ID found. Run `prjct init` first."):h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(e){let i=await rn(o,"before","task",{projectPath:t,skipHooks:n.skipHooks});if(!i.success)return{success:!1,error:`Hook failed: ${i.failed}`};let a=await jo.execute("task",{task:e},t);if(!a.success)return n.md||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 ri(o),S=await ul(o);if(S&&f.linear?.teamId){await pt.initializeFromApiKey(S,f.linear.teamId);let b=await pt.fetchIssue(e);b&&(c=e,u=`${e}: ${b.title}`,await pt.markInProgress(e))}}catch{}await F.startTask(o,{id:oe(),description:u,sessionId:oe(),linearId:c});let m=await dc.getAvailableAgents(t),p=m.length>0?m.join(", "):"none (run p. sync)",g=a.orchestratorContext?.agents?.length||m.length;if(n.md){let f=a.subtasks||[],S=$a({description:u,branch:a.branch,linearId:c,type:a.type}),b=f.length>0?Ma(f,0):"",D=dd(["All commits must include footer: `Generated with [p/](https://www.prjct.app/)`","Never commit directly to main/master"]),j=Oe([{label:"Find relevant files",command:`prjct context files "${e}"`},{label:"Complete subtask",command:"prjct done --md"},{label:"Pause task",command:"prjct pause --md"}]);console.log(me(S,b,D,j))}else h.done(`${e}`,{agents:g>0?g:void 0}),qs("working"),ot("task");return await this.logToMemory(t,"task_started",{task:e,agenticMode:!0,availableAgents:m,orchestratorContext:a.orchestratorContext,timestamp:H.getTimestamp()}),await rn(o,"after","task",{projectPath:t,skipHooks:n.skipHooks}),{...a,success:!0,task:e,agenticMode:!0,availableAgents:m,fibonacci:{isValidPoint:ug,pointsToMinutes:Qo,pointsToTimeRange:dg,storeEstimate:l(async f=>{let S=Qo(f);return await F.updateCurrentTask(o,{estimatedPoints:f,estimatedMinutes:S.typical}),S},"storeEstimate")}}}else{let i=await F.getCurrentTask(o);if(!i)return n.md?console.log(Zt("No active task")):h.warn("no active task"),{success:!0,message:"No active task"};if(n.md){let a=i.startedAt?H.calculateDuration(new Date(i.startedAt)):void 0,c=$a({description:i.description,status:"active",branch:i.branch,linearId:i.linearId,type:i.type,duration:a}),u=i.subtasks||[],d=i.currentSubtaskIndex,m=u.length>0?Ma(u,d):"",p=Oe([{label:"Complete subtask",command:"prjct done --md"},{label:"Pause task",command:"prjct pause --md"}]);console.log(me(c,m,p))}else h.done(`working on: ${i.description}`);return{success:!0,task:i.description,currentTask:i}}}catch(s){return n.md?console.log(`> Error: ${y(s)}`):h.fail(y(s)),{success:!1,error:y(s)}}}async done(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await R.getProjectId(e);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=await F.getCurrentTask(s);if(!o)return h.warn("no active task"),{success:!0,message:"No active task to complete"};let i=await rn(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=H.calculateDuration(f),u=Math.round((Date.now()-f.getTime())/6e4)}let d=o.estimatedMinutes,m=o.estimatedPoints;try{await Ke.record(s,{sessionId:o.sessionId,command:"done",task:a,startedAt:o.startedAt,completedAt:H.getTimestamp(),estimatedDuration:d?fg(d):"0m",actualDuration:c||"0m",variance:d?NP(u-d):"+0m",completedAsPlanned:!0,qualityScore:3,tags:[o.linearId].filter(Boolean)})}catch{}let p="";if(m&&d){let f=u-d,S=d>0?Math.round((u-d)/d*100):0,b=f>=0?"+":"";p=` | est: ${m}pt (${fg(d)}) \u2192 ${b}${S}%`}await F.completeTask(s,t.feedback);let g=o.linearId;if(g)try{let f=await ri(s),S=await ul(s);S&&f.linear?.teamId&&(await pt.initializeFromApiKey(S,f.linear.teamId),await pt.markDone(g))}catch{}if(t.md){let f=c?` (${c})`:"";console.log(me(Ot("Subtask Complete",`**Completed:** ${a}${f}`),xt({Duration:c||"unknown",...p?{Variance:p.replace(" | ","")}:{}}),Oe([{label:"Complete next subtask",command:"p. done"},{label:"Ship when ready",command:"p. ship"}])))}else{let f=c?` (${c}${p})`:"";g?h.done(`${a}${f} \u2192 Linear \u2713`):h.done(`${a}${f}`),qs("completed"),ot("done")}return await this.logToMemory(e,"task_completed",{task:a,duration:c,estimatedPoints:m,estimatedMinutes:d,actualMinutes:u,timestamp:H.getTimestamp()}),await rn(s,"after","done",{projectPath:e,skipHooks:t.skipHooks}),{success:!0,task:a,duration:c}}catch(n){return h.fail(y(n)),{success:!1,error:y(n)}}}async next(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await R.getProjectId(e);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=await pe.getActiveTasks(s);if(o.length===0)return t.md?console.log(Zt("Queue is empty")):h.warn("queue empty"),{success:!0,message:"Queue is empty"};if(t.md){let i=o.map(a=>{let c=a.type?` [${a.type}]`:"",u=a.priority?` ${a.priority}`:"";return`${a.description}${c}${u}`});console.log(me(Ue("Queue",`${o.length} task${o.length!==1?"s":""}`),Ct(i,!0),Oe([{label:"Start working",command:`p. task "${o[0].description}"`}])))}else h.done(`${o.length} task${o.length!==1?"s":""} queued`),ot("next");return{success:!0,tasks:o,count:o.length}}catch(n){return h.fail(y(n)),{success:!1,error:y(n)}}}async pause(e="",t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;let o=await R.getProjectId(t);if(!o)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let i=await F.getCurrentTask(o);if(!i)return n.md?console.log(Zt("No active task to pause")):h.warn("no active task to pause"),{success:!1,message:"No active task to pause"};let a="";if(i.startedAt&&(a=H.calculateDuration(new Date(i.startedAt))),await F.pauseTask(o,e),n.md)console.log(me(Ot("Task Paused",`**Paused:** ${i.description}`),xt({Reason:e||void 0,"Duration worked":a||void 0}),Oe([{label:"Resume this task",command:"p. resume"},{label:"Start something new",command:"p. task"}])));else{let c=i.description.slice(0,40);h.done(`paused: ${c}${e?` (${e})`:""}`),qs("paused"),ot("pause")}return await this.logToMemory(t,"task_paused",{task:i.description,reason:e,timestamp:H.getTimestamp()}),{success:!0,task:i.description,reason:e}}catch(s){return h.fail(y(s)),{success:!1,error:y(s)}}}async resume(e=null,t=process.cwd(),n={}){try{let s=await this.ensureProjectInit(t);if(!s.success)return s;let o=await R.getProjectId(t);if(!o)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let i=await F.getCurrentTask(o);if(i)return n.md?console.log(Zt(`Already working on: ${i.description}`)):h.warn("already working on a task"),{success:!1,message:`Already working on: ${i.description}`};let a=await F.resumeTask(o);return a?(n.md?console.log(me(Ot("Task Resumed",`**Resumed:** ${a.description}`),Oe([{label:"Continue working, then finish",command:"p. done"}]))):(h.done(`resumed: ${a.description.slice(0,40)}`),qs("working"),ot("resume")),await this.logToMemory(t,"task_resumed",{task:a.description,timestamp:H.getTimestamp()}),{success:!0,task:a.description}):(n.md?console.log(Zt("No paused task found")):h.warn("no paused task to resume"),{success:!1,message:"No paused task found"})}catch(s){return h.fail(y(s)),{success:!1,error:y(s)}}}async workflow(e=null,t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await R.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(!e){let o=await il(s);return console.log(ag(o)),{success:!0,preferences:o}}return{success:!0,projectId:s,input:e,setWorkflowPreference:l(async o=>{await og(s,{...o,createdAt:H.getTimestamp()})},"setWorkflowPreference"),removeWorkflowPreference:l(async(o,i)=>{await ig(s,o,i)},"removeWorkflowPreference"),listWorkflowPreferences:l(async()=>il(s),"listWorkflowPreferences")}}catch(n){return h.fail(y(n)),{success:!1,error:y(n)}}}};function fg(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`}l(fg,"formatMinutesToDuration");function NP(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`}l(NP,"formatVariance");var $n=class{static{l(this,"PrjctCommands")}workflow;planning;shipping;analytics;performanceCmds;maintenance;analysis;setupCmds;updateCmds;velocityCmds;contextCmds;agent;agentInfo;currentAuthor;prjctDir;constructor(){this.workflow=new fs,this.planning=new An,this.shipping=new ls,this.analytics=new ss,this.performanceCmds=new is,this.maintenance=new os,this.analysis=new Rn,this.setupCmds=new as,this.updateCmds=new ds,this.velocityCmds=new ps,this.contextCmds=new jn,this.agent=null,this.agentInfo=null,this.currentAuthor=null,this.prjctDir=".prjct"}async task(e=null,t=process.cwd(),n={}){return this.workflow.now(e,t,n)}async done(e=process.cwd(),t={}){return this.workflow.done(e,t)}async next(e=process.cwd(),t={}){return this.workflow.next(e,t)}async pause(e="",t=process.cwd(),n={}){return this.workflow.pause(e,t,n)}async resume(e=null,t=process.cwd(),n={}){return this.workflow.resume(e,t,n)}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(),n={}){return this.planning.bug(e,t,n)}async idea(e,t=process.cwd(),n={}){return this.planning.idea(e,t,n)}async spec(e=null,t=process.cwd()){return this.planning.spec(e,t)}async ship(e,t=process.cwd(),n={}){return this.shipping.ship(e,t,{...n})}async dash(e="default",t=process.cwd(),n={}){return this.analytics.dash(e,t,n)}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 update(e={},t=process.cwd()){return this.updateCmds.update(e,t)}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)}},I1=new $n;Oo();var hg={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}},yg=[{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:"update",group:"setup",description:"Migrate all projects from JSON to SQLite",usage:{claude:null,terminal:"prjct update [--all] [--dry-run]"},params:"[--all] [--dry-run]",implemented:!0,hasTemplate:!1,requiresProject:!1,features:["Migrates JSON storage files to SQLite","Sweeps leftover JSON files","--all flag processes all projects on machine","--dry-run to preview without changes"]},{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"]}];Mo();mn();ue();O();je();He();import{execSync as oi}from"node:child_process";import Ze from"node:fs/promises";import LP from"node:os";import Wt from"node:path";import UP from"node:readline";import ce from"chalk";var ii="<!-- prjct:start - DO NOT REMOVE THIS MARKER -->",ur="<!-- prjct:end - DO NOT REMOVE THIS MARKER -->";async function dl(r){let e=0;try{let t=await Ze.readdir(r,{withFileTypes:!0});for(let n of t){let s=Wt.join(r,n.name);if(n.isDirectory())e+=await dl(s);else try{let o=await Ze.stat(s);e+=o.size}catch{}}}catch{}return e}l(dl,"getDirectorySize");function wg(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]}`}l(wg,"formatSize");async function HP(r){try{return(await Ze.readdir(r,{withFileTypes:!0})).filter(t=>t.isDirectory()).length}catch{return 0}}l(HP,"countDirectoryItems");function zP(){let r={homebrew:!1,npm:!1};try{oi("brew list prjct-cli 2>/dev/null",{encoding:"utf-8"})&&(r.homebrew=!0,r.homebrewFormula="prjct-cli")}catch{}try{oi("npm list -g prjct-cli --depth=0 2>/dev/null",{encoding:"utf-8"}).includes("prjct-cli")&&(r.npm=!0)}catch{}return r}l(zP,"detectInstallation");async function GP(){let r=[],e=Iu(),t=E.getGlobalBasePath(),n=await M(t),s=n?await HP(Wt.join(t,"projects")):0,o=n?await dl(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=Wt.join(e.claude.config,"CLAUDE.md"),a=await M(i),c=!1;if(a)try{let Be=await Ze.readFile(i,"utf-8");c=Be.includes(ii)&&Be.includes(ur)}catch{}r.push({path:i,type:"section",description:"prjct section in CLAUDE.md",exists:a&&c});let u=e.claude.commands,d=await M(u),m=d?await dl(u):0;r.push({path:u,type:"directory",description:"Claude commands",size:m,exists:d});let p=e.claude.router,g=await M(p);r.push({path:p,type:"file",description:"Claude router",exists:g});let f=Wt.join(e.claude.config,"prjct-statusline.sh"),S=await M(f);r.push({path:f,type:"file",description:"Status line script",exists:S});let b=e.gemini.router,D=await M(b);r.push({path:b,type:"file",description:"Gemini router",exists:D});let j=Wt.join(e.gemini.config,"GEMINI.md"),q=await M(j),Re=!1;if(q)try{let Be=await Ze.readFile(j,"utf-8");Re=Be.includes(ii)&&Be.includes(ur)}catch{}return q&&Re&&r.push({path:j,type:"section",description:"prjct section in GEMINI.md",exists:!0}),r}l(GP,"gatherUninstallItems");async function WP(r){try{let e=await Ze.readFile(r,"utf-8");if(!e.includes(ii)||!e.includes(ur))return!1;let t=e.indexOf(ii),n=e.indexOf(ur)+ur.length,s=e.substring(0,t)+e.substring(n);return s=s.replace(/\n{3,}/g,`
|
|
1138
|
+
|
|
1139
|
+
`).trim(),!s||s.trim().length===0?await Ze.unlink(r):await Ze.writeFile(r,`${s}
|
|
1140
|
+
`,"utf-8"),!0}catch{return!1}}l(WP,"removePrjctSection");async function BP(){let r=LP.homedir(),e=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19),t=Wt.join(r,`.prjct-backup-${e}`);try{await Ze.mkdir(t,{recursive:!0});let n=E.getGlobalBasePath();return await M(n)&&await Sg(n,Wt.join(t,".prjct-cli")),t}catch{return null}}l(BP,"createBackup");async function Sg(r,e){await Ze.mkdir(e,{recursive:!0});let t=await Ze.readdir(r,{withFileTypes:!0});for(let n of t){let s=Wt.join(r,n.name),o=Wt.join(e,n.name);n.isDirectory()?await Sg(s,o):await Ze.copyFile(s,o)}}l(Sg,"copyDirectory");async function VP(r,e,t){let n=[],s=[];for(let o of r)if(o.exists)try{o.type==="section"?await WP(o.path)&&n.push(o.path):o.type==="directory"?(await Ze.rm(o.path,{recursive:!0,force:!0}),n.push(o.path)):o.type==="file"&&(await Ze.unlink(o.path),n.push(o.path))}catch(i){s.push(`${o.path}: ${y(i)}`)}if(!t.keepPackage){if(e.homebrew&&e.homebrewFormula)try{t.dryRun||oi(`brew uninstall ${e.homebrewFormula}`,{stdio:"pipe"}),n.push("Homebrew: prjct-cli")}catch(o){s.push(`Homebrew: ${y(o)}`)}if(e.npm)try{t.dryRun||oi("npm uninstall -g prjct-cli",{stdio:"pipe"}),n.push("npm: prjct-cli")}catch(o){s.push(`npm: ${y(o)}`)}}return{deleted:n,errors:s}}l(VP,"performUninstall");async function JP(r){let e=UP.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.toLowerCase()==="uninstall")})})}l(JP,"promptConfirmation");async function qP(r={},e=process.cwd()){let t=await GP(),n=zP(),s=t.filter(c=>c.exists);if(s.length===0&&!n.homebrew&&!n.npm)return console.log(ce.yellow(`
|
|
1141
|
+
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(ce.red.bold(" WARNING: This action is DANGEROUS and IRREVERSIBLE")),console.log(""),console.log(ce.white("The following will be permanently deleted:")),console.log("");for(let c of s){let u=E.getDisplayPath(c.path),d="";c.type==="section"?d=ce.dim("(section only)"):c.size&&(d=ce.dim(`(${wg(c.size)})`)),console.log(` ${ce.cyan(u.padEnd(35))} ${d}`),console.log(` ${ce.dim(c.description)}`),console.log("")}if(n.homebrew&&(console.log(` ${ce.cyan("Homebrew".padEnd(35))} ${ce.dim("prjct-cli formula")}`),console.log("")),n.npm&&(console.log(` ${ce.cyan("npm global".padEnd(35))} ${ce.dim("prjct-cli package")}`),console.log("")),o>0&&(console.log(ce.dim(` Total size: ${wg(o)}`)),console.log("")),r.dryRun)return console.log(ce.yellow("Dry run - no changes made")),{success:!0,message:"Dry run complete",itemsFound:s.length};if(r.backup){console.log(ce.blue("Creating backup..."));let c=await BP();c?(console.log(ce.green(`Backup created: ${E.getDisplayPath(c)}`)),console.log("")):console.log(ce.yellow("Failed to create backup, continuing..."))}if(!r.force&&(console.log(ce.yellow('Type "uninstall" to confirm:')),!await JP("> ")))return console.log(ce.yellow(`
|
|
1142
|
+
Uninstall cancelled.`)),{success:!1,message:"Uninstall cancelled by user"};console.log(""),console.log(ce.blue("Removing prjct..."));let{deleted:i,errors:a}=await VP(t,n,r);if(console.log(""),i.length>0&&console.log(ce.green(`Removed ${i.length} items`)),a.length>0){console.log(ce.yellow(`
|
|
1143
|
+
${a.length} errors:`));for(let c of a)console.log(ce.red(` - ${c}`))}return console.log(""),console.log(ce.green("prjct has been uninstalled.")),console.log(ce.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}}l(qP,"uninstall");var ai=class extends ae{static{l(this,"UninstallCommands")}async uninstall(e={},t=process.cwd()){return qP(e,t)}};var hs=new fs,ci=new An,KP=new ls,kg=new ss,YP=new is,ys=new os,ws=new Rn,bg=new as,XP=new jn,QP=new ps,ZP=new ai,eC=new ds;function tC(){for(let[r,e]of Object.entries(hg))L.registerCategory(r,e)}l(tC,"registerCategories");function Pg(){if(L.has("work"))return;tC();let r=l(e=>yg.find(t=>t.name===e),"getMeta");L.registerMethod("task",hs,"now",r("task")),L.registerMethod("done",hs,"done",r("done")),L.registerMethod("next",hs,"next",r("next")),L.registerMethod("pause",hs,"pause",r("pause")),L.registerMethod("resume",hs,"resume",r("resume")),L.registerMethod("workflow",hs,"workflow",r("workflow")),L.registerMethod("init",ci,"init",r("init")),L.registerMethod("bug",ci,"bug",r("bug")),L.registerMethod("idea",ci,"idea",r("idea")),L.registerMethod("spec",ci,"spec",r("spec")),L.registerMethod("ship",KP,"ship",r("ship")),L.registerMethod("dash",kg,"dash",r("dash")),L.registerMethod("help",kg,"help",r("help")),L.registerMethod("perf",YP,"perf",r("perf")),L.registerMethod("velocity",QP,"velocity",r("velocity")),L.registerMethod("cleanup",ys,"cleanup",r("cleanup")),L.registerMethod("design",ys,"design",r("design")),L.registerMethod("recover",ys,"recover",r("recover")),L.registerMethod("undo",ys,"undo",r("undo")),L.registerMethod("redo",ys,"redo",r("redo")),L.registerMethod("history",ys,"history",r("history")),L.registerMethod("analyze",ws,"analyze",r("analyze")),L.registerMethod("sync",ws,"sync",r("sync")),L.registerMethod("stats",ws,"stats",r("stats")),L.registerMethod("status",ws,"status",r("status")),L.registerMethod("seal",ws,"seal",r("seal")),L.registerMethod("verify",ws,"verify",r("verify")),L.registerMethod("start",bg,"start",r("start")),L.registerMethod("setup",bg,"setup",r("setup")),L.registerMethod("uninstall",ZP,"uninstall",r("uninstall")),L.registerMethod("update",eC,"update",r("update")),L.registerMethod("context",XP,"context",r("context"))}l(Pg,"registerAllCommands");Pg();nt();Pi();import{Hono as pC}from"hono";import{cors as mC}from"hono/cors";import{logger as gC}from"hono/logger";ue();le();Hs();Gs();Ws();Vs();O();Qn();import nC from"node:fs/promises";import sC from"node:path";import{Hono as rC}from"hono";function oC(r){return E.getGlobalProjectPath(r)}l(oC,"getProjectDataPath");function Cg(r,e){let t=new rC,n=oC(r);return t.get("/state",async s=>{let o=await F.read(r);return s.json(o)}),t.get("/queue",async s=>{let o=await pe.read(r);return s.json(o)}),t.get("/ideas",async s=>{let o=await Me.read(r);return s.json(o)}),t.get("/roadmap",async s=>{let o=$.getDoc(r,"roadmap");return o?s.json(o):s.json({features:[],backlog:[],lastUpdated:""})}),t.get("/shipped",async s=>{let o=await qe.read(r);return s.json(o)}),t.get("/dashboard",async s=>{let[o,i,a,c]=await Promise.all([F.read(r),pe.read(r),Me.read(r),qe.read(r)]),u=$.getDoc(r,"roadmap");return s.json({projectId:r,state:o,queue:i,ideas:a,roadmap:u||{features:[],backlog:[],lastUpdated:""},shipped:c,timestamp:new Date().toISOString()})}),t.post("/state",async s=>{try{let o=await s.req.json();return await F.write(r,o),s.json({success:!0})}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=sC.join(n,"context",`${o}.md`),c=await nC.readFile(a,"utf-8");return s.text(c,200,{"Content-Type":"text/markdown"})}catch(a){return C(a)||B.error(`Context read error: ${y(a)}`),s.text("",200,{"Content-Type":"text/markdown"})}}),t}l(Cg,"createRoutes");ue();le();Hs();Gs();Ws();Vs();import Ss from"node:fs/promises";import iC from"node:path";import{Hono as aC}from"hono";var cC=E.getGlobalBasePath(),ks=iC.join(cC,"projects");function li(r){return $.getDoc(r,"project")}l(li,"getProjectConfig");async function pl(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(pl,"calculateDuration");function xg(){let r=new aC;return r.get("/projects",async e=>{try{await Ss.mkdir(ks,{recursive:!0});let n=(await Ss.readdir(ks,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name),s=await Promise.all(n.map(async o=>{let i=li(o),a=await F.read(o),c=await pe.read(o),u=await Me.read(o),d=await qe.read(o),m=a?.currentTask,p=await pl(m?.startedAt);return{id:o,name:i?.name||o.slice(0,8),path:i?.path||null,currentTask:m?{...m,duration:p}:null,pausedTask:a?.previousTask||null,stats:{queueCount:c?.tasks?.filter(g=>!g.completed)?.length||0,ideasCount:u?.ideas?.filter(g=>g.status==="pending")?.length||0,shippedCount:d?.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");try{let[n,s,o,i,a]=await Promise.all([Promise.resolve(li(t)),F.read(t),pe.read(t),Me.read(t),qe.read(t)]),c=$.getDoc(t,"roadmap");s?.currentTask?.startedAt&&(s.currentTask.duration=await pl(s.currentTask.startedAt));let u=new Date,d=new Date(u.getFullYear(),u.getMonth(),u.getDate()),m=new Date(d);m.setDate(m.getDate()-m.getDay());let p=o?.tasks?.filter(f=>!f.completed||!f.completedAt?!1:new Date(f.completedAt)>=d)?.length||0,g=o?.tasks?.filter(f=>!f.completed||!f.completedAt?!1:new Date(f.completedAt)>=m)?.length||0;return e.json({id:t,name:n?.name||t,path:n?.path,state:s||{currentTask:null,previousTask:null,lastUpdated:""},queue:o||{tasks:[],lastUpdated:""},ideas:i||{ideas:[],lastUpdated:""},shipped:a||{shipped:[],lastUpdated:""},roadmap:c||{features:[],backlog:[],lastUpdated:""},stats:{tasksToday:p,tasksThisWeek:g,queueCount:o?.tasks?.filter(f=>!f.completed)?.length||0,ideasCount:i?.ideas?.filter(f=>f.status==="pending")?.length||0,shippedCount:a?.shipped?.length||0},timestamp:new Date().toISOString()})}catch(n){return e.json({error:String(n)},500)}}),r.post("/projects/:id/task/complete",async e=>{let t=e.req.param("id");try{let n=await F.read(t);if(!n?.currentTask)return e.json({success:!1,error:"No active task"},400);let s=n.currentTask,o={currentTask:null,previousTask:null,lastUpdated:new Date().toISOString()};return await F.write(t,o),e.json({success:!0,completedTask:s,message:`Completed: ${s.description}`})}catch(n){return e.json({success:!1,error:String(n)},500)}}),r.post("/projects/:id/task/pause",async e=>{let t=e.req.param("id");try{let s=(await e.req.json().catch(()=>({}))).reason,o=await F.read(t);if(!o?.currentTask)return e.json({success:!1,error:"No active task"},400);let i={id:o.currentTask.id,description:o.currentTask.description,status:"paused",startedAt:o.currentTask.startedAt,pausedAt:new Date().toISOString(),pauseReason:s},a={currentTask:null,previousTask:i,lastUpdated:new Date().toISOString()};return await F.write(t,a),e.json({success:!0,pausedTask:i,message:`Paused: ${i.description}`})}catch(n){return e.json({success:!1,error:String(n)},500)}}),r.post("/projects/:id/task/resume",async e=>{let t=e.req.param("id");try{let n=await F.read(t);if(!n?.previousTask)return e.json({success:!1,error:"No paused task"},400);let s={id:n.previousTask.id,description:n.previousTask.description,status:"active",startedAt:new Date().toISOString(),sessionId:`sess_${Date.now().toString(36)}`},o={currentTask:s,previousTask:null,lastUpdated:new Date().toISOString()};return await F.write(t,o),e.json({success:!0,resumedTask:s,message:`Resumed: ${s.description}`})}catch(n){return e.json({success:!1,error:String(n)},500)}}),r.post("/projects/:id/queue/start",async e=>{let t=e.req.param("id");try{let n=await e.req.json(),{taskId:s}=n;if(!s)return e.json({success:!1,error:"taskId required"},400);let[o,i]=await Promise.all([F.read(t),pe.read(t)]);if(o?.currentTask)return e.json({success:!1,error:"Complete or pause current task first"},400);let a=i?.tasks?.find(d=>d.id===s);if(!a)return e.json({success:!1,error:"Task not found in queue"},404);let c={id:a.id,description:a.description,status:"active",startedAt:new Date().toISOString(),sessionId:`sess_${Date.now().toString(36)}`,featureId:a.featureId},u={currentTask:c,previousTask:null,lastUpdated:new Date().toISOString()};return await F.write(t,u),e.json({success:!0,task:c,message:`Started: ${c.description}`})}catch(n){return e.json({success:!1,error:String(n)},500)}}),r.post("/projects/:id/ideas",async e=>{let t=e.req.param("id");try{let n=await e.req.json(),{text:s,priority:o="medium",tags:i=[]}=n;if(!s)return e.json({success:!1,error:"text required"},400);let a=await Me.addIdea(t,s,{priority:o||"medium",tags:i});return e.json({success:!0,idea:a,message:`Captured: ${s.slice(0,50)}...`})}catch(n){return e.json({success:!1,error:String(n)},500)}}),r.get("/stats/global",async e=>{try{await Ss.mkdir(ks,{recursive:!0});let n=(await Ss.readdir(ks,{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=await F.read(c),d=await pe.read(c),m=await Me.read(c),p=await qe.read(c);u?.currentTask&&a++,s+=d?.tasks?.filter(g=>!g.completed)?.length||0,o+=m?.ideas?.filter(g=>g.status==="pending")?.length||0,i+=p?.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 Ss.mkdir(ks,{recursive:!0});let s=(await Ss.readdir(ks,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name),o=null;if(t)for(let d of s){let m=li(d),p=m?.repoPath||m?.path;if(p&&t.startsWith(p)){o=d;break}}let i=null,a=null,c=null,u=o?[o]:s;for(let d of u){let m=await F.read(d),p=li(d);if(m?.currentTask){i={id:d,name:p?.name||d,path:p?.repoPath||p?.path},a={...m.currentTask,duration:await pl(m.currentTask.startedAt)};break}m?.previousTask&&!c&&(i={id:d,name:p?.name||d,path:p?.repoPath||p?.path},c=m.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(xg,"createExtendedRoutes");di();import{streamSSE as lC}from"hono/streaming";var vg=3600*1e3,uC=300*1e3,dC=3e4;function Tg(){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()>vg&&t(i)},uC),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 lC(o,async i=>{let a=crypto.randomUUID(),c=new Date().toISOString(),u=new AbortController,d={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)}},dC),p=setTimeout(()=>{t(a)},vg);typeof m=="object"&&"unref"in m&&m.unref(),typeof p=="object"&&"unref"in p&&p.unref(),r.set(a,{client:d,heartbeatInterval:m,ttlTimeout:p,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(Tg,"createSSEManager");function Eg(r){let e=new pC,t=Tg();r.enableCors!==!1&&e.use("*",mC({origin:"*",allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization"]})),r.enableLogging!==!1&&e.use("*",gC()),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=Cg(r.projectId,r.projectPath);e.route("/api",n);let s=xg();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(As())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: ${As()?"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(Eg,"createServer");var Ag=3478;var Lt={runDir:l(()=>`${process.env.HOME||Ps("node:os").homedir()}/.prjct-cli/run`,"runDir"),socket:l(()=>`${Lt.runDir()}/daemon.sock`,"socket"),pid:l(()=>`${Lt.runDir()}/daemon.pid`,"pid"),log:l(()=>`${Lt.runDir()}/daemon.log`,"log")},Ig=1800*1e3;function ml(r){return Buffer.from(`${JSON.stringify(r)}
|
|
1144
|
+
`)}l(ml,"encodeMessage");var bs=null,dr=null,Ce=null,Ee=null;async function Dg(r){let e=Lt.socket(),t=Lt.pid(),n=Lt.runDir();if(mt.mkdirSync(n,{recursive:!0}),mt.existsSync(t)){let s=parseInt(mt.readFileSync(t,"utf-8").trim(),10);kC(s)&&(console.error(`Daemon already running (PID ${s})`),process.exit(1)),mt.unlinkSync(t)}if(mt.existsSync(e)&&mt.unlinkSync(e),Ee={startedAt:Date.now(),commandsServed:0,lastActivity:Date.now(),idleTimeoutMs:Ig,idleTimer:null},Ce=new $n,bs=fC(s=>hC(s)),bs.listen(e,()=>{mt.chmodSync(e,384),mt.writeFileSync(t,String(process.pid)),console.log(`prjct daemon started (PID ${process.pid})`),console.log(` Socket: ${e}`),Rg()}),bs.on("error",s=>{console.error("Daemon socket error:",s.message),pr(1)}),!r.noHttp)try{let s=process.cwd(),o=await R.getProjectId(s);if(o){let i=r.port||Ag;dr=Eg({port:i,projectId:o,projectPath:s,enableLogging:!1}),await dr.start()}}catch{}if(process.on("SIGTERM",()=>pr(0)),process.on("SIGINT",()=>pr(0)),process.on("SIGHUP",()=>{Ce=new $n,console.log("Daemon reloaded (SIGHUP)")}),!r.foreground)try{process.stdin?.unref?.()}catch{}}l(Dg,"startDaemon");function hC(r){let e="";r.on("data",async t=>{e+=t.toString();let n;for(;(n=e.indexOf(`
|
|
1145
|
+
`))!==-1;){let s=e.slice(0,n);if(e=e.slice(n+1),!!s.trim())try{let o=JSON.parse(s),i=await yC(o);r.write(ml(i))}catch(o){let i={id:"unknown",success:!1,exitCode:1,stderr:`Protocol error: ${o.message}`};r.write(ml(i))}}}),r.on("error",()=>{})}l(hC,"handleConnection");async function yC(r){if(!Ee||!Ce)return{id:r.id,success:!1,exitCode:1,stderr:"Daemon not initialized"};if(Rg(),Ee.commandsServed++,Ee.lastActivity=Date.now(),r.command==="daemon")return SC(r);if(r.command==="__ping")return{id:r.id,success:!0,exitCode:0,result:{pong:!0,pid:process.pid}};try{let e=[],t=[],n=console.log,s=console.error;console.log=(...o)=>e.push(o.map(String).join(" ")),console.error=(...o)=>t.push(o.map(String).join(" "));try{let o=await wC(r);return{id:r.id,success:o.success,exitCode:o.success?0:1,stdout:e.join(`
|
|
1433
1146
|
`)||o.message||void 0,stderr:t.join(`
|
|
1434
|
-
`)||o.error||void 0,result:o}}finally{console.log=n,console.error=s}}catch(e){return{id:r.id,success:!1,exitCode:1,stderr:e.message}}}l(
|
|
1147
|
+
`)||o.error||void 0,result:o}}finally{console.log=n,console.error=s}}catch(e){return{id:r.id,success:!1,exitCode:1,stderr:e.message}}}l(yC,"handleRequest");async function wC(r){let e=r.args.join(" ")||null,t=r.options,n=t.md===!0;switch(r.command){case"sync":return Ce.sync(r.cwd,{aiTools:t.agents?String(t.agents).split(","):void 0,preview:t.preview===!0||t["dry-run"]===!0,yes:t.yes===!0,json:t.json===!0,md:n,package:t.package?String(t.package):void 0,full:t.full===!0});case"status":return Ce.status(r.cwd,{json:t.json===!0,md:n});case"stats":return Ce.stats(r.cwd,{json:t.json===!0,export:t.export===!0});case"seal":return Ce.seal(r.cwd,{json:t.json===!0});case"verify":return Ce.verify(r.cwd,{json:t.json===!0,semantic:t.semantic===!0});case"task":return Ce.task(e,r.cwd,{md:n});case"done":return Ce.done(r.cwd,{md:n});case"next":return Ce.next(r.cwd,{md:n});case"pause":return Ce.pause(e||"",r.cwd,{md:n});case"resume":return Ce.resume(e,r.cwd,{md:n});case"bug":return Ce.bug(e||"",r.cwd,{md:n});case"idea":return Ce.idea(e||"",r.cwd,{md:n});case"ship":return Ce.ship(e,r.cwd,{md:n});case"dash":return Ce.dash(e||"default",r.cwd,{md:n});case"design":return Ce.design(e||"",t);case"analyze":return Ce.analyze(t);case"cleanup":return Ce.cleanup(t);default:return L.execute(r.command,e,r.cwd)}}l(wC,"executeCommand");function SC(r){let e=r.args[0];if(e==="status")return{id:r.id,success:!0,exitCode:0,result:{running:!0,pid:process.pid,socketPath:Lt.socket(),uptime:Ee?Date.now()-Ee.startedAt:0,commandsServed:Ee?.commandsServed??0,lastActivity:Ee?new Date(Ee.lastActivity).toISOString():null,registeredCommands:L.list().length}};if(e==="stop"){let t={id:r.id,success:!0,exitCode:0,stdout:"Daemon stopping..."};return setTimeout(()=>pr(0),100),t}return{id:r.id,success:!1,exitCode:1,stderr:`Unknown daemon command: ${e}. Use: status, stop`}}l(SC,"handleDaemonCommand");function Rg(){Ee&&(Ee.idleTimer&&clearTimeout(Ee.idleTimer),Ee.idleTimer=setTimeout(()=>{console.log(`Daemon idle for ${Ee.idleTimeoutMs/1e3/60} minutes, shutting down`),pr(0)},Ee.idleTimeoutMs),Ee.idleTimer.unref&&Ee.idleTimer.unref())}l(Rg,"resetIdleTimer");function pr(r){console.log("Daemon shutting down..."),Ee?.idleTimer&&clearTimeout(Ee.idleTimer),dr&&(dr.stop(),dr=null),bs&&(bs.close(),bs=null);let e=Lt.socket(),t=Lt.pid();try{mt.existsSync(e)&&mt.unlinkSync(e)}catch{}try{mt.existsSync(t)&&mt.unlinkSync(t)}catch{}process.exit(r)}l(pr,"shutdown");function kC(r){try{return process.kill(r,0),!0}catch{return!1}}l(kC,"isProcessRunning");var gl=process.argv.slice(2),bC=parseInt(gl.find(r=>r.startsWith("--port="))?.split("=")[1]||"",10)||void 0,PC=gl.includes("--no-http"),CC=gl.includes("--foreground");Dg({port:bC,noHttp:PC,foreground:CC}).catch(r=>{console.error("Failed to start daemon:",r.message),process.exit(1)});
|