prjct-cli 1.25.0 → 1.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -1
- package/dist/bin/prjct-core.mjs +368 -364
- package/dist/daemon/entry.mjs +349 -345
- package/dist/templates.json +1 -1
- package/package.json +1 -1
package/dist/daemon/entry.mjs
CHANGED
|
@@ -3,12 +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 iu(r,t)}function Yf(r){return Jn.extname(r)}function Qf(r){return Jn.basename(r,Jn.extname(r))}var Ee=w(()=>{"use strict";ou();M();l(hn,"readJson");l(Fs,"writeJson");l(Wn,"readFile");l(iu,"writeFile");l(Uf,"atomicWrite");l(Hf,"appendToFile");l(_i,"appendLine");l(Gf,"prependToFile");l(D,"fileExists");l(Mr,"dirExists");l(Ye,"ensureDir");l(zf,"deleteFile");l(Jf,"deleteDir");l(Bn,"listFiles");l(Wf,"getFileSize");l(Bf,"getFileModifiedTime");l(Vf,"copyFile");l(qf,"moveFile");l(Kf,"readLines");l(Xf,"writeLines");l(Yf,"getFileExtension");l(Qf,"getFileNameWithoutExtension")});import{z as Dt}from"zod";function au(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 yx,wx,Sx,Os,kx,_s=w(()=>{"use strict";yx=Dt.enum(["opus","sonnet","haiku"]),wx=Dt.enum(["2.5-pro","2.5-flash","2.0-flash"]),Sx=Dt.string().min(1),Os=Dt.object({provider:Dt.string(),model:Dt.string(),cliVersion:Dt.string().optional(),recordedAt:Dt.string()}),kx=Dt.object({preferredModel:Dt.string().optional(),lastAnalysisModel:Os.optional()});l(au,"compareSemver")});import Ni from"node:fs/promises";import Zf from"node:os";import cu from"node:path";async function pu(){try{let r=await Ni.readFile(uu,"utf-8"),e=JSON.parse(r);return!e.timestamp||!e.detection||Date.now()-new Date(e.timestamp).getTime()>eh?null:e.detection}catch{return null}}async function du(r){let e={timestamp:new Date().toISOString(),detection:r};await Ni.mkdir(lu,{recursive:!0}),await Ni.writeFile(uu,JSON.stringify(e,null,2))}var lu,uu,eh,mu=w(()=>{"use strict";lu=cu.join(Zf.homedir(),".prjct-cli","cache"),uu=cu.join(lu,"providers.json"),eh=600*1e3;l(pu,"readProviderCache");l(du,"writeProviderCache")});var Qe={};fn(Qe,{AntigravityProvider:()=>Hi,ClaudeProvider:()=>Fr,CursorProvider:()=>hu,GeminiProvider:()=>Ui,Providers:()=>ft,WindsurfProvider:()=>yu,detectAllProviders:()=>Gi,detectAntigravity:()=>lh,detectCursorProject:()=>Su,detectProvider:()=>Li,detectWindsurfProject:()=>ku,getActiveProvider:()=>oh,getCommandsDir:()=>mh,getGlobalContextPath:()=>uh,getGlobalSettingsPath:()=>ph,getProjectCommandsPath:()=>gh,getProviderBranding:()=>Or,getSkillsPath:()=>dh,hasProviderConfig:()=>ih,needsCursorRouterRegeneration:()=>ah,needsWindsurfRouterRegeneration:()=>ch,selectProvider:()=>fh,validateCliVersion:()=>wu});import{exec as th}from"node:child_process";import Vn from"node:os";import Fe from"node:path";import{promisify as nh}from"node:util";async function sh(r){try{let{stdout:e}=await gu(`which ${r}`,{timeout:fu});return e.trim()}catch{return null}}async function rh(r){try{let{stdout:e}=await gu(`${r} --version`,{timeout:fu}),t=e.match(/\d+\.\d+\.\d+/);return t?t[0]:e.trim()}catch{return null}}async function Li(r){let e=ft[r];if(!e.cliCommand)return{installed:!1};let t=await sh(e.cliCommand);if(!t)return{installed:!1};let n=await rh(e.cliCommand),s=wu(r,n||void 0);return{installed:!0,version:n||void 0,path:t,versionWarning:s||void 0}}function wu(r,e){let t=ft[r];return!t.minCliVersion||!e?null:au(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 Gi(r=!1){if(!r){let s=await pu();if(s)return s}let[e,t]=await Promise.all([Li("claude"),Li("gemini")]),n={claude:e,gemini:t};return await du(n).catch(()=>{}),n}async function oh(r){if(r&&ft[r])return ft[r];let e=await Gi();return e.claude.installed&&!e.gemini.installed?Fr:e.gemini.installed&&!e.claude.installed?Ui:Fr}async function ih(r){let e=ft[r];return e.configDir?D(e.configDir):!1}function Or(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 Su(r){let e=Fe.join(r,".cursor"),t=Fe.join(e,"rules"),n=Fe.join(t,"prjct.mdc"),[s,o]=await Promise.all([D(e),D(n)]);return{detected:s,routerInstalled:o,projectRoot:s?r:void 0}}async function ah(r){let e=await Su(r);return e.detected&&!e.routerInstalled}async function ku(r){let e=Fe.join(r,".windsurf"),t=Fe.join(e,"rules"),n=Fe.join(t,"prjct.md"),[s,o]=await Promise.all([D(e),D(n)]);return{detected:s,routerInstalled:o,projectRoot:s?r:void 0}}async function ch(r){let e=await ku(r);return e.detected&&!e.routerInstalled}async function lh(){let r=Hi.configDir;if(!r)return{installed:!1,skillInstalled:!1};let e=Fe.join(r,"skills","prjct","SKILL.md"),[t,n]=await Promise.all([D(r),D(e)]);return{installed:t,skillInstalled:n,configPath:t?r:void 0}}function uh(r){let e=ft[r];return e.configDir?Fe.join(e.configDir,e.contextFile):null}function ph(r){let e=ft[r];return!e.configDir||!e.settingsFile?null:Fe.join(e.configDir,e.settingsFile)}function dh(r){return ft[r].skillsDir}function mh(r){return ft[r].commandsDir}function gh(r,e){let t=ft[r];return Fe.join(e,t.commandsDir)}async function fh(){let r=await Gi(),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 gu,fu,Fr,Ui,Hi,hu,yu,ft,ze=w(()=>{"use strict";_s();Ee();mu();gu=nh(th),fu=2e3,Fr={name:"claude",displayName:"Claude Code",cliCommand:"claude",configDir:Fe.join(Vn.homedir(),".claude"),contextFile:"CLAUDE.md",skillsDir:Fe.join(Vn.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"},Ui={name:"gemini",displayName:"Gemini CLI",cliCommand:"gemini",configDir:Fe.join(Vn.homedir(),".gemini"),contextFile:"GEMINI.md",skillsDir:Fe.join(Vn.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"},Hi={name:"antigravity",displayName:"Google Antigravity",cliCommand:null,configDir:Fe.join(Vn.homedir(),".gemini","antigravity"),contextFile:"ANTIGRAVITY.md",skillsDir:Fe.join(Vn.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},hu={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},yu={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},ft={claude:Fr,gemini:Ui,cursor:hu,antigravity:Hi,windsurf:yu};l(sh,"whichCommand");l(rh,"getCliVersion");l(Li,"detectProvider");l(wu,"validateCliVersion");l(Gi,"detectAllProviders");l(oh,"getActiveProvider");l(ih,"hasProviderConfig");l(Or,"getProviderBranding");l(Su,"detectCursorProject");l(ah,"needsCursorRouterRegeneration");l(ku,"detectWindsurfProject");l(ch,"needsWindsurfRouterRegeneration");l(lh,"detectAntigravity");l(uh,"getGlobalContextPath");l(ph,"getGlobalSettingsPath");l(dh,"getSkillsPath");l(mh,"getCommandsDir");l(gh,"getProjectCommandsPath");l(fh,"selectProvider")});import hh from"node:crypto";import Rt from"node:fs/promises";import zi from"node:os";import O from"node:path";import{globSync as yh}from"glob";var Ji,wh,P,K=w(()=>{"use strict";Q();Ee();Ji=class{static{l(this,"PathManager")}globalBaseDir;globalProjectsDir;globalConfigDir;constructor(){let e=process.env.PRJCT_CLI_HOME?.trim();this.globalBaseDir=e?O.resolve(e):O.join(zi.homedir(),".prjct-cli"),this.globalProjectsDir=O.join(this.globalBaseDir,"projects"),this.globalConfigDir=O.join(this.globalBaseDir,"config")}setGlobalBaseDir(e){this.globalBaseDir=O.resolve(e),this.globalProjectsDir=O.join(this.globalBaseDir,"projects"),this.globalConfigDir=O.join(this.globalBaseDir,"config")}generateProjectId(e){return hh.randomUUID()}getGlobalBasePath(){return this.globalBaseDir}getGlobalProjectPath(e){return O.join(this.globalProjectsDir,e)}getLocalConfigPath(e){return O.join(e,".prjct","prjct.config.json")}getGlobalProjectConfigPath(e){return O.join(this.getGlobalProjectPath(e),"project.json")}getLegacyPrjctPath(e){return O.join(e,".prjct")}async hasLegacyStructure(e){let t=this.getLegacyPrjctPath(e);return await Mr(t)}async hasConfig(e){let t=this.getLocalConfigPath(e);return await D(t)}async ensureGlobalStructure(){await Ye(this.globalBaseDir),await Ye(this.globalProjectsDir),await Ye(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 Ye(O.join(t,s));return await Ye(O.join(t,"planning","tasks")),await Ye(O.join(t,"sessions")),t}getSessionPath(e,t=new Date){let{year:n,month:s,day:o}=Oi(t);return O.join(this.getGlobalProjectPath(e),"sessions",n,s,o)}getCurrentSessionPath(e){return this.getSessionPath(e,new Date)}async ensureSessionPath(e,t=new Date){let n=this.getSessionPath(e,t);return await Ye(n),n}async listSessions(e,t=null,n=null){let s=O.join(this.getGlobalProjectPath(e),"sessions"),o=[];try{let i=await Rt.readdir(s,{withFileTypes:!0});for(let a of i){if(!a.isDirectory()||t&&a.name!==t.toString())continue;let c=O.join(s,a.name),u=await Rt.readdir(c,{withFileTypes:!0});for(let p of u){if(!p.isDirectory()||n&&p.name!==n.toString().padStart(2,"0"))continue;let m=O.join(c,p.name),d=await Rt.readdir(m,{withFileTypes:!0});for(let g of d)g.isDirectory()&&o.push({year:a.name,month:p.name,day:g.name,path:O.join(m,g.name),date:new Date(`${a.name}-${p.name}-${g.name}`)})}}return o.sort((a,c)=>c.date.getTime()-a.date.getTime()),o}catch{return[]}}async getSessionsInRange(e,t,n=new Date){return(await this.listSessions(e)).filter(o=>o.date>=t&&o.date<=n)}getFilePath(e,t,n){return O.join(this.getGlobalProjectPath(e),t,n)}async listProjects(){try{return await this.ensureGlobalStructure(),(await Rt.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 Mr(t)}getDisplayPath(e){let t=zi.homedir();return e.startsWith(t)?e.replace(t,"~"):e}getAuthConfigPath(){return O.join(this.globalConfigDir,"auth.json")}getSyncPendingPath(e){return O.join(this.getGlobalProjectPath(e),"sync","pending.json")}getLastSyncPath(e){return O.join(this.getGlobalProjectPath(e),"sync","last-sync.json")}getRunningStatusPath(){return O.join(this.globalBaseDir,".running")}getDocsPath(){return O.join(this.globalBaseDir,"docs")}async getAgentDir(){return(await(ze(),ot(Qe)).getActiveProvider()).configDir}async getAgentSettingsPath(){let e=await(ze(),ot(Qe)).getActiveProvider();return(ze(),ot(Qe)).getGlobalSettingsPath(e.name)}getClaudeDir(){return O.join(zi.homedir(),".claude")}getClaudeSettingsPath(){return O.join(this.getClaudeDir(),"settings.json")}getAgentsPath(e){return e?O.join(this.getGlobalProjectPath(e),"agents"):O.join(this.globalBaseDir,"agents")}getStoragePath(e,t){return O.join(this.getGlobalProjectPath(e),"storage",t)}getContextPath(e){return O.join(this.getGlobalProjectPath(e),"context")}async detectMonorepo(e){let t={isMonorepo:!1,type:null,rootPath:e,packages:[]},n=[{file:"pnpm-workspace.yaml",type:"pnpm"},{file:"lerna.json",type:"lerna"},{file:"nx.json",type:"nx"},{file:"rush.json",type:"rush"},{file:"turbo.json",type:"turborepo"}];for(let s of n){let o=O.join(e,s.file);if(await D(o)){t.isMonorepo=!0,t.type=s.type;break}}if(!t.isMonorepo){let s=O.join(e,"package.json");if(await D(s))try{let o=await Rt.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 Rt.readFile(O.join(e,"pnpm-workspace.yaml"),"utf-8")).match(/packages:\s*\n((?:\s*-\s*.+\n?)+)/);i&&(s=i[1].split(`
|
|
10
|
-
`).map(a=>a.replace(/^\s*-\s*['"]?|['"]?\s*$/g,"")).filter(Boolean))}else if(t==="npm"||t==="lerna"){let o=O.join(e,"package.json"),i=await Rt.readFile(o,"utf-8"),a=JSON.parse(i);if(Array.isArray(a.workspaces)?s=a.workspaces:a.workspaces?.packages&&(s=a.workspaces.packages),t==="lerna"){let c=O.join(e,"lerna.json");if(await D(c)){let u=await Rt.readFile(c,"utf-8"),p=JSON.parse(u);p.packages&&(s=p.packages)}}}else if(t==="nx")s=["apps/*","libs/*","packages/*"];else if(t==="turborepo"){let o=O.join(e,"package.json"),i=await Rt.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=yh(o,{cwd:e,absolute:!1});for(let a of i){let c=O.join(e,a),u=O.join(c,"package.json");if(await D(u))try{let p=await Rt.readFile(u,"utf-8"),m=JSON.parse(p),d=O.join(c,"PRJCT.md");n.push({name:m.name||O.basename(a),path:c,relativePath:a,hasPrjctMd:await D(d)})}catch{}}}}catch{}return n}async findContainingPackage(e,t){if(!t.isMonorepo)return null;let n=O.resolve(e);for(let s of t.packages){let o=O.resolve(s.path);if(n.startsWith(o))return s}return null}async findMonorepoRoot(e){let t=O.resolve(e),n=O.parse(t).root;for(;t!==n;){if((await this.detectMonorepo(t)).isMonorepo)return t;t=O.dirname(t)}return null}},wh=new Ji,P=wh});import Ns from"node:fs/promises";import tn from"node:path";import{z as te}from"zod";async function Ch(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=tn.join(e,"package.json"),s=await Ns.readFile(n,"utf-8"),o=JSON.parse(s),i={...o.dependencies,...o.devDependencies},a=[],c=[];for(let u of r.frameworks){let p=u.toLowerCase();Object.keys(i).some(d=>d.toLowerCase().includes(p))?c.push(u):a.push(u)}return a.length===0?{name:"Framework verification",passed:!0,output:`${c.length} framework(s) verified in dependencies`,durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Frameworks not found in dependencies: ${a.join(", ")}`,durationMs:Date.now()-t}}catch(n){return S(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 vh(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 Ah(e),s=new Set(n),o=[],i=[];for(let a of r.languages){let c=Ph[a];if(!c)continue;c.some(p=>s.has(p))?o.push(a):i.push(a)}return i.length===0?{name:"Language verification",passed:!0,output:`${o.length} language(s) verified with matching files`,durationMs:Date.now()-t}:{name:"Language verification",passed:!1,error:`Languages without matching files: ${i.join(", ")}`,durationMs:Date.now()-t}}catch(n){return{name:"Language verification",passed:!1,error:`Failed to scan project files: ${n instanceof Error?n.message:"unknown error"}`,durationMs:Date.now()-t}}}async function xh(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=tn.join(e,a);try{await Ns.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 Th(r,e){let t=Date.now();try{let n=await Ih(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 Eh(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=tn.join(e,o.file);try{await Ns.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 bu(r,e){let t=Date.now(),n=await Promise.all([Ch(r,e),vh(r,e),xh(r,e),Th(r,e),Eh(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 Ah(r){let e=new Set,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function n(s){try{let o=await Ns.readdir(s,{withFileTypes:!0});for(let i of o){let a=tn.join(s,i.name),c=tn.relative(r,a);if(!t.some(u=>u.test(c))){if(i.isDirectory())await n(a);else if(i.isFile()){let u=tn.extname(i.name);u&&e.add(u)}}}}catch{}}return l(n,"scanDir"),await n(r),Array.from(e)}async function Ih(r){let e=0,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function n(s){try{let o=await Ns.readdir(s,{withFileTypes:!0});for(let i of o){let a=tn.join(s,i.name),c=tn.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 Sh,kh,bh,Wi,qx,Ph,Bi=w(()=>{"use strict";M();_s();Sh=te.enum(["draft","verified","sealed"]),kh=te.object({name:te.string(),description:te.string(),location:te.string().optional()}),bh=te.object({issue:te.string(),file:te.string(),suggestion:te.string()}),Wi=te.object({projectId:te.string(),languages:te.array(te.string()),frameworks:te.array(te.string()),packageManager:te.string().optional(),sourceDir:te.string().optional(),testDir:te.string().optional(),configFiles:te.array(te.string()),fileCount:te.number(),patterns:te.array(kh),antiPatterns:te.array(bh),analyzedAt:te.string(),modelMetadata:Os.optional(),status:Sh.default("draft"),commitHash:te.string().optional(),signature:te.string().optional(),sealedAt:te.string().optional(),verifiedAt:te.string().optional()}),qx={languages:[],frameworks:[],configFiles:[],fileCount:0,patterns:[],antiPatterns:[],analyzedAt:new Date().toISOString(),status:"draft"},Ph={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(Ch,"verifyFrameworks");l(vh,"verifyLanguages");l(xh,"verifyPatternLocations");l(Th,"verifyFileCount");l(Eh,"verifyAntiPatternFiles");l(bu,"semanticVerify");l(Ah,"getProjectExtensions");l(Ih,"countProjectFiles")});import{z as oe}from"zod";function jh(r){return r instanceof qn}function V(r){return jh(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var Kn,Qx,Zx,eT,tT,nT,sT,qn,_r,Nr,Ls,zt=w(()=>{"use strict";Kn={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}},Qx=Kn.create("FileError",oe.object({path:oe.string(),operation:oe.enum(["read","write","delete","create","copy"]),reason:oe.string().optional()})),Zx=Kn.create("ValidationError",oe.object({field:oe.string(),expected:oe.string(),received:oe.string().optional(),message:oe.string().optional()})),eT=Kn.create("PermissionError",oe.object({action:oe.string(),resource:oe.string(),reason:oe.string().optional()})),tT=Kn.create("TaskError",oe.object({taskId:oe.string().optional(),operation:oe.enum(["create","update","complete","pause","resume","delete"]),reason:oe.string()})),nT=Kn.create("SessionError",oe.object({sessionId:oe.string().optional(),reason:oe.string()})),sT=Kn.create("SyncError",oe.object({projectId:oe.string().optional(),operation:oe.enum(["push","pull","auth","connect"]),reason:oe.string()})),qn=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)}},_r=class r extends qn{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")}},Nr=class r extends qn{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")}},Ls=class r extends qn{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(jh,"isPrjctError");l(V,"getErrorMessage")});function Ur(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 Dh[r]}var q,Vi,qi,Lr,Dh,ht,Us,Pu,Hs,Jt=w(()=>{"use strict";q={GATHERING:"gathering",ANALYZING:"analyzing",PROPOSING:"proposing",PENDING_APPROVAL:"awaiting_approval",APPROVED:"approved",REJECTED:"rejected",EXECUTING:"executing",COMPLETED:"completed",ABORTED:"aborted"},Vi=["feature","spec","design","refactor","migrate"],qi=["ship","cleanup","git","migrate"],Lr=["Read","Glob","Grep","GetTimestamp","GetDate","GetDateTime"],Dh={TOOL_CHECK:5e3,GIT_OPERATION:1e4,GIT_CLONE:6e4,API_REQUEST:3e4,NPM_INSTALL:12e4,WORKFLOW_HOOK:6e4};l(Ur,"getTimeout");ht={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},Us={JSONL_MAX_LINES:1e3,ROTATION_SIZE_MB:10,LARGE_FILE_WARN_MB:50},Pu={HISTORY_MAX:100},Hs={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 $h(){let r=process.env.PRJCT_DEBUG||process.env.DEBUG||"";if(!r)return{level:-1,name:"disabled"};if(Rh.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 Hr(r,e,t){return Cu>=r?(...n)=>console[t](e,...n):Fh}var Xn,Rh,Cu,Mh,Fh,Oh,H,Yn=w(()=>{"use strict";Xn={error:0,warn:1,info:2,debug:3},Rh=new Set(["1","true","*"]);l($h,"getLogLevel");({level:Cu,name:Mh}=$h()),Fh=l(()=>{},"noop");l(Hr,"createLogMethod");Oh={error:Hr(Xn.error,"[prjct:error]","error"),warn:Hr(Xn.warn,"[prjct:warn]","warn"),info:Hr(Xn.info,"[prjct:info]","log"),debug:Hr(Xn.debug,"[prjct:debug]","log"),isEnabled:l(()=>Cu>=0,"isEnabled"),level:l(()=>Mh,"level")},H=Oh});import vu from"node:fs/promises";import xu from"node:path";var Gr,_h,Tu=w(()=>{"use strict";zt();K();Fi();Jt();Yn();Gr=class{static{l(this,"EventBus")}listeners;onceListeners;history;historyLimit;projectId;constructor(){this.listeners=new Map,this.onceListeners=new Map,this.history=[],this.historyLimit=Pu.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"&&H.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(Ir.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(Ir.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 H.error("Event callback error:",n),n}}async logEvent(e){try{let t=P.getGlobalProjectPath(this.projectId),n=xu.join(t,"memory","events.jsonl");await vu.mkdir(xu.dirname(n),{recursive:!0});let s=`${JSON.stringify(e)}
|
|
11
|
-
`;await vu.appendFile(n,s)}catch(t){H.debug("Failed to log event:",V(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())}},_h=new Gr});function Jr(r,e){let t=r[0];return e==="delete"?`${t}.deleted`:`${t}.updated`}var zr,Qn,Eu=w(()=>{"use strict";K();Q();Ee();l(Jr,"inferEventType");zr=class{static{l(this,"SyncEventBus")}async publish(e){let t=P.getSyncPendingPath(e.projectId),n=await hn(t,[])??[];n.push(e),await Fs(t,n)}async getPending(e){let t=P.getSyncPendingPath(e);return await hn(t,[])??[]}async clearPending(e){let t=P.getSyncPendingPath(e);await Fs(t,[])}async updateLastSync(e){let t=P.getLastSyncPath(e),n={timestamp:b(),success:!0};await Fs(t,n)}async getLastSync(e){let t=P.getLastSyncPath(e);return await hn(t,null)}},Qn=new zr});var Ki=w(()=>{"use strict";Tu();Eu()});var yt,Wr=w(()=>{"use strict";yt=class{static{l(this,"TTLCache")}cache=new Map;ttl;maxSize;constructor(e={}){this.ttl=e.ttl??5e3,this.maxSize=e.maxSize??50}isValid(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp<this.ttl:!1}get(e){let t=this.cache.get(e);return t?this.isValid(e)?t.data:(this.cache.delete(e),null):null}set(e,t){this.cache.set(e,{data:t,timestamp:Date.now()}),this.evictOldEntries()}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}has(e){return this.cache.has(e)}get size(){return this.cache.size}evictOldEntries(){if(this.cache.size<=this.maxSize)return;let t=Array.from(this.cache.entries()).sort((n,s)=>n[1].timestamp-s[1].timestamp).slice(0,this.cache.size-this.maxSize);for(let[n]of t)this.cache.delete(n)}stats(){return{size:this.cache.size,maxSize:this.maxSize,ttl:this.ttl}}prune(){let e=0;for(let t of this.cache.keys())this.isValid(t)||(this.cache.delete(t),e++);return e}}});import{Database as Nh}from"bun:sqlite";import Xi from"node:fs";import Au from"node:path";var Lh,Br,F,it,at=w(()=>{"use strict";K();Lh=[{version:1,name:"initial-schema",up:l(r=>{r.run(`
|
|
6
|
+
var vr=Object.defineProperty;var nf=Object.getOwnPropertyDescriptor;var sf=Object.getOwnPropertyNames;var rf=Object.prototype.hasOwnProperty;var l=(r,e)=>vr(r,"name",{value:e,configurable:!0}),xi=(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')}),$l=r=>e=>{var t=r[e];if(t)return t();throw new Error("Module not found in bundle: "+e)};var y=(r,e)=>()=>(r&&(e=r(r=0)),e);var Ln=(r,e)=>{for(var t in e)vr(r,t,{get:e[t],enumerable:!0})},of=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of sf(e))!rf.call(r,s)&&s!==t&&vr(r,s,{get:()=>e[s],enumerable:!(n=nf(e,s))||n.enumerable});return r};var ut=r=>of(vr({},"__esModule",{value:!0}),r);var Ml=y(()=>{"use strict"});var xr,Fl=y(()=>{"use strict";xr={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 Fs,Tr=y(()=>{"use strict";Fs={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 Ol(r){return r instanceof Error&&"code"in r}function C(r){return Ol(r)&&r.code==="ENOENT"}function w(r){return r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var F=y(()=>{"use strict";l(Ol,"isNodeError");l(C,"isNotFoundError");l(w,"getErrorMessage")});var _l=y(()=>{"use strict"});var Nl=y(()=>{"use strict";_l()});function Er(r,e=!1){return e||r>=6?"high":r>=3?"medium":"low"}var j,Ll,Un=y(()=>{"use strict";j={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"},Ll=["frontend","backend","devops","docs","testing","database","general"];l(Er,"calculateConfidence")});var Ti=y(()=>{"use strict"});var Ei=y(()=>{"use strict";Ml();Fl();Tr();F();Nl();Un();Ti()});var L={};Ln(L,{calculateDuration:()=>wf,formatDate:()=>Ar,formatDuration:()=>Os,formatMonth:()=>df,getDateKey:()=>pf,getDateRange:()=>ff,getDaysAgo:()=>Yt,getDaysFromNow:()=>gf,getEndOfDay:()=>kf,getStartOfDay:()=>Sf,getTimestamp:()=>b,getTodayKey:()=>Ul,getYearMonthDay:()=>Ai,isToday:()=>hf,isWithinLastDays:()=>yf,parseDate:()=>mf,toRelative:()=>nt});import{formatDistanceToNowStrict as uf}from"date-fns";function Ar(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 df(r){let e=r.getFullYear(),t=(r.getMonth()+1).toString().padStart(2,"0");return`${e}-${t}`}function Ul(){return Ar(new Date)}function pf(r){return Ar(r)}function Ai(r){return{year:r.getFullYear().toString(),month:(r.getMonth()+1).toString().padStart(2,"0"),day:r.getDate().toString().padStart(2,"0")}}function mf(r){return new Date(r)}function b(){return new Date().toISOString()}function Yt(r){let e=new Date;return e.setDate(e.getDate()-r),e}function gf(r){let e=new Date;return e.setDate(e.getDate()+r),e}function ff(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 hf(r){return Ar(r)===Ul()}function yf(r,e){let t=Yt(e);return r>=t}function Os(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 wf(r,e=new Date){let t=e.getTime()-r.getTime();return Os(t)}function Sf(r){let e=new Date(r);return e.setHours(0,0,0,0),e}function kf(r){let e=new Date(r);return e.setHours(23,59,59,999),e}function nt(r){let e=typeof r=="string"?new Date(r):r;return uf(e,{addSuffix:!0})}var te=y(()=>{"use strict";l(Ar,"formatDate");l(df,"formatMonth");l(Ul,"getTodayKey");l(pf,"getDateKey");l(Ai,"getYearMonthDay");l(mf,"parseDate");l(b,"getTimestamp");l(Yt,"getDaysAgo");l(gf,"getDaysFromNow");l(ff,"getDateRange");l(hf,"isToday");l(yf,"isWithinLastDays");l(Os,"formatDuration");l(wf,"calculateDuration");l(Sf,"getStartOfDay");l(kf,"getEndOfDay");l(nt,"toRelative")});import zl from"node:fs/promises";async function Wl(r,e){let t;try{t=await zl.readFile(r,"utf-8")}catch(o){if(C(o))return null;throw o}let n;try{n=JSON.parse(t)}catch{return await Hl(r,t),Gl(r,"Malformed JSON"),null}let s=e.safeParse(n);return s.success?n:(await Hl(r,t),Gl(r,bf(s.error)),null)}async function Hl(r,e){let t=`${r}.backup`;try{await zl.writeFile(t,e,"utf-8")}catch{}}function Gl(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 bf(r){return r.issues.slice(0,3).map(e=>`${e.path.join(".")}: ${e.message}`).join("; ")}var Bl=y(()=>{"use strict";F();l(Wl,"safeRead");l(Hl,"createBackup");l(Gl,"logCorruption");l(bf,"formatZodError")});var ne={};Ln(ne,{appendLine:()=>Ii,appendToFile:()=>Cf,atomicWrite:()=>Pf,copyFile:()=>If,deleteDir:()=>Tf,deleteFile:()=>xf,dirExists:()=>Ir,ensureDir:()=>yt,fileExists:()=>$,getFileExtension:()=>$f,getFileModifiedTime:()=>Af,getFileNameWithoutExtension:()=>Mf,getFileSize:()=>Ef,listFiles:()=>zn,moveFile:()=>Df,prependToFile:()=>vf,readFile:()=>Gn,readJson:()=>pn,readLines:()=>jf,writeFile:()=>Vl,writeJson:()=>_s,writeLines:()=>Rf});import oe from"node:fs/promises";import Hn from"node:path";async function pn(r,e=null,t){if(t)return await Wl(r,t)??e;try{let n=await oe.readFile(r,"utf-8");return JSON.parse(n)}catch(n){if(C(n))return e;throw n}}async function _s(r,e,t=2){let n=JSON.stringify(e,null,t);await oe.writeFile(r,n,"utf-8")}async function Gn(r,e=""){try{return await oe.readFile(r,"utf-8")}catch(t){if(C(t))return e;throw t}}async function Vl(r,e){let t=Hn.dirname(r);await oe.mkdir(t,{recursive:!0}),await oe.writeFile(r,e,"utf-8")}async function Pf(r,e){let t=Hn.dirname(r);await oe.mkdir(t,{recursive:!0});let n=`${r}.${Date.now()}.tmp`;await oe.writeFile(n,e,"utf-8"),await oe.rename(n,r)}async function Cf(r,e){await oe.appendFile(r,e,"utf-8")}async function Ii(r,e){let t=Hn.dirname(r);await oe.mkdir(t,{recursive:!0}),await oe.appendFile(r,`${e}
|
|
7
|
+
`,"utf-8")}async function vf(r,e){try{let t=await oe.readFile(r,"utf-8");await oe.writeFile(r,e+t,"utf-8")}catch(t){if(C(t))await oe.writeFile(r,e,"utf-8");else throw t}}async function $(r){try{return await oe.access(r),!0}catch(e){if(C(e))return!1;throw e}}async function Ir(r){try{return(await oe.stat(r)).isDirectory()}catch(e){if(C(e))return!1;throw e}}async function yt(r){await oe.mkdir(r,{recursive:!0})}async function xf(r){try{return await oe.unlink(r),!0}catch(e){if(C(e))return!1;throw e}}async function Tf(r){try{return await oe.rm(r,{recursive:!0,force:!0}),!0}catch(e){if(C(e))return!1;throw e}}async function zn(r,e={}){try{let n=await oe.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 Ef(r){return(await oe.stat(r)).size}async function Af(r){return(await oe.stat(r)).mtime}async function If(r,e){await oe.copyFile(r,e)}async function Df(r,e){await oe.rename(r,e)}async function jf(r){return(await Gn(r,"")).split(`
|
|
8
|
+
`)}async function Rf(r,e){let t=e.join(`
|
|
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(`
|
|
12
11
|
-- =======================================================================
|
|
13
12
|
-- Document storage (backward-compatible with JSON file pattern)
|
|
14
13
|
-- =======================================================================
|
|
@@ -239,14 +238,14 @@ var Ar=Object.defineProperty;var bf=Object.getOwnPropertyDescriptor;var Pf=Objec
|
|
|
239
238
|
CREATE INDEX idx_archives_entity_type ON archives(entity_type);
|
|
240
239
|
CREATE INDEX idx_archives_archived_at ON archives(archived_at);
|
|
241
240
|
CREATE INDEX idx_archives_entity_id ON archives(entity_id);
|
|
242
|
-
`)},"up")}],
|
|
241
|
+
`)},"up")}],Mr=class{static{l(this,"PrjctDatabase")}connections=new Map;getDbPath(e){return cu.join(T.getGlobalProjectPath(e),"prjct.db")}getDb(e){let t=this.connections.get(e);if(t)return t;let n=this.getDbPath(e),s=cu.dirname(n);Li.existsSync(s)||Li.mkdirSync(s,{recursive:!0});let o=new mh(n,{create:!0});return o.run("PRAGMA journal_mode = WAL"),o.run("PRAGMA synchronous = NORMAL"),o.run("PRAGMA cache_size = -2000"),o.run("PRAGMA temp_store = MEMORY"),o.run("PRAGMA mmap_size = 268435456"),this.runMigrations(o),this.connections.set(e,o),o}close(e){if(e){let t=this.connections.get(e);t&&(t.close(),this.connections.delete(e))}else this.connections.forEach(t=>{t.close()}),this.connections.clear()}exists(e){return Li.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(`
|
|
243
242
|
CREATE TABLE IF NOT EXISTS _migrations (
|
|
244
243
|
version INTEGER PRIMARY KEY,
|
|
245
244
|
name TEXT NOT NULL,
|
|
246
245
|
applied_at TEXT NOT NULL
|
|
247
246
|
)
|
|
248
|
-
`);let t=new Set(e.prepare("SELECT version FROM _migrations").all().map(n=>n.version));for(let n of
|
|
249
|
-
`)}async saveDraft(e,t){let n={...t,status:"draft"};
|
|
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
|
|
250
249
|
|
|
251
250
|
Return ONLY valid JSON matching this schema (no markdown, no explanation):
|
|
252
251
|
|
|
@@ -255,11 +254,11 @@ ${e.example}
|
|
|
255
254
|
\`\`\`
|
|
256
255
|
|
|
257
256
|
Fields:
|
|
258
|
-
${
|
|
259
|
-
`)}return"(see example above)"}function Lu(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 ${Lu(r.element)}`:r instanceof Ae.ZodObject?"object":"any"}var Ou,_u,Nu,Kr=w(()=>{"use strict";Gs();Gs();Ou=Ae.object({agentName:Ae.string(),reasoning:Ae.string(),confidence:Ae.number().min(0).max(1)}),_u=Ae.object({subtasks:Ae.array(Ae.object({description:Ae.string(),domain:qr,agent:Ae.string(),dependsOn:Ae.array(Ae.number())})),effort:Ae.enum(["low","medium","high"])}),Nu={classification:{schema:nn,example:JSON.stringify({primaryDomain:"backend",secondaryDomains:["database"],confidence:.9,filePatterns:["src/api/**"],relevantAgents:["backend.md"]},null,2)},agentAssignment:{schema:Ou,example:JSON.stringify({agentName:"backend.md",reasoning:"Task involves API endpoint creation",confidence:.85},null,2)},subtaskBreakdown:{schema:_u,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(ta,"renderSchemaForPrompt");l(ey,"describeSchema");l(Lu,"describeField")});import{z as E}from"zod";var Hu,ty,ny,Gu,sy,ry,oy,iy,ay,cy,ly,zu,uy,py,gE,Ju,Wu,Bu,Vu,dy,Xr,na=w(()=>{"use strict";Hu=E.number().min(1).max(5),ty=E.enum(["exceeded","met","partial","failed"]),ny=E.enum(["definitely","probably","maybe","no"]),Gu=E.enum(["scope_creep","underestimated_complexity","technical_debt","external_blockers","learning_curve","requirements_changed","optimistic_estimate","team_changes","other"]),sy=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:Gu.optional(),explanation:E.string().optional()})}),ry=E.object({name:E.string(),baseline:E.number().nullable(),target:E.number(),actual:E.number(),unit:E.string(),achieved:E.boolean(),percentOfTarget:E.number()}),oy=E.object({criteria:E.string(),met:E.boolean(),notes:E.string().optional()}),iy=E.object({metrics:E.array(ry),acceptanceCriteria:E.array(oy),overallSuccess:ty,successScore:E.number().min(0).max(100)}),ay=E.object({category:E.enum(["estimation","technical","process","communication","tooling","architecture","testing","other"]),insight:E.string(),actionable:E.boolean(),action:E.string().optional()}),cy=E.object({whatWorked:E.array(E.string()),whatDidnt:E.array(E.string()),surprises:E.array(E.string()),recommendations:E.array(ay)}),ly=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:ny,worthItReason:E.string().optional(),alternativeConsidered:E.string().optional(),betterAlternativeExists:E.boolean().optional()}),zu=E.object({id:E.string(),taskId:E.string(),description:E.string(),estimatedMinutes:E.number().optional(),actualMinutes:E.number(),completedAsPlanned:E.boolean(),qualityScore:Hu,blockers:E.array(E.string()),agentUsed:E.string().optional(),skillsUsed:E.array(E.string()).optional(),startedAt:E.string(),completedAt:E.string()}),uy=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:sy,success:iy.optional(),learnings:cy,roi:ly,rating:Hu,taskOutcomes:E.array(zu).optional(),startedAt:E.string(),shippedAt:E.string(),reviewedAt:E.string().optional(),reviewedBy:E.string().optional(),legacy:E.boolean().optional()}),py=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:Gu,count:E.number(),averageVariance:E.number()})),topLearnings:E.array(E.object({insight:E.string(),frequency:E.number()}))}),gE=E.object({outcomes:E.array(uy),taskOutcomes:E.array(zu).optional(),aggregates:py.optional(),lastUpdated:E.string(),lastAggregated:E.string().optional()}),Ju={outcomes:[],taskOutcomes:[],lastUpdated:""},Wu=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"),Bu=l((r,e)=>e<=0?r*10:Math.round(r*10/e*100)/100,"calculateROIScore"),Vu=l(r=>r>=100?"exceeded":r>=80?"met":r>=50?"partial":"failed","determineSuccessLevel"),dy=l(r=>Math.max(0,100-Math.abs(r)),"calculateEstimationAccuracy"),Xr=l(r=>{if(r.length===0)return{totalFeatures:0,averageEstimationAccuracy:0,averageSuccessRate:0,averageROI:0,bySuccessLevel:{exceeded:0,met:0,partial:0,failed:0},variancePatterns:[],topLearnings:[]};let e=r.map(p=>dy(p.effort.variance.percentage)),t=r.filter(p=>p.success).map(p=>p.success.successScore),n=r.map(p=>p.roi.roiScore),s={exceeded:r.filter(p=>p.success?.overallSuccess==="exceeded").length,met:r.filter(p=>p.success?.overallSuccess==="met").length,partial:r.filter(p=>p.success?.overallSuccess==="partial").length,failed:r.filter(p=>p.success?.overallSuccess==="failed").length},o=r.filter(p=>p.effort.variance.reason).reduce((p,m)=>{let d=m.effort.variance.reason;return p[d]||(p[d]={count:0,totalVariance:0}),p[d].count++,p[d].totalVariance+=m.effort.variance.percentage,p},{}),i=Object.entries(o).map(([p,m])=>({reason:p,count:m.count,averageVariance:Math.round(m.totalVariance/m.count)})),c=r.flatMap(p=>[...p.learnings.whatWorked,...p.learnings.whatDidnt]).reduce((p,m)=>(p[m]=(p[m]||0)+1,p),{}),u=Object.entries(c).sort((p,m)=>m[1]-p[1]).slice(0,10).map(([p,m])=>({insight:p,frequency:m}));return{totalFeatures:r.length,averageEstimationAccuracy:Math.round(e.reduce((p,m)=>p+m,0)/e.length),averageSuccessRate:t.length>0?Math.round(t.reduce((p,m)=>p+m,0)/t.length):0,averageROI:Math.round(n.reduce((p,m)=>p+m,0)/n.length*100)/100,bySuccessLevel:s,variancePatterns:i,topLearnings:u}},"aggregateOutcomes")});import{z as ve}from"zod";function wy(){let r={};for(let e of fy)r[e]="allow";for(let e of hy)r[e]="ask";for(let e of yy)r[e]="deny";return{bash:r,files:{read:{"**/*":"allow"},write:{"**/*":"allow"},delete:{"**/*":"ask"}},web:{enabled:!0},doomLoop:{enabled:!0,maxRetries:3},externalDirectories:"ask"}}var Yr,wE,my,sa,gy,SE,fy,hy,yy,kE,qu=w(()=>{"use strict";Yr=ve.enum(["allow","deny","ask"]),wE=ve.enum(["read","write","delete","create"]),my=ve.record(ve.string(),Yr),sa=ve.record(ve.string(),Yr),gy=ve.object({enabled:ve.boolean().default(!0),allowedDomains:ve.array(ve.string()).optional(),blockedDomains:ve.array(ve.string()).optional()}),SE=ve.object({bash:my.optional(),files:ve.object({read:sa.optional(),write:sa.optional(),delete:sa.optional()}).optional(),web:gy.optional(),skills:ve.record(ve.string(),Yr).optional(),doomLoop:ve.object({enabled:ve.boolean().default(!0),maxRetries:ve.number().default(3)}).optional(),externalDirectories:Yr.default("ask")}),fy=["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*"],hy=["rm -rf*","rm -r*","git push*","git reset --hard*","git clean*","npm publish*","chmod*","chown*","sudo*","curl*|*sh","wget*|*sh"],yy=["rm -rf /*","rm -rf ~/*",":(){ :|:& };:*","mkfs*","dd if=*of=/dev/*"];l(wy,"buildDefaultPermissions");kE=wy()});import{z as Le}from"zod";var vE,xE,Ku=w(()=>{"use strict";vE=Le.object({projectId:Le.string(),name:Le.string(),repoPath:Le.string(),description:Le.string().optional(),version:Le.string().optional(),cliVersion:Le.string().optional(),techStack:Le.array(Le.string()),fileCount:Le.number(),commitCount:Le.number(),createdAt:Le.string(),lastSync:Le.string(),lastSyncCommit:Le.string().optional(),lastSyncBranch:Le.string().optional()}),xE={techStack:[],fileCount:0,commitCount:0,createdAt:new Date().toISOString(),lastSync:new Date().toISOString()}});import{z as A}from"zod";var Sy,ky,by,Py,Cy,vy,xy,Ty,Ey,Ay,Iy,jy,Dy,Ry,$y,My,Fy,Oy,IE,jE,Xu=w(()=>{"use strict";Sy=A.enum(["planned","active","completed","shipped"]),ky=A.enum(["low","medium","high"]),by=A.enum(["feature","breaking_change","refactor","infrastructure"]),Py=A.enum(["completed","active","planned"]),Cy=A.enum(["planned","active","completed"]),vy=A.enum(["git","git-branch","manual","prd"]),xy=A.object({id:A.string(),description:A.string(),completed:A.boolean(),completedAt:A.string().optional()}),Ty=A.object({id:A.string(),name:A.string(),status:Py,completedAt:A.string().optional()}),Ey=A.object({goal:A.string(),phases:A.array(Ty),successMetrics:A.array(A.string()).optional()}),Ay=A.object({hours:A.number(),minutes:A.number(),totalMinutes:A.number(),display:A.string().optional()}),Iy=A.object({hash:A.string(),message:A.string(),date:A.string(),author:A.string().optional()}),jy=A.object({hours:A.number(),confidence:A.enum(["low","medium","high"]).optional(),breakdown:A.array(A.object({area:A.string(),hours:A.number()})).optional()}),Dy=A.object({hours:A.number().optional(),commits:A.number().optional(),linesAdded:A.number().optional(),linesRemoved:A.number().optional()}),Ry=A.object({estimated:jy.nullable(),actual:Dy.nullable()}),$y=A.object({totalHours:A.number(),allocatedHours:A.number(),bufferPercent:A.number().optional()}),My=A.object({id:A.string(),name:A.string(),theme:A.string().optional(),goals:A.array(A.string()).optional(),features:A.array(A.string()),capacity:$y.optional(),status:Cy,startDate:A.string().optional(),endDate:A.string().optional()}),Fy=A.object({id:A.string(),name:A.string(),description:A.string().optional(),date:A.string(),status:Sy,impact:ky,effort:A.string().optional(),progress:A.number(),type:by.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(xy),createdAt:A.string(),shippedAt:A.string().optional(),version:A.string().optional(),duration:Ay.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:vy.optional(),quarter:A.string().nullable().optional(),dependencies:A.array(A.string()).optional(),blockedBy:A.array(A.string()).optional(),effortTracking:Ry.optional(),valueScore:A.number().optional(),commits:A.array(Iy).optional(),branch:A.string().optional(),commitsAhead:A.number().optional()}),Oy=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()}),IE=A.object({strategy:Ey.nullable().optional(),features:A.array(Fy),backlog:A.array(A.union([A.string(),Oy])),lastUpdated:A.string(),quarters:A.array(My).optional(),generatedFrom:A.enum(["git-history","manual","prd"]).optional(),generatedAt:A.string().optional()}),jE={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 _y from"node:crypto";import{homedir as Ny}from"node:os";import{join as Ly}from"node:path";function ie(){return _y.randomUUID()}var Uy,Yu=w(()=>{"use strict";l(ie,"generateUUID");Uy=Ly(Ny(),".prjct-cli","projects")});import{z as W}from"zod";var Hy,Qu,Gy,zy,Jy,Wy,By,Vy,qy,Zu,ra=w(()=>{"use strict";Hy=W.enum(["feature","fix","improvement","refactor"]),Qu=W.enum(["pass","warning","fail","skipped"]),Gy=W.enum(["added","changed","fixed","removed"]),zy=W.object({hours:W.number(),minutes:W.number(),totalMinutes:W.number()}),Jy=W.object({filesChanged:W.number().nullable().optional(),linesAdded:W.number().nullable().optional(),linesRemoved:W.number().nullable().optional(),commits:W.number().nullable().optional()}),Wy=W.object({description:W.string(),type:Gy.optional()}),By=W.object({lintStatus:Qu.nullable().optional(),lintDetails:W.string().optional(),testStatus:Qu.nullable().optional(),testDetails:W.string().optional()}),Vy=W.object({hash:W.string().optional(),message:W.string().optional(),branch:W.string().optional()}),qy=W.object({id:W.string(),name:W.string(),version:W.string().nullable().optional(),type:Hy,agent:W.string().optional(),description:W.string().optional(),changes:W.array(Wy).optional(),codeSnippets:W.array(W.string()).optional(),commit:Vy.optional(),codeMetrics:Jy.optional(),qualityMetrics:By.optional(),quantitativeImpact:W.string().optional(),duration:zy.optional(),tasksCompleted:W.number().nullable().optional(),shippedAt:W.string(),featureId:W.string().optional()}),Zu=W.object({shipped:W.array(qy),lastUpdated:W.string()})});import{z as T}from"zod";var Ky,tp,Xy,Yy,Qy,oa,np,Zy,ew,sp,ep,tw,nw,rp,op,ip,sw,rw,zE,Qr=w(()=>{"use strict";_s();Ky=T.enum(["low","medium","high","critical"]),tp=T.enum(["feature","bug","improvement","chore"]),Xy=T.enum(["active","backlog","previously_active"]),Yy=T.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),Qy=T.enum(["task_completed","feature_shipped","idea_captured","session_started"]),oa=T.object({title:T.string(),description:T.string(),filesChanged:T.array(T.object({path:T.string(),action:T.enum(["created","modified","deleted"])})),whatWasDone:T.array(T.string()).min(1),outputForNextAgent:T.string().min(1),notes:T.string().optional()}),np=T.object({output:T.string().min(1,"Subtask output is required"),summary:oa}),Zy=T.object({id:T.string(),description:T.string(),domain:T.string(),agent:T.string(),status:Yy,dependsOn:T.array(T.string()),startedAt:T.string().optional(),completedAt:T.string().optional(),output:T.string().optional(),summary:oa.optional(),skipReason:T.string().optional(),blockReason:T.string().optional(),estimatedPoints:T.number().optional(),estimatedMinutes:T.number().optional()}),ew=T.object({completed:T.number(),total:T.number(),percentage:T.number()}),sp=T.object({id:T.string(),description:T.string(),startedAt:T.string(),sessionId:T.string(),featureId:T.string().optional(),subtasks:T.array(Zy).optional(),currentSubtaskIndex:T.number().optional(),subtaskProgress:ew.optional(),linearId:T.string().optional(),linearUuid:T.string().optional(),estimatedPoints:T.number().optional(),estimatedMinutes:T.number().optional(),modelMetadata:Os.optional()}),ep=T.object({id:T.string(),description:T.string(),status:T.literal("paused"),startedAt:T.string(),pausedAt:T.string(),pauseReason:T.string().optional()}),tw=T.object({stackConfirmed:T.array(T.string()).optional(),patternsDiscovered:T.array(T.string()).optional(),agentAccuracy:T.array(T.object({agent:T.string(),rating:T.enum(["helpful","neutral","inaccurate"]),note:T.string().optional()})).optional(),issuesEncountered:T.array(T.string()).optional()}),nw=T.object({taskId:T.string(),title:T.string(),classification:tp,startedAt:T.string(),completedAt:T.string(),subtaskCount:T.number(),subtaskSummaries:T.array(oa),outcome:T.string(),branchName:T.string(),linearId:T.string().optional(),linearUuid:T.string().optional(),prUrl:T.string().optional(),feedback:tw.optional()}),rp=T.object({currentTask:sp.nullable(),previousTask:ep.nullable().optional(),pausedTasks:T.array(ep).optional(),taskHistory:T.array(nw).optional(),lastUpdated:T.string()}),op=T.object({id:T.string(),description:T.string(),priority:Ky,type:tp,featureId:T.string().optional(),originFeature:T.string().optional(),completed:T.boolean(),completedAt:T.string().optional(),createdAt:T.string(),section:Xy,agent:T.string().optional(),groupName:T.string().optional(),groupId:T.string().optional()}),ip=T.object({tasks:T.array(op),lastUpdated:T.string()}),sw=T.object({tasksToday:T.number(),tasksThisWeek:T.number(),streak:T.number(),velocity:T.string(),avgDuration:T.string()}),rw=T.object({type:Qy,description:T.string(),timestamp:T.string(),duration:T.string().optional()}),zE=T.object({projectId:T.string(),currentTask:sp.nullable(),queue:T.array(op),stats:sw,recentActivity:T.array(rw),lastSync:T.string()})});import{z as Z}from"zod";var ow,iw,ap,VE,qE,KE,sn,cp,Zn=w(()=>{"use strict";ow=Z.enum(["improving","stable","declining"]),iw=Z.object({sprintNumber:Z.number(),startDate:Z.string(),endDate:Z.string(),pointsCompleted:Z.number(),tasksCompleted:Z.number(),avgVariance:Z.number(),estimationAccuracy:Z.number()}),ap=Z.object({category:Z.string(),avgVariance:Z.number(),taskCount:Z.number()}),VE=Z.object({totalPoints:Z.number(),sprints:Z.number(),estimatedDate:Z.string()}),qE=Z.object({sprints:Z.array(iw),averageVelocity:Z.number(),velocityTrend:ow,estimationAccuracy:Z.number(),overEstimated:Z.array(ap),underEstimated:Z.array(ap),lastUpdated:Z.string()}),KE=Z.object({sprintLengthDays:Z.number().min(1).max(90).default(7),startDay:Z.enum(["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]).default("monday"),windowSize:Z.number().min(1).max(52).default(6),accuracyTolerance:Z.number().min(0).max(100).default(20)}),sn={sprintLengthDays:7,startDay:"monday",windowSize:6,accuracyTolerance:20},cp={sprints:[],averageVelocity:0,velocityTrend:"stable",estimationAccuracy:0,overEstimated:[],underEstimated:[],lastUpdated:""}});var wt=w(()=>{"use strict";ju();Bi();Gs();Zi();ea();Kr();_s();na();qu();Ku();Xu();Yu();ra();Qr();Zn()});var St,ia,Ze,rn=w(()=>{"use strict";wt();Q();at();St={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},ia=class{static{l(this,"ArchiveStorage")}archive(e,t){let n=ie(),s=b();return F.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 F.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(ie(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,n,i.reason)}),t.length}getArchived(e,t,n=50){return t?F.query(e,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",t,n):F.query(e,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",n)}getStats(e){let t=F.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=F.get(e,"SELECT * FROM archives WHERE id = ?",t);return n?(F.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);F.run(e,"DELETE FROM archives WHERE archived_at < ?",n);let o=this.getTotalCount(e);return s-o}getTotalCount(e){return F.get(e,"SELECT COUNT(*) as count FROM archives")?.count??0}},Ze=new ia});var aa,kt,Zr=w(()=>{"use strict";wt();Zi();Q();rn();$t();aa=class extends Ce{static{l(this,"IdeasStorage")}constructor(){super("ideas.json",$u)}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=Xe(a.addedAt),u=a.tags.length>0?` ${a.tags.map(m=>`#${m}`).join(" ")}`:"",p=a.priority!=="medium"?` [${a.priority.toUpperCase()}]`:"";t.push(`- ${a.text}${p} _(${c})_${u}`)}):t.push("_No pending ideas_"),t.push(""),s.length>0&&(t.push("## Converted"),s.forEach(a=>{let c=Xe(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=Xe(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(`
|
|
260
|
-
`)}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:
|
|
261
|
-
`);if(t.push("## \u{1F4B0} Token Savings"),t.push(""),t.push(`- **Total saved**: ${this.formatTokens(e.totalTokensSaved)} tokens`),t.push(`- **Compression**: ${(e.avgCompressionRate*100).toFixed(0)}% average reduction`),t.push(`- **Estimated cost saved**: ${
|
|
262
|
-
`)}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,
|
|
257
|
+
${Oh(e.schema)}`:null}function Oh(r){if(r instanceof De.ZodObject){let e=r.shape;return Object.entries(e).map(([t,n])=>`- \`${t}\`: ${Cu(n)}`).join(`
|
|
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
|
+
`)}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:ae(),text:t,status:"pending",priority:n.priority||"medium",tags:n.tags||[],addedAt:b()};return await this.update(e,o=>({ideas:[s,...o.ideas],lastUpdated:b()})),await this.publishEvent(e,"idea.created",{ideaId:s.id,text:s.text,priority:s.priority}),s}async getById(e,t){return(await this.read(e)).ideas.find(s=>s.id===t)}async convertToFeature(e,t,n){await this.update(e,s=>({ideas:s.ideas.map(o=>o.id===t?{...o,status:"converted",convertedTo:n}:o),lastUpdated:b()})),await this.publishEvent(e,"idea.converted",{ideaId:t,featureId:n})}async archive(e,t){await this.update(e,n=>({ideas:n.ideas.map(s=>s.id===t?{...s,status:"archived"}:s),lastUpdated:b()})),await this.publishEvent(e,"idea.archived",{ideaId:t})}async setPriority(e,t,n){await this.update(e,s=>({ideas:s.ideas.map(o=>o.id===t?{...o,priority:n}:o),lastUpdated:b()}))}async addTags(e,t,n){await this.update(e,s=>({ideas:s.ideas.map(o=>o.id===t?{...o,tags:[...new Set([...o.tags,...n])]}:o),lastUpdated:b()}))}async removeIdea(e,t){await this.update(e,n=>({ideas:n.ideas.filter(s=>s.id!==t),lastUpdated:b()}))}async getCounts(e){let t=await this.read(e);return{pending:t.ideas.filter(n=>n.status==="pending").length,converted:t.ideas.filter(n=>n.status==="converted").length,archived:t.ideas.filter(n=>n.status==="archived").length}}async cleanup(e){let n=(await this.read(e)).ideas.filter(a=>a.status==="archived");if(n.length<=50)return{removed:0};let s=n.sort((a,c)=>new Date(c.addedAt).getTime()-new Date(a.addedAt).getTime()),o=new Set(s.slice(50).map(a=>a.id)),i=o.size;return await this.update(e,a=>({ideas:a.ideas.filter(c=>!o.has(c.id)),lastUpdated:b()})),{removed:i}}async markDormantIdeas(e){let t=await this.read(e),n=Yt(Ot.IDEA_DORMANT_DAYS),s=t.ideas.filter(i=>i.status==="pending"&&new Date(i.addedAt)<n);if(s.length===0)return 0;rt.archiveMany(e,s.map(i=>({entityType:"idea",entityId:i.id,entityData:i,summary:i.text,reason:"dormant"})));let o=new Set(s.map(i=>i.id));return await this.update(e,i=>({ideas:i.ideas.map(a=>o.has(a.id)?{...a,status:"dormant"}:a),lastUpdated:b()})),await this.publishEvent(e,"ideas.dormant",{count:s.length}),s.length}},Ee=new Zi});import zy from"node:crypto";import qr from"node:fs/promises";import Ju from"node:path";function qu(){return{version:Pt,lastUpdated:"",checksums:{}}}var Pt,ea,Oe,Ws=y(()=>{"use strict";re();F();te();de();Pt="1.0.0";l(qu,"getDefaultChecksums");ea=class{static{l(this,"IndexStorage")}getIndexPath(e){return Ju.join(T.getGlobalProjectPath(e),"index")}async ensureIndexDir(e){let t=this.getIndexPath(e);return await qr.mkdir(t,{recursive:!0}),t}async readIndex(e){try{let t=this.getIndexMeta(e,"project-index");if(t!==null)return t.version!==Pt?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 qu()}async writeChecksums(e,t){this.setIndexMeta(e,"checksums",t)}async calculateChecksum(e){try{let t=await qr.readFile(e);return zy.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:Pt,lastUpdated:b(),scores:t};this.setIndexMeta(e,"file-scores",n)}async clearIndex(e){try{M.getDb(e).prepare("DELETE FROM index_meta").run()}catch{}let t=this.getIndexPath(e);try{let n=await qr.readdir(t);await Promise.all(n.map(s=>qr.unlink(Ju.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!==Pt?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!==Pt?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=M.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=M.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)}},Oe=new ea});import{z as we}from"zod";function ta(r,e="default"){let t=Ku[e]||Ku.default;return r/1e3*t}function Qn(r){return r<.01?`$${(r*100).toFixed(2)}\xA2`:`$${r.toFixed(2)}`}var Wy,By,Yu,Xu,Ku,Kr=y(()=>{"use strict";Wy=we.object({date:we.string(),tokensSaved:we.number(),syncs:we.number(),avgCompressionRate:we.number(),totalDuration:we.number()}),By=we.object({agentName:we.string(),usageCount:we.number(),tokensSaved:we.number()}),Yu=we.object({totalTokensSaved:we.number(),avgCompressionRate:we.number(),syncCount:we.number(),watchTriggers:we.number(),avgSyncDuration:we.number(),totalSyncDuration:we.number(),agentUsage:we.array(By),dailyStats:we.array(Wy),firstSync:we.string(),lastUpdated:we.string()}),Xu={totalTokensSaved:0,avgCompressionRate:0,syncCount:0,watchTriggers:0,avgSyncDuration:0,totalSyncDuration:0,agentUsage:[],dailyStats:[],firstSync:"",lastUpdated:""},Ku={"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(ta,"estimateCostSaved");l(Qn,"formatCost")});var na,mn,Yr=y(()=>{"use strict";Kr();te();Mt();na=class extends xe{static{l(this,"MetricsStorage")}constructor(){super("metrics.json",Yu)}getDefault(){return{...Xu}}getMdFilename(){return"metrics.md"}getLayer(){return"context"}getEventType(e){return`metrics.${e}d`}toMarkdown(e){let t=["# Value Dashboard \u{1F4CA}",""];if(e.syncCount===0)return t.push("_No metrics yet. Run `prjct sync` to start tracking._"),t.push(""),t.join(`
|
|
260
|
+
`);if(t.push("## \u{1F4B0} Token Savings"),t.push(""),t.push(`- **Total saved**: ${this.formatTokens(e.totalTokensSaved)} tokens`),t.push(`- **Compression**: ${(e.avgCompressionRate*100).toFixed(0)}% average reduction`),t.push(`- **Estimated cost saved**: ${Qn(ta(e.totalTokensSaved))}`),t.push(""),t.push("## \u26A1 Performance"),t.push(""),t.push(`- **Syncs completed**: ${e.syncCount.toLocaleString()}`),t.push(`- **Avg sync time**: ${this.formatDuration(e.avgSyncDuration)}`),e.watchTriggers>0&&t.push(`- **Watch triggers**: ${e.watchTriggers.toLocaleString()} auto-syncs`),t.push(""),e.agentUsage.length>0){t.push("## \u{1F916} Agent Usage"),t.push("");let n=[...e.agentUsage].sort((o,i)=>i.usageCount-o.usageCount),s=n.reduce((o,i)=>o+i.usageCount,0);n.slice(0,5).forEach(o=>{let i=s>0?(o.usageCount/s*100).toFixed(0):0;t.push(`- **${o.agentName}**: ${i}% (${o.usageCount} uses)`)}),t.push("")}if(e.dailyStats.length>0){t.push("## \u{1F4C8} 30-Day Trend"),t.push("");let n=this.getLast30Days(e.dailyStats),s=n.reduce((o,i)=>o+i.tokensSaved,0);t.push(`- **Tokens saved**: ${this.formatTokens(s)}`),t.push(`- **Syncs**: ${n.reduce((o,i)=>o+i.syncs,0)}`),t.push(""),t.push("```"),t.push(this.generateSparkline(n)),t.push("```"),t.push("")}return t.push("---"),t.push(""),e.firstSync&&t.push(`_Tracking since ${new Date(e.firstSync).toLocaleDateString()}_`),t.push(""),t.join(`
|
|
261
|
+
`)}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(v=>v.date===o);if(p>=0){let v=m[p];m[p]={...v,tokensSaved:v.tokensSaved+n,syncs:v.syncs+1,avgCompressionRate:(v.avgCompressionRate*v.syncs+s)/(v.syncs+1),totalDuration:v.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(v=>v.date>=f),k=[...i.agentUsage];if(t.agents)for(let v of t.agents){let D=k.findIndex(q=>q.agentName===v);D>=0?k[D]={...k[D],usageCount:k[D].usageCount+1,tokensSaved:k[D].tokensSaved+Math.floor(n/t.agents.length)}:k.push({agentName:v,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:k,dailyStats:S,firstSync:i.firstSync||b(),lastUpdated:b()}})}async getSummary(e){let t=await this.read(e),n=this.getLast30Days(t.dailyStats),s=this.getPrev30Days(t.dailyStats),o=n.reduce((c,u)=>c+u.tokensSaved,0),i=s.reduce((c,u)=>c+u.tokensSaved,0),a=i>0?(o-i)/i*100:0;return{totalTokensSaved:t.totalTokensSaved,estimatedCostSaved:ta(t.totalTokensSaved),compressionRate:t.avgCompressionRate,syncCount:t.syncCount,avgSyncDuration:t.avgSyncDuration,topAgents:[...t.agentUsage].sort((c,u)=>u.usageCount-c.usageCount).slice(0,5),last30DaysTokens:o,trend:a}}async getDailyStats(e,t=30){let n=await this.read(e),s=new Date;s.setDate(s.getDate()-t);let o=s.toISOString().split("T")[0];return n.dailyStats.filter(i=>i.date>=o).sort((i,a)=>i.date.localeCompare(a.date))}getLast30Days(e){let t=new Date;t.setDate(t.getDate()-30);let n=t.toISOString().split("T")[0];return e.filter(s=>s.date>=n)}getPrev30Days(e){let t=new Date;t.setDate(t.getDate()-30);let n=new Date;n.setDate(n.getDate()-60);let s=n.toISOString().split("T")[0],o=t.toISOString().split("T")[0];return e.filter(i=>i.date>=s&&i.date<o)}formatTokens(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}formatDuration(e){return e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}generateSparkline(e){if(e.length===0)return"";let t="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",n=e.map(o=>o.tokensSaved),s=Math.max(...n,1);return n.map(o=>{let i=Math.min(Math.floor(o/s*(t.length-1)),t.length-1);return t[i]}).join("")}},mn=new na});import Je from"node:fs/promises";import se from"node:path";async function Bs(r){let e=Date.now(),t={success:!1,migratedFiles:[],skippedFiles:[],errors:[],backupDir:null,duration:0};try{if(M.exists(r)&&M.hasDoc(r,"state"))return t.success=!0,t.duration=Date.now()-e,t;let n=T.getGlobalProjectPath(r),s=se.join(n,"storage"),o=se.join(n,"index"),i=se.join(n,"memory");t.backupDir=await Vy(s,o,i),M.getDb(r);for(let{filename:a,key:c}of oa){let u=se.join(s,a),d=await gn(u);if(d===null){t.skippedFiles.push(a);continue}try{M.setDoc(r,c,d),Qu(r,c,d),t.migratedFiles.push(a)}catch(m){t.errors.push({file:a,error:String(m)})}}for(let{filename:a,key:c}of ra){let u=se.join(o,a),d=await gn(u);if(d===null){t.skippedFiles.push(`index/${a}`);continue}try{M.run(r,"INSERT OR REPLACE INTO index_meta (key, data, updated_at) VALUES (?, ?, ?)",c,JSON.stringify(d),new Date().toISOString()),Zu(r,c,d),t.migratedFiles.push(`index/${a}`)}catch(m){t.errors.push({file:`index/${a}`,error:String(m)})}}return await ew(r,o,t),await tw(r,o,t),await nw(r,i,t),await sw(r,i,t),t.errors.length===0&&await rw(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 Vy(r,e,t){let n=se.join(r,"backup");return await Je.mkdir(n,{recursive:!0}),await Je.mkdir(se.join(n,"index"),{recursive:!0}),await Je.mkdir(se.join(n,"memory"),{recursive:!0}),await sa(r,n,s=>s.endsWith(".json")||s.endsWith(".jsonl")),await sa(e,se.join(n,"index")),await sa(t,se.join(n,"memory")),n}async function sa(r,e,t){try{let n=await Je.readdir(r,{withFileTypes:!0});for(let s of n){if(!s.isFile()||t&&!t(s.name))continue;let o=se.join(r,s.name),i=se.join(e,s.name);await Je.copyFile(o,i)}}catch(n){if(!C(n))throw n}}function Qu(r,e,t){switch(e){case"state":Jy(r,t);break;case"queue":qy(r,t);break;case"ideas":Ky(r,t);break;case"shipped":Yy(r,t);break;case"metrics":Xy(r,t);break;case"analysis":Qy(r,t);break}}function Jy(r,e){let t=M.getDb(r),n=t.prepare(`
|
|
263
262
|
INSERT OR REPLACE INTO tasks
|
|
264
263
|
(id, description, type, status, parent_description, branch, linear_id,
|
|
265
264
|
linear_uuid, session_id, feature_id, started_at, completed_at,
|
|
@@ -270,68 +269,68 @@ ${ey(e.schema)}`:null}function ey(r){if(r instanceof Ae.ZodObject){let e=r.shape
|
|
|
270
269
|
(id, task_id, description, status, domain, agent, sort_order,
|
|
271
270
|
depends_on, started_at, completed_at, output, summary)
|
|
272
271
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
273
|
-
`),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
|
|
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 qy(r,e){let t=e.tasks;if(!t||!Array.isArray(t))return;let s=M.getDb(r).prepare(`
|
|
274
273
|
INSERT OR REPLACE INTO queue_tasks
|
|
275
274
|
(id, description, type, priority, section, created_at, completed, completed_at,
|
|
276
275
|
feature_id, feature_name)
|
|
277
276
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
278
|
-
`);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
|
|
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 Ky(r,e){let t=e.ideas;if(!t||!Array.isArray(t))return;let s=M.getDb(r).prepare(`
|
|
279
278
|
INSERT OR REPLACE INTO ideas
|
|
280
279
|
(id, text, status, priority, tags, added_at, converted_to, details, data)
|
|
281
280
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
282
|
-
`);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
|
|
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 Yy(r,e){let t=e.shipped;if(!t||!Array.isArray(t))return;let s=M.getDb(r).prepare(`
|
|
283
282
|
INSERT OR REPLACE INTO shipped_features
|
|
284
283
|
(id, name, shipped_at, version, description, type, duration, data)
|
|
285
284
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
286
|
-
`);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
|
|
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 Xy(r,e){let t=e.dailyStats;if(!t||!Array.isArray(t))return;let s=M.getDb(r).prepare(`
|
|
287
286
|
INSERT OR REPLACE INTO metrics_daily
|
|
288
287
|
(date, tokens_saved, syncs, avg_compression_rate, total_duration)
|
|
289
288
|
VALUES (?, ?, ?, ?, ?)
|
|
290
|
-
`);for(let o of t)s.run(o.date,o.tokensSaved??0,o.syncs??0,o.avgCompressionRate??0,o.totalDuration??0)}function
|
|
289
|
+
`);for(let o of t)s.run(o.date,o.tokensSaved??0,o.syncs??0,o.avgCompressionRate??0,o.totalDuration??0)}function Qy(r,e){let n=M.getDb(r).prepare(`
|
|
291
290
|
INSERT OR REPLACE INTO analysis
|
|
292
291
|
(id, status, commit_hash, signature, sealed_at, analyzed_at, data)
|
|
293
292
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
294
|
-
`),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
|
|
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 Zu(r,e,t){e==="categories-cache"&&Zy(r,t)}function Zy(r,e){let t=e.fileCategories;if(!t||!Array.isArray(t))return;let s=M.getDb(r).prepare(`
|
|
295
294
|
INSERT OR REPLACE INTO index_files
|
|
296
295
|
(path, categories, domain, score, size, mtime, language)
|
|
297
296
|
VALUES (?, ?, ?, COALESCE((SELECT score FROM index_files WHERE path = ?), 0), NULL, NULL, NULL)
|
|
298
|
-
`);for(let o of t)s.run(o.path,o.categories?JSON.stringify(o.categories):null,o.primaryDomain??null,o.path)}async function
|
|
297
|
+
`);for(let o of t)s.run(o.path,o.categories?JSON.stringify(o.categories):null,o.primaryDomain??null,o.path)}async function ew(r,e,t){let n=se.join(e,"checksums.json"),s=await gn(n);if(s===null){t.skippedFiles.push("index/checksums.json");return}try{let o=s.checksums;if(!o)return;let i=M.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 tw(r,e,t){let n=se.join(e,"file-scores.json"),s=await gn(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=M.getDb(r),a=i.prepare(`
|
|
299
298
|
INSERT OR REPLACE INTO index_files
|
|
300
299
|
(path, score, size, mtime, language, categories, domain)
|
|
301
300
|
VALUES (?, ?, ?, ?, NULL,
|
|
302
301
|
COALESCE((SELECT categories FROM index_files WHERE path = ?), NULL),
|
|
303
302
|
COALESCE((SELECT domain FROM index_files WHERE path = ?), NULL))
|
|
304
|
-
`);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
|
|
305
|
-
`).filter(c=>c.trim());if(o.length===0){t.skippedFiles.push("memory/events.jsonl");return}let i=
|
|
306
|
-
`).filter(c=>c.trim());if(o.length===0){t.skippedFiles.push("memory/learnings.jsonl");return}let i=
|
|
307
|
-
`).filter(f=>f.trim());if(
|
|
308
|
-
`)}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:
|
|
309
|
-
`);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=
|
|
310
|
-
`)}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:
|
|
311
|
-
`)}get length(){return this.lines.length}};l(yp,"md")});var Js,Sa,ts,ka=w(()=>{"use strict";Js={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"}},Sa=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=Js[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 Js[e]}getPrompt(e){return Js[e].prompt}getValidCommands(e){return Js[e].transitions}formatNextSteps(e){return Js[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}`}})}},ts=new Sa});var ba,X,oo=w(()=>{"use strict";wt();Qr();Q();wp();ka();rn();$t();ba=class extends Ce{static{l(this,"StateStorage")}constructor(){super("state.json",rp)}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 yp().h1("NOW").when(!!e.currentTask,t=>{let n=e.currentTask;if(t.bold(n.description).blank().raw(`Started: ${Xe(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: ${Xe(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: ${Xe(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=ts.getCurrentState(e),s=ts.canTransition(n,t);if(!s.valid)throw new Error(`${s.error}. ${s.suggestion||""}`.trim())}async getCurrentTask(e){return(await this.read(e)).currentTask}async startTask(e,t){let n=await this.read(e);this.validateTransition(n,"task");let s={...t,startedAt:b()};return await this.update(e,o=>({...o,currentTask:s,lastUpdated:b()})),await this.publishEvent(e,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId}),s}async updateCurrentTask(e,t){let n=await this.read(e);if(!n.currentTask)return null;let s={...n.currentTask,...t};return await this.update(e,o=>({...o,currentTask:s,lastUpdated:b()})),s}async completeTask(e,t){let n=await this.read(e),s=n.currentTask;if(!s)return null;this.validateTransition(n,"done");let o=b(),i=this.createTaskHistoryEntry(s,o,t),a=this.getTaskHistoryFromState(n),c=[i,...a].slice(0,this.maxTaskHistory);return await this.update(e,()=>({currentTask:null,previousTask:null,taskHistory:c,lastUpdated:o})),await this.publishEvent(e,"task.completed",{taskId:s.id,description:s.description,startedAt:s.startedAt,completedAt:o}),s}createTaskHistoryEntry(e,t,n){let s=e,o=(e.subtasks||[]).filter(c=>c.status==="completed"&&c.summary).map(c=>c.summary),i=o.length>0?o.map(c=>c.title).join(", "):"Task completed",a={taskId:e.id,title:s.parentDescription||e.description,classification:s.type||"improvement",startedAt:e.startedAt,completedAt:t,subtaskCount:e.subtasks?.length||0,subtaskSummaries:o,outcome:i,branchName:s.branch||"unknown",linearId:e.linearId,linearUuid:e.linearUuid,prUrl:s.prUrl};return n&&(a.feedback=n),a}maxPausedTasks=5;maxTaskHistory=20;stalenessThresholdDays=30;async pauseTask(e,t){let n=await this.read(e);if(!n.currentTask)return null;this.validateTransition(n,"pause");let s={id:n.currentTask.id,description:n.currentTask.description,status:"paused",startedAt:n.currentTask.startedAt,pausedAt:b(),pauseReason:t},o=this.getPausedTasksFromState(n),i=[s,...o].slice(0,this.maxPausedTasks);return await this.update(e,()=>({currentTask:null,previousTask:null,pausedTasks:i,lastUpdated:b()})),await this.publishEvent(e,"task.paused",{taskId:s.id,description:s.description,pausedAt:s.pausedAt,reason:t,pausedCount:i.length}),s}async resumeTask(e,t){let n=await this.read(e),s=this.getPausedTasksFromState(n);if(s.length===0)return null;this.validateTransition(n,"resume");let o=0;if(t&&(o=s.findIndex(u=>u.id===t),o===-1))return null;let i=s[o],a=s.filter((u,p)=>p!==o),c={id:i.id,description:i.description,startedAt:b(),sessionId:ie()};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[];Ze.archiveMany(e,o.map(a=>({entityType:"paused_task",entityId:a.id,entityData:a,summary:a.description,reason:"staleness"}))),await this.update(e,a=>({...a,pausedTasks:i,previousTask:null,lastUpdated:b()}));for(let a of o)await this.publishEvent(e,"task.archived",{taskId:a.id,description:a.description,pausedAt:a.pausedAt,reason:"staleness"});return o}async clearTask(e){await this.update(e,()=>({currentTask:null,previousTask:null,pausedTasks:[],lastUpdated:b()}))}async hasTask(e){let t=await this.read(e),n=this.getPausedTasksFromState(t);return t.currentTask!==null||n.length>0}async getPausedTask(e){let t=await this.read(e);return this.getPausedTasksFromState(t)[0]||null}async getAllPausedTasks(e){let t=await this.read(e);return this.getPausedTasksFromState(t)}async getTaskHistory(e){let t=await this.read(e);return this.getTaskHistoryFromState(t)}async getMostRecentTask(e){let t=await this.read(e);return this.getTaskHistoryFromState(t)[0]||null}async getTaskHistoryByType(e,t){let n=await this.read(e);return this.getTaskHistoryFromState(n).filter(o=>o.classification===t)}async getAggregatedFeedback(e){let n=(await this.getTaskHistory(e)).filter(d=>d.feedback),s=[],o=[],i=[],a=[];for(let d of n){let g=d.feedback;g.stackConfirmed&&s.push(...g.stackConfirmed),g.patternsDiscovered&&o.push(...g.patternsDiscovered),g.agentAccuracy&&i.push(...g.agentAccuracy),g.issuesEncountered&&a.push(...g.issuesEncountered)}let c=[...new Set(s)],u=[...new Set(o)],p=new Map;for(let d of a)p.set(d,(p.get(d)||0)+1);let m=[...p.entries()].filter(([d,g])=>g>=2).map(([d])=>d);return{stackConfirmed:c,patternsDiscovered:u,agentAccuracy:i,issuesEncountered:[...new Set(a)],knownGotchas:m}}async createSubtasks(e,t){let n=await this.read(e);if(!n.currentTask)return;let s=t.map((o,i)=>({...o,status:i===0?"in_progress":"pending",startedAt:i===0?b():void 0,dependsOn:o.dependsOn||[]}));await this.update(e,o=>({...o,currentTask:{...o.currentTask,subtasks:s,currentSubtaskIndex:0,subtaskProgress:{completed:0,total:s.length,percentage:0}},lastUpdated:b()})),await this.publishEvent(e,"subtasks.created",{taskId:n.currentTask.id,subtaskCount:s.length,subtasks:s.map(o=>({id:o.id,description:o.description,domain:o.domain}))})}async completeSubtask(e,t){let n=np.safeParse(t);if(!n.success){let f=n.error.issues.map(k=>`${k.path.join(".")}: ${k.message}`);throw new Error(`Subtask completion requires handoff data:
|
|
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 nw(r,e,t){let n=se.join(e,"events.jsonl");try{let o=(await Je.readFile(n,"utf-8")).split(`
|
|
304
|
+
`).filter(c=>c.trim());if(o.length===0){t.skippedFiles.push("memory/events.jsonl");return}let i=M.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 sw(r,e,t){let n=se.join(e,"learnings.jsonl");try{let o=(await Je.readFile(n,"utf-8")).split(`
|
|
305
|
+
`).filter(c=>c.trim());if(o.length===0){t.skippedFiles.push("memory/learnings.jsonl");return}let i=M.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 rw(r,e,t,n){let s=l(async(i,a)=>{try{await Je.unlink(i)}catch(c){C(c)||n.errors.push({file:a,error:`cleanup: ${String(c)}`})}},"deleteFile");for(let{filename:i}of oa)await s(se.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(se.join(e,i),`cleanup:index/${i}`);await s(se.join(t,"events.jsonl"),"cleanup:memory/events.jsonl"),await s(se.join(t,"learnings.jsonl"),"cleanup:memory/learnings.jsonl")}async function gn(r){try{let e=await Je.readFile(r,"utf-8");return JSON.parse(e)}catch(e){if(C(e)||e instanceof SyntaxError)return null;throw e}}async function Xr(r){let e=T.getGlobalProjectPath(r),t=se.join(e,"storage"),n=0;M.getDb(r);for(let{filename:u,key:d}of oa){let m=se.join(t,u),p=await gn(m);if(p!==null){M.setDoc(r,d,p),Qu(r,d,p);try{await Je.unlink(m)}catch{}n++}}let s=se.join(e,"project.json"),o=await gn(s);if(o!==null){M.setDoc(r,"project",o);try{await Je.unlink(s)}catch{}n++}let i=se.join(e,"memory");for(let u of["events.jsonl","learnings.jsonl"]){let d=se.join(i,u);try{let p=(await Je.readFile(d,"utf-8")).split(`
|
|
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:
|
|
312
311
|
${f.join(`
|
|
313
|
-
`)}`)}let{output:s,summary:o}=n.data,i=await this.read(e);if(!i.currentTask?.subtasks)return null;let a=i.currentTask.currentSubtaskIndex||0,c=i.currentTask.subtasks[a];if(!c)return null;let u=[...i.currentTask.subtasks];u[a]={...c,status:"completed",completedAt:b(),output:s,summary:o};let
|
|
314
|
-
`);n.push(`**Average**: ${t.averageVelocity} pts/sprint`),n.push(`**Trend**: ${
|
|
315
|
-
`)}async saveMetrics(e,t){await this.write(e,{metrics:t,lastUpdated:t.lastUpdated}),await this.publishEntityEvent(e,"velocity","updated",{averageVelocity:t.averageVelocity,trend:t.velocityTrend,sprintCount:t.sprints.length})}async getMetrics(e){return(await this.read(e)).metrics}};l(
|
|
316
|
-
`).filter(Boolean).map(a=>{let[c,u,
|
|
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:b(),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:b()}),await this.update(e,f=>({...f,currentTask:{...f.currentTask,subtasks:u,currentSubtaskIndex:g<m?g:a,subtaskProgress:{completed:d,total:m,percentage:p}},lastUpdated:b()})),await this.publishEvent(e,"subtask.completed",{taskId:i.currentTask.id,subtaskId:c.id,description:c.description,output:s,handoff:o.outputForNextAgent,filesChanged:o.filesChanged.length,progress:{completed: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:b(),output:`Failed: ${t}`};let a=s+1,c=i.length;a<c&&(i[a]={...i[a],status:"in_progress",startedAt:b()});let u=i.filter(m=>m.status==="completed"||m.status==="failed"||m.status==="skipped").length,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:b()})),await this.publishEvent(e,"subtask.failed",{taskId:n.currentTask.id,subtaskId:o.id,description:o.description,error:t}),a<c?i[a]:null}async skipSubtask(e,t){let n=await this.read(e);if(!n.currentTask?.subtasks)return null;let s=n.currentTask.currentSubtaskIndex||0,o=n.currentTask.subtasks[s];if(!o)return null;let i=[...n.currentTask.subtasks];i[s]={...o,status:"skipped",completedAt:b(),output:`Skipped: ${t}`,skipReason:t};let a=s+1,c=i.length;a<c&&(i[a]={...i[a],status:"in_progress",startedAt:b()});let u=i.filter(m=>m.status==="completed"||m.status==="failed"||m.status==="skipped").length,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:b()})),await this.publishEvent(e,"subtask.skipped",{taskId:n.currentTask.id,subtaskId:o.id,description:o.description,reason:t}),a<c?i[a]:null}async blockSubtask(e,t){let n=await this.read(e);if(!n.currentTask?.subtasks)return null;let s=n.currentTask.currentSubtaskIndex||0,o=n.currentTask.subtasks[s];if(!o)return null;let i=[...n.currentTask.subtasks];i[s]={...o,status:"blocked",output:`Blocked: ${t}`,blockReason:t};let a=s+1,c=i.length;return a<c&&(i[a]={...i[a],status:"in_progress",startedAt:b()}),await this.update(e,u=>({...u,currentTask:{...u.currentTask,subtasks:i,currentSubtaskIndex:a<c?a:s},lastUpdated:b()})),await this.publishEvent(e,"subtask.blocked",{taskId:n.currentTask.id,subtaskId:o.id,description:o.description,blocker:t}),a<c?i[a]:null}},O=new da});import Wt from"node:fs/promises";import ow from"node:os";import hn from"node:path";function ma(r){return new pa(r)}var pa,nd=y(()=>{"use strict";Gi();F();pa=class{static{l(this,"FileStorage")}projectId;basePath;constructor(e){this.projectId=e,this.basePath=hn.join(ow.homedir(),".prjct-cli/projects",e,"data")}pathToFile(e){if(e.length===1)return hn.join(this.basePath,`${e[0]}.json`);let t=`${e[0]}s`,s=`${e.slice(1).join("/")}.json`;return hn.join(this.basePath,t,s)}async write(e,t){let n=this.pathToFile(e);await Wt.mkdir(hn.dirname(n),{recursive:!0}),await Wt.writeFile(n,JSON.stringify(t,null,2),"utf-8"),Kn.publish({type:Ur(e,"write"),path:e,data:t,timestamp:new Date().toISOString(),projectId:this.projectId}),e.length===2&&await this.updateIndex(e[0],e[1],"add")}async read(e){let t=this.pathToFile(e);try{let n=await Wt.readFile(t,"utf-8");return JSON.parse(n)}catch(n){if(C(n)||n instanceof SyntaxError)return null;throw n}}async list(e){let t=hn.join(this.basePath,`${e[0]}s`);try{return(await Wt.readdir(t)).filter(s=>s.endsWith(".json")&&s!=="index.json").map(s=>[...e,s.replace(".json","")])}catch(n){if(C(n))return[];throw n}}async delete(e){let t=this.pathToFile(e);try{await Wt.unlink(t),Kn.publish({type:Ur(e,"delete"),path:e,data:null,timestamp:new Date().toISOString(),projectId:this.projectId}),e.length===2&&await this.updateIndex(e[0],e[1],"remove")}catch(n){if(!C(n))throw n}}async exists(e){let t=this.pathToFile(e);try{return await Wt.access(t),!0}catch(n){if(C(n))return!1;throw n}}async updateIndex(e,t,n){let s=hn.join(this.basePath,`${e}s`,"index.json"),o={ids:[],updatedAt:""};try{let i=await Wt.readFile(s,"utf-8");o=JSON.parse(i)}catch(i){if(!C(i)&&!(i instanceof SyntaxError))throw i}n==="add"&&!o.ids.includes(t)?o.ids.push(t):n==="remove"&&(o.ids=o.ids.filter(i=>i!==t)),o.updatedAt=new Date().toISOString(),await Wt.mkdir(hn.dirname(s),{recursive:!0}),await Wt.writeFile(s,JSON.stringify(o,null,2),"utf-8")}};l(ma,"getStorage")});function iw(r){switch(r){case"improving":return"\u2191";case"declining":return"\u2193";default:return"\u2192"}}var ga,fa,ha=y(()=>{"use strict";Yn();Mt();ga=class extends xe{static{l(this,"VelocityStorage")}constructor(){super("velocity.json")}getDefault(){return{metrics:Vu,lastUpdated:""}}getMdFilename(){return"velocity.md"}getLayer(){return"progress"}getEventType(e){return`velocity.${e}d`}toMarkdown(e){let{metrics:t}=e,n=["# Velocity",""];if(t.sprints.length===0)return n.push("_No velocity data yet. Complete tasks with estimates to build velocity history._"),n.push(""),n.join(`
|
|
313
|
+
`);n.push(`**Average**: ${t.averageVelocity} pts/sprint`),n.push(`**Trend**: ${iw(t.velocityTrend)} ${t.velocityTrend}`),n.push(`**Estimation Accuracy**: ${t.estimationAccuracy}%`),n.push(""),n.push("## Sprint History"),n.push(""),n.push("| Sprint | Points | Tasks | Accuracy | Variance |"),n.push("|--------|--------|-------|----------|----------|");let s=t.sprints.slice(-6);for(let o of s)n.push(`| ${o.sprintNumber} | ${o.pointsCompleted} | ${o.tasksCompleted} | ${o.estimationAccuracy}% | ${o.avgVariance>0?"+":""}${o.avgVariance}% |`);if(n.push(""),t.underEstimated.length>0||t.overEstimated.length>0){n.push("## Estimation Patterns"),n.push("");for(let o of t.underEstimated)n.push(`- \u26A0 **${o.category}**: underestimated by avg ${o.avgVariance}% (${o.taskCount} tasks)`);for(let o of t.overEstimated)n.push(`- \u2713 **${o.category}**: overestimated by avg ${o.avgVariance}% (${o.taskCount} tasks)`);n.push("")}return n.join(`
|
|
314
|
+
`)}async saveMetrics(e,t){await this.write(e,{metrics:t,lastUpdated:t.lastUpdated}),await this.publishEntityEvent(e,"velocity","updated",{averageVelocity:t.averageVelocity,trend:t.velocityTrend,sprintCount:t.sprints.length})}async getMetrics(e){return(await this.read(e)).metrics}};l(iw,"formatTrendIcon");fa=new ga});var Ct=y(()=>{"use strict";Gr();tn();de();Xn();Ws();Yr();Qr();Zn();es();ts();nd();Mt();ha()});import{exec as cw}from"node:child_process";import ss from"node:fs/promises";import ns from"node:path";import{promisify as lw}from"node:util";async function sd(r,e){let t=T.getGlobalProjectPath(r),n=T.getContextPath(r),s=ma(r);await ss.mkdir(n,{recursive:!0});let o=await s.read(["project"])||{},i=await s.list(["task"]),a=await s.list(["feature"]),c=await s.list(["idea"]),u=await s.list(["agent"]),d=[];for(let k of i){let v=await s.read(k);v&&d.push({...v,id:k[1]})}let m=[];for(let k of a){let v=await s.read(k);v&&m.push({...v,id:k[1]})}let p=[];for(let k of c){let v=await s.read(k);v&&p.push({...v,id:k[1]})}let g=[];for(let k of u){let v=await s.read(k);v&&g.push({...v,name:k[1]})}let f=await uw(e),S=await dw(e);await pw(n,r,o,d,m,p,g,f,S,e),await mw(n,d),await gw(n,d),await fw(n,o,f,S)}async function uw(r){let e={branch:"main",commits:0,contributors:0,hasChanges:!1,recentCommits:[]};try{let{stdout:t}=await Js("git branch --show-current",{cwd:r});e.branch=t.trim()||"main";let{stdout:n}=await Js("git rev-list --count HEAD",{cwd:r});e.commits=parseInt(n.trim(),10)||0;let{stdout:s}=await Js("git shortlog -sn --all | wc -l",{cwd:r});e.contributors=parseInt(s.trim(),10)||0;let{stdout:o}=await Js("git status --porcelain",{cwd:r});e.hasChanges=o.trim().length>0;let{stdout:i}=await Js('git log --oneline -10 --pretty=format:"%h|%s|%ad" --date=short',{cwd:r});e.recentCommits=i.split(`
|
|
315
|
+
`).filter(Boolean).map(a=>{let[c,u,d]=a.split("|");return{hash:c,message:u,date:d}})}catch{}return e}async function dw(r){let e={dependencies:{},devDependencies:{},scripts:{}};try{let t=ns.join(r,"package.json"),n=JSON.parse(await ss.readFile(t,"utf-8"));e.dependencies=n.dependencies||{},e.devDependencies=n.devDependencies||{},e.scripts=n.scripts||{}}catch{}return e}async function pw(r,e,t,n,s,o,i,a,c,u){let d=t.name||ns.basename(u),m=n.find(v=>v.status==="in_progress"),p=n.filter(v=>v.status==="pending"),g=s.filter(v=>v.status==="in_progress"||v.status==="active"),f=Object.keys(c.dependencies),S=Object.keys(c.devDependencies),k=`# ${d} - Project Context
|
|
317
316
|
<!-- projectId: ${e} -->
|
|
318
317
|
<!-- Generated: ${new Date().toISOString()} -->
|
|
319
318
|
|
|
320
319
|
## PROJECT DATA
|
|
321
320
|
|
|
322
|
-
### Dependencies (${f.length+
|
|
321
|
+
### Dependencies (${f.length+S.length})
|
|
323
322
|
|
|
324
323
|
**Production** (${f.length}):
|
|
325
|
-
${f.length>0?f.map(
|
|
324
|
+
${f.length>0?f.map(v=>`- ${v}: ${c.dependencies[v]}`).join(`
|
|
326
325
|
`):"_None_"}
|
|
327
326
|
|
|
328
|
-
**Dev** (${
|
|
329
|
-
${
|
|
327
|
+
**Dev** (${S.length}):
|
|
328
|
+
${S.length>0?S.map(v=>`- ${v}: ${c.devDependencies[v]}`).join(`
|
|
330
329
|
`):"_None_"}
|
|
331
330
|
|
|
332
331
|
### Scripts
|
|
333
332
|
|
|
334
|
-
${Object.keys(c.scripts).length>0?Object.entries(c.scripts).map(([
|
|
333
|
+
${Object.keys(c.scripts).length>0?Object.entries(c.scripts).map(([v,D])=>`- \`${v}\`: ${D}`).join(`
|
|
335
334
|
`):"_None_"}
|
|
336
335
|
|
|
337
336
|
### Git
|
|
@@ -342,7 +341,7 @@ ${Object.keys(c.scripts).length>0?Object.entries(c.scripts).map(([x,$])=>`- \`${
|
|
|
342
341
|
- Uncommitted: ${a.hasChanges?"Yes":"No"}
|
|
343
342
|
|
|
344
343
|
**Recent:**
|
|
345
|
-
${a.recentCommits.length>0?a.recentCommits.slice(0,5).map(
|
|
344
|
+
${a.recentCommits.length>0?a.recentCommits.slice(0,5).map(v=>`- \`${v.hash}\` ${v.message}`).join(`
|
|
346
345
|
`):"_None_"}
|
|
347
346
|
|
|
348
347
|
---
|
|
@@ -351,23 +350,23 @@ ${a.recentCommits.length>0?a.recentCommits.slice(0,5).map(x=>`- \`${x.hash}\` ${
|
|
|
351
350
|
|
|
352
351
|
**Now:** ${m?m.description:"_No active task_"}
|
|
353
352
|
|
|
354
|
-
**Queue (${
|
|
355
|
-
${
|
|
353
|
+
**Queue (${p.length}):**
|
|
354
|
+
${p.length>0?p.slice(0,10).map((v,D)=>`${D+1}. ${v.description}`).join(`
|
|
356
355
|
`):"_Empty_"}
|
|
357
356
|
|
|
358
357
|
**Active Features (${g.length}):**
|
|
359
|
-
${g.length>0?g.map(
|
|
358
|
+
${g.length>0?g.map(v=>`- ${v.name}`).join(`
|
|
360
359
|
`):"_None_"}
|
|
361
360
|
|
|
362
361
|
**Ideas (${o.length}):**
|
|
363
|
-
${o.length>0?o.slice(0,5).map(
|
|
362
|
+
${o.length>0?o.slice(0,5).map(v=>`- ${v.title}`).join(`
|
|
364
363
|
`):"_None_"}
|
|
365
364
|
|
|
366
365
|
---
|
|
367
366
|
|
|
368
367
|
## AGENTS
|
|
369
368
|
|
|
370
|
-
${i.length>0?i.map(
|
|
369
|
+
${i.length>0?i.map(v=>`- **${v.name}**: ${v.role||"Specialist"}`).join(`
|
|
371
370
|
`):"_None_"}
|
|
372
371
|
|
|
373
372
|
---
|
|
@@ -389,7 +388,7 @@ ${i.length>0?i.map(x=>`- **${x.name}**: ${x.role||"Specialist"}`).join(`
|
|
|
389
388
|
\u2514\u2500\u2500 sync/ # Sync state
|
|
390
389
|
\u2514\u2500\u2500 pending.json
|
|
391
390
|
\`\`\`
|
|
392
|
-
`;await ss.writeFile(ns.join(r,"CLAUDE.md"),
|
|
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
|
|
393
392
|
|
|
394
393
|
**Task:** ${t.description}
|
|
395
394
|
|
|
@@ -399,11 +398,11 @@ ${i.length>0?i.map(x=>`- **${x.name}**: ${x.role||"Specialist"}`).join(`
|
|
|
399
398
|
`:`# NOW
|
|
400
399
|
|
|
401
400
|
_No active task. Use /p:now to start._
|
|
402
|
-
`;await ss.writeFile(ns.join(r,"now.md"),n,"utf-8")}async function
|
|
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
|
|
403
402
|
|
|
404
403
|
${t.length>0?t.map((s,o)=>`${o+1}. ${s.description}${s.priority?` [${s.priority}]`:""}`).join(`
|
|
405
404
|
`):"_Empty queue. Use /p:next to add tasks._"}
|
|
406
|
-
`;await ss.writeFile(ns.join(r,"queue.md"),n,"utf-8")}async function
|
|
405
|
+
`;await ss.writeFile(ns.join(r,"queue.md"),n,"utf-8")}async function fw(r,e,t,n){let s=`# PROJECT SUMMARY
|
|
407
406
|
|
|
408
407
|
**Name:** ${e.name||"Unknown"}
|
|
409
408
|
**Version:** ${e.version||"N/A"}
|
|
@@ -419,19 +418,14 @@ ${t.length>0?t.map((s,o)=>`${o+1}. ${s.description}${s.priority?` [${s.priority}
|
|
|
419
418
|
|
|
420
419
|
- Production: ${Object.keys(n.dependencies).length}
|
|
421
420
|
- Dev: ${Object.keys(n.devDependencies).length}
|
|
422
|
-
`;await ss.writeFile(ns.join(r,"summary.md"),s,"utf-8")}var Ws,bp=w(()=>{"use strict";K();Ft();Ws=Ew(Tw);l(kp,"generateContext");l(Aw,"getGitData");l(Iw,"getPackageData");l(jw,"generateClaudeMd");l(Dw,"generateNowMd");l(Rw,"generateQueueMd");l($w,"generateSummaryMd")});var Pt={};fn(Pt,{appendJsonLine:()=>rs,appendJsonLineWithRotation:()=>os,appendJsonLines:()=>Ow,checkFileSizeWarning:()=>Hw,countJsonLines:()=>Cp,filterJsonLines:()=>Aa,getFileSizeMB:()=>ja,getFirstJsonLines:()=>_w,getLastJsonLines:()=>Ia,isJsonLinesEmpty:()=>Lw,mergeJsonLines:()=>Nw,parseJsonLines:()=>Pp,readJsonLines:()=>Vt,readJsonLinesStreaming:()=>Uw,rotateJsonLinesIfNeeded:()=>vp,stringifyJsonLines:()=>Ea,writeJsonLines:()=>io});import Mw from"node:fs";import bn from"node:fs/promises";import kn from"node:path";import Fw from"node:readline";function Pp(r){let e=r.split(`
|
|
423
|
-
|
|
424
|
-
`)}
|
|
425
|
-
`}
|
|
426
|
-
|
|
427
|
-
`).filter(n=>n.trim()).length}catch(e){if(S(e))return 0;throw e}}async function Ia(r,e){return(await Vt(r)).slice(-e)}async function _w(r,e){return(await Vt(r)).slice(0,e)}async function Nw(r){let e=[];for(let t of r){let n=await Vt(t);e.push(...n)}return e}async function Lw(r){return await Cp(r)===0}async function Uw(r,e=Us.JSONL_MAX_LINES){try{let t=Mw.createReadStream(r),n=Fw.createInterface({input:t,crlfDelay:1/0}),s=[];for await(let o of n)if(o.trim()){try{s.push(JSON.parse(o))}catch{}s.length>e&&s.shift()}return s}catch(t){if(S(t))return[];throw t}}async function ja(r){try{return(await bn.stat(r)).size/(1024*1024)}catch(e){if(S(e))return 0;throw e}}async function vp(r,e=Us.ROTATION_SIZE_MB){let t=await ja(r);if(t<e)return!1;let n=new Date().toISOString().split("T")[0],s=kn.dirname(r),o=kn.extname(r),i=kn.basename(r,o),a=kn.join(s,`${i}-${n}${o}`);return await bn.rename(r,a),console.log(`\u{1F4E6} Rotated ${kn.basename(r)} (${t.toFixed(1)}MB) \u2192 ${kn.basename(a)}`),!0}async function os(r,e,t=Us.ROTATION_SIZE_MB){await vp(r,t),await rs(r,e)}async function Hw(r,e=Us.LARGE_FILE_WARN_MB){let t=await ja(r),n=t>e;return n&&console.warn(`\u26A0\uFE0F Large file detected: ${kn.basename(r)} (${t.toFixed(1)}MB). Reading may use significant memory.`),{sizeMB:t,isLarge:n}}var Bs=w(()=>{"use strict";M();Jt();l(Pp,"parseJsonLines");l(Ea,"stringifyJsonLines");l(Vt,"readJsonLines");l(io,"writeJsonLines");l(rs,"appendJsonLine");l(Ow,"appendJsonLines");l(Aa,"filterJsonLines");l(Cp,"countJsonLines");l(Ia,"getLastJsonLines");l(_w,"getFirstJsonLines");l(Nw,"mergeJsonLines");l(Lw,"isJsonLinesEmpty");l(Uw,"readJsonLinesStreaming");l(ja,"getFileSizeMB");l(vp,"rotateJsonLinesIfNeeded");l(os,"appendJsonLineWithRotation");l(Hw,"checkFileSizeWarning")});import Da from"node:fs/promises";import is from"node:path";function $a(r){if(eu.includes(r))return[r];let e=r.toLowerCase().replace(/[-_\s]/g,""),t=[];for(let[n,s]of Object.entries(ao))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 Ra,ao,Pn,Vs,qs,Ks=w(()=>{"use strict";K();M();zn();Q();Ee();Bs();Ra={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)},ao={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($a,"resolveCanonicalDomains");Pn=class{static{l(this,"CachedStore")}_data=null;_loaded=!1;_projectId=null;getSubdirectory(){return null}getPath(e){let t=is.join(P.getGlobalProjectPath(e),"memory"),n=this.getSubdirectory();return n?is.join(t,n,this.getFilename()):is.join(t,this.getFilename())}async load(e){if(this._loaded&&this._data&&this._projectId===e)return this._data;let t=this.getPath(e);try{let n=await Da.readFile(t,"utf-8");this._data=JSON.parse(n),this.afterLoad(this._data)}catch(n){if(S(n))this._data=this.getDefault();else throw n}return this._loaded=!0,this._projectId=e,this._data}afterLoad(e){}async save(e){if(!this._data)return;let t=this.getPath(e);await Da.mkdir(is.dirname(t),{recursive:!0}),await Da.writeFile(t,JSON.stringify(this._data,null,2),"utf-8")}getData(){return this._data}setData(e){this._data=e}async update(e,t){let n=await this.load(e),s=t(n);return this._data=s,await this.save(e),s}isLoaded(e){return e?this._loaded&&this._projectId===e:this._loaded}reset(){this._data=null,this._loaded=!1,this._projectId=null}},Vs=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()}},qs=class{static{l(this,"HistoryStore")}_getSessionPath(e){let t=new Date,n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`,s=$r();return is.join(P.getGlobalProjectPath(e),"memory","sessions",n,`${s}.jsonl`)}async appendHistory(e,t){let n=this._getSessionPath(e);await Ye(is.dirname(n));let s={ts:b(),...t,type:t.type};await rs(n,s)}async getRecentHistory(e,t=20){let n=this._getSessionPath(e);return Ia(n,t)}}});import Ma from"node:fs/promises";import Fa from"node:path";var Xs,Oa=w(()=>{"use strict";K();M();zn();Q();Ks();Xs=class r extends Pn{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=Dr(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=Dr(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:Dr(a,c),observationCount:a,userConfirmed:c},await this.save(e)}async confirmPreference(e,t){let s=(await this.load(e)).preferences[t];return s?(s.userConfirmed=!0,s.confidence="high",s.updatedAt=b(),await this.save(e),!0):!1}async getPreference(e,t,n=null){return(await this.load(e)).preferences[t]?.value??n}async getPatternsSummary(e){let t=await this.load(e);return{decisions:Object.keys(t.decisions).length,learnedDecisions:Object.values(t.decisions).filter(n=>n.confidence!=="low").length,workflows:Object.keys(t.workflows).length,preferences:Object.keys(t.preferences).length}}_getArchivePath(e){let t=Fa.join(P.getGlobalProjectPath(e),"memory");return Fa.join(t,"patterns-archive.json")}async archiveStaleDecisions(e){let t=await this.load(e),n=Date.now(),s=r.ARCHIVE_AGE_DAYS*24*60*60*1e3,o=[];for(let[c,u]of Object.entries(t.decisions)){let p=new Date(u.lastSeen).getTime();n-p>s&&o.push(c)}if(o.length===0)return 0;let i=this._getArchivePath(e),a={};try{let c=await Ma.readFile(i,"utf-8");a=JSON.parse(c)}catch(c){if(!S(c))throw c}for(let c of o)a[c]=t.decisions[c],delete t.decisions[c];return await Ma.mkdir(Fa.dirname(i),{recursive:!0}),await Ma.writeFile(i,JSON.stringify(a,null,2),"utf-8"),await this.save(e),o.length}}});var Cn,_a=w(()=>{"use strict";wt();zn();Q();Ks();Cn=class extends Pn{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:ie(),title:t,content:n,tags:a,userTriggered:o,createdAt:c,updatedAt:c};i.memories.push(u);for(let p of a)i.index[p].push(u.id);return await this.save(e),u.id}async updateMemory(e,t,n){let s=await this.load(e),o=s.memories.findIndex(c=>c.id===t);if(o===-1)return!1;let i=s.memories[o],a=i.tags||[];if(n.title&&(i.title=n.title),n.content&&(i.content=n.content),n.tags){let c=this._coerceTags(n.tags);for(let u of a)s.index[u]=s.index[u].filter(p=>p!==t);for(let u of c)s.index[u].push(t);i.tags=c}return i.updatedAt=b(),await this.save(e),!0}async deleteMemory(e,t){let n=await this.load(e),s=n.memories.findIndex(i=>i.id===t);if(s===-1)return!1;let o=n.memories[s];for(let i of o.tags||[])n.index[i]&&(n.index[i]=n.index[i].filter(a=>a!==t));return n.memories.splice(s,1),await this.save(e),!0}async findByTags(e,t,n=!1){let s=await this.load(e),o=this._coerceTags(t);if(n)return s.memories.filter(i=>o.every(a=>(i.tags||[]).includes(a)));{let i=new Set;for(let a of o){let c=s.index[a];for(let u of c)i.add(u)}return s.memories.filter(a=>i.has(a.id))}}async searchMemories(e,t){let n=await this.load(e),s=t.toLowerCase();return n.memories.filter(o=>o.title.toLowerCase().includes(s)||o.content.toLowerCase().includes(s))}async getRelevantMemories(e,t,n=5){return(await this.load(e)).memories.map(i=>{let a=0,c=this._extractContextTags(t);for(let d of i.tags||[])c.includes(d)&&(a+=10);let p=(Date.now()-new Date(i.updatedAt).getTime())/(1e3*60*60*24);a+=Math.max(0,5-p),i.userTriggered&&(a+=5);let m=this._extractKeywords(t);for(let d of m)i.content.toLowerCase().includes(d)&&(a+=2),i.title.toLowerCase().includes(d)&&(a+=3);return{...i,_score:a}}).filter(i=>i._score>0).sort((i,a)=>a._score-i._score).slice(0,n).map(({_score:i,...a})=>a)}async getRelevantMemoriesWithMetrics(e,t){let n=await this.load(e),s=n.memories.length;if(s===0)return{memories:[],metrics:{totalMemories:0,memoriesConsidered:0,memoriesReturned:0,filteringRatio:0,avgRelevanceScore:0}};let o=t.maxResults??10,i=t.minRelevance??10,c=n.memories.map(d=>{let g={domainMatch:0,tagMatch:0,recency:0,confidence:0,keywords:0,userTriggered:0};if(t.taskDomain&&(g.domainMatch=this._getSemanticDomainScore(t.taskDomain,d.tags||[])),t.commandName){let x=this._getCommandTags(t.commandName),$=(d.tags||[]).filter(J=>x.includes(J));g.tagMatch=Math.min(20,$.length*8)}let k=(Date.now()-new Date(d.updatedAt).getTime())/(1e3*60*60*24);if(g.recency=Math.max(0,Math.round(15-k*.5)),d.confidence?g.confidence=d.confidence==="high"?20:d.confidence==="medium"?12:5:d.observationCount&&(g.confidence=Math.min(20,d.observationCount*3)),t.taskDescription){let x=this._extractKeywordsFromText(t.taskDescription),$=0;for(let J of x)d.content.toLowerCase().includes(J)&&($+=2),d.title.toLowerCase().includes(J)&&($+=3);g.keywords=Math.min(15,$)}d.userTriggered&&(g.userTriggered=5);let v=g.domainMatch+g.tagMatch+g.recency+g.confidence+g.keywords+g.userTriggered;return{...d,relevanceScore:v,scoreBreakdown:g}}).filter(d=>d.relevanceScore>=i),p=c.sort((d,g)=>g.relevanceScore-d.relevanceScore).slice(0,o),m=p.length>0?Math.round(p.reduce((d,g)=>d+g.relevanceScore,0)/p.length):0;return{memories:p,metrics:{totalMemories:s,memoriesConsidered:c.length,memoriesReturned:p.length,filteringRatio:s>0?p.length/s:0,avgRelevanceScore:m}}}_getSemanticDomainScore(e,t){let n=this._resolveCanonicalDomains(e);if(n.length===0)return 0;let s=new Set;for(let a of n){let c=Ra[a];if(c)for(let u of c)s.add(u)}let o=new Set;for(let a of n){let c=ao[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 $a(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?`
|
|
428
|
-
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 Na,Gw,le,as=w(()=>{"use strict";Ks();Oa();_a();Ks();Oa();_a();Na=class{static{l(this,"MemorySystem")}_semanticMemories;_patternStore;_historyStore;_sessionStore;constructor(){this._semanticMemories=new Cn,this._patternStore=new Xs,this._historyStore=new qs,this._sessionStore=new Vs}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()}},Gw=new Na,le=Gw});import{exec as zw}from"node:child_process";import et from"node:fs/promises";import Ct from"node:path";import{promisify as Jw}from"node:util";var vn,La,Ww,Ie,xp=w(()=>{"use strict";M();vn=Jw(zw),La=class{static{l(this,"CodebaseAnalyzer")}projectPath=null;init(e=process.cwd()){this.projectPath=e}async readPackageJson(){try{let e=Ct.join(this.projectPath,"package.json"),t=await et.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(S(e)||e instanceof SyntaxError)return null;throw e}}async readCargoToml(){try{let e=Ct.join(this.projectPath,"Cargo.toml");return await et.readFile(e,"utf-8")}catch(e){if(S(e))return null;throw e}}async readRequirements(){try{let e=Ct.join(this.projectPath,"requirements.txt");return await et.readFile(e,"utf-8")}catch(e){if(S(e))return null;throw e}}async readGoMod(){try{let e=Ct.join(this.projectPath,"go.mod");return await et.readFile(e,"utf-8")}catch(e){if(S(e))return null;throw e}}async readGemfile(){try{let e=Ct.join(this.projectPath,"Gemfile");return await et.readFile(e,"utf-8")}catch(e){if(S(e))return null;throw e}}async readMixExs(){try{let e=Ct.join(this.projectPath,"mix.exs");return await et.readFile(e,"utf-8")}catch(e){if(S(e))return null;throw e}}async readPomXml(){try{let e=Ct.join(this.projectPath,"pom.xml");return await et.readFile(e,"utf-8")}catch(e){if(S(e))return null;throw e}}async readComposerJson(){try{let e=Ct.join(this.projectPath,"composer.json"),t=await et.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(S(e)||e instanceof SyntaxError)return null;throw e}}async readPyprojectToml(){try{let e=Ct.join(this.projectPath,"pyproject.toml");return await et.readFile(e,"utf-8")}catch(e){if(S(e))return null;throw e}}async getFileExtensions(){try{let{stdout:e}=await vn('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(`
|
|
429
|
-
`).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 et.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(S(e))return[];throw e}}async listDirectories(){try{return(await et.readdir(this.projectPath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).filter(t=>!t.startsWith(".")&&t!=="node_modules")}catch(e){if(S(e))return[];throw e}}async getGitLog(e=50){try{let{stdout:t}=await vn(`git log -n ${e} --pretty=format:"%h|%an|%ar|%s"`,{cwd:this.projectPath});return t}catch{return""}}async getGitStats(){try{let{stdout:e}=await vn("git rev-list --count HEAD",{cwd:this.projectPath}),{stdout:t}=await vn('git log --format="%an" | sort -u | wc -l',{cwd:this.projectPath}),{stdout:n}=await vn('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 vn('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 et.access(Ct.join(this.projectPath,e)),!0}catch(t){if(S(t))return!1;throw t}}async readFile(e){try{let t=Ct.join(this.projectPath,e);return await et.readFile(t,"utf-8")}catch(t){if(S(t))return null;throw t}}async findFiles(e){try{let{stdout:t}=await vn(`find . -type f -name "${e}" ! -path "*/node_modules/*" ! -path "*/.git/*"`,{cwd:this.projectPath});return t.trim().split(`
|
|
430
|
-
`).filter(Boolean)}catch{return[]}}},Ww=new La,Ie=Ww});import Ua from"node:fs";import lo from"node:path";function Tp(){if(Ys)return Ys;let r=__dirname;for(let e=0;e<5;e++){let t=lo.join(r,"package.json");if(Ua.existsSync(t))try{if(JSON.parse(Ua.readFileSync(t,"utf-8")).name==="prjct-cli")return Ys=r,r}catch{}r=lo.dirname(r)}return Ys=lo.join(__dirname,"..","..",".."),Ys}function Vw(){if(co)return co;try{let r=lo.join(Tp(),"package.json"),e=JSON.parse(Ua.readFileSync(r,"utf-8"));return co=e.version,Bw=e,co}catch(r){return console.error("Failed to read version from package.json:",y(r)),"0.0.0"}}var co,Bw,Ys,cs,Se,xn=w(()=>{"use strict";M();co=null,Bw=null,Ys=null;l(Tp,"getPackageRoot");l(Vw,"getVersion");cs=Vw(),Se=Tp()});import Ga from"node:fs";import qw from"node:fs/promises";import uo from"node:path";function za(){if(Ep)return Ha;Ep=!0;let r=uo.join(Se,"dist","templates.json");try{let e=Ga.readFileSync(r,"utf-8");return Ha=JSON.parse(e),Ha}catch{return null}}function Xw(r){let e=Tn.indexOf(r);e>-1&&Tn.splice(e,1),Tn.push(r)}function Yw(){for(;ls.size>=Kw&&Tn.length>0;){let r=Tn.shift();r&&ls.delete(r)}}function po(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(`
|
|
431
|
-
`).forEach(i=>{let[a,...c]=i.split(":");if(a&&c.length>0){let u=c.join(":").trim();u.startsWith("[")&&u.endsWith("]")?o[a.trim()]=u.slice(1,-1).split(",").map(p=>p.trim()):o[a.trim()]=u.replace(/^["']|["']$/g,"")}}),{frontmatter:o,content:s.trim()}}async function Ap(r){if(ls.has(r))return Xw(r),ls.get(r);let e,t=za();if(t){let s=`commands/${r}.md`;e=t[s]}if(!e){let s=uo.join(Se,"templates","commands",`${r}.md`);try{e=await qw.readFile(s,"utf-8")}catch{throw Nr.notFound(r)}}let n=po(e);return Yw(),ls.set(r,n),Tn.push(r),n}async function Qw(r){return(await Ap(r)).frontmatter["allowed-tools"]||[]}function Zw(){ls.clear(),Tn.length=0}function xe(r){let e=za();if(e?.[r])return e[r];let t=uo.join(Se,"templates",r);try{return Ga.readFileSync(t,"utf-8")}catch{return null}}function us(r){let e=za();if(e)return Object.keys(e).filter(n=>n.startsWith(r));let t=uo.join(Se,"templates",r);try{return Ga.readdirSync(t).map(s=>`${r}${s}`)}catch{return[]}}var Kw,ls,Tn,Ha,Ep,eS,Ja,ps=w(()=>{"use strict";zt();xn();Kw=50,ls=new Map,Tn=[],Ha=null,Ep=!1;l(za,"loadBundle");l(Xw,"updateLruOrder");l(Yw,"evictLru");l(po,"parseFrontmatter");l(Ap,"load");l(Qw,"getAllowedTools");l(Zw,"clearCache");l(xe,"getTemplateContent");l(us,"listTemplates");eS={load:Ap,parseFrontmatter:po,getAllowedTools:Qw,clearCache:Zw,getTemplateContent:xe,listTemplates:us},Ja=eS});import z from"node:fs/promises";import Ba from"node:os";import B from"node:path";async function tS(){try{let r=xe("global/modules/module-config.json");if(r)return JSON.parse(r);let e=B.join(Se,"templates/global/modules/module-config.json"),t=await z.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async function nS(r){let e=await tS();if(!e){let i=xe("global/CLAUDE.md");if(i)return i;let a=B.join(Se,"templates/global/CLAUDE.md");return z.readFile(a,"utf-8")}let t=r||e.default,n=e.profiles[t];if(!n&&!e.profiles[e.default]){let a=xe("global/CLAUDE.md");if(a)return a;let c=B.join(Se,"templates/global/CLAUDE.md");return z.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=xe(`global/modules/${i}`);if(a)o.push(""),o.push(a);else try{let c=B.join(Se,"templates/global/modules",i),u=await z.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(`
|
|
432
|
-
`)}async function sS(){try{let r=B.join(Ba.homedir(),".prjct-cli","docs");await z.mkdir(r,{recursive:!0});let e=us("global/docs/");if(e.length>0){for(let s of e)if(s.endsWith(".md")){let o=xe(s);if(o){let i=B.basename(s);await z.writeFile(B.join(r,i),o,"utf-8")}}return{success:!0}}let t=B.join(Se,"templates/global/docs"),n=await z.readdir(t);for(let s of n)if(s.endsWith(".md")){let o=B.join(t,s),i=B.join(r,s),a=await z.readFile(o,"utf-8");await z.writeFile(i,a,"utf-8")}return{success:!0}}catch(r){return{success:!1,error:y(r)}}}async function rS(){let r=(ze(),ot(Qe)),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 z.mkdir(e.configDir,{recursive:!0});let s=B.join(e.configDir,e.contextFile),o=B.join(Se,"templates","global",e.contextFile),i="";try{let u=xe(`global/${e.contextFile}`);u?i=u:i=await z.readFile(o,"utf-8")}catch{if(t==="claude")try{i=await nS("standard")}catch{let p=xe("global/CLAUDE.md");if(p)i=p;else{let m=B.join(Se,"templates/global/CLAUDE.md");i=await z.readFile(m,"utf-8")}}else{let p=xe("global/CLAUDE.md");if(p)i=p;else{let m=B.join(Se,"templates/global/CLAUDE.md");i=await z.readFile(m,"utf-8")}t==="gemini"&&(i=i.replace(/Claude/g,"Gemini"))}}let a="",c=!1;try{a=await z.readFile(s,"utf-8"),c=!0}catch(u){if(S(u))c=!1;else throw u}if(c){let u="<!-- prjct:start - DO NOT REMOVE THIS MARKER -->",p="<!-- prjct:end - DO NOT REMOVE THIS MARKER -->";if(a.includes(u)&&a.includes(p)){let d=a.substring(0,a.indexOf(u)),g=a.substring(a.indexOf(p)+p.length),f=i.substring(i.indexOf(u),i.indexOf(p)+p.length),k=d+f+g;return await z.writeFile(s,k,"utf-8"),{success:!0,action:"updated",path:s}}else{let d=`${a}
|
|
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}
|
|
433
427
|
|
|
434
|
-
${i}`;return await
|
|
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+=`
|
|
435
429
|
|
|
436
430
|
---
|
|
437
431
|
|
|
@@ -442,11 +436,11 @@ ${i}`;return await z.writeFile(s,d,"utf-8"),{success:!0,action:"appended",path:s
|
|
|
442
436
|
`;for(let s of t)n+=s.content,n+=`
|
|
443
437
|
|
|
444
438
|
`;return`${n.trimEnd()}
|
|
445
|
-
`}function
|
|
446
|
-
`);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(
|
|
447
|
-
`,"utf-8")}async readGlobalConfig(e){try{let t=
|
|
448
|
-
`,"utf-8")}async ensureGlobalConfig(e){let t=await this.readGlobalConfig(e);if(!t){let n=b();t={projectId:e,authors:[],version:
|
|
449
|
-
`;await
|
|
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:`
|
|
450
444
|
AGENTIC EXECUTION:
|
|
451
445
|
- Read: templates/agentic/orchestrator.md
|
|
452
446
|
- Analyze task: "${e}"
|
|
@@ -454,12 +448,12 @@ ${i}`;return await z.writeFile(s,d,"utf-8"),{success:!0,action:"appended",path:s
|
|
|
454
448
|
- Claude decides which agent(s) to use
|
|
455
449
|
- Always prefer specialists over generalist
|
|
456
450
|
- Fragment complex tasks into subtasks
|
|
457
|
-
`}}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}},ms=new Po});var Co,vo,Hp=w(()=>{"use strict";Co=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"}},vo=new Co});var Gp,TS,xo,ES,zp=w(()=>{"use strict";zs();Gp=8e4,TS={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"]},xo=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||Gp,[c,u,p]=await Promise.all([Re.readIndex(t),Re.readDomains(t),Re.readCategories(t)]);if(!c||!u||!p)return this.fallbackSelection(c?.relevantFiles||[],n);let m=this.detectTaskDomains(e,u.domains),d=new Set;for(let $ of m){let J=p.domainIndex[$]||[];for(let Pe of J)d.add(Pe)}if(i&&p.domainIndex.general){let $=p.domainIndex.general.slice(0,10);for(let J of $)d.add(J)}let g=c.relevantFiles.filter($=>d.has($.path)&&$.score>=o);g.sort(($,J)=>J.score-$.score);let f=0,k=[];for(let $ of g){let J=Math.ceil($.size/this.CHARS_PER_TOKEN);if(f+J>a||k.length>=s)break;k.push($),f+=J}let v=Math.ceil(c.relevantFiles.reduce(($,J)=>$+J.size,0)/this.CHARS_PER_TOKEN),x=v>0?(v-f)/v:0;return{files:k,domains:m,metrics:{totalFiles:c.relevantFiles.length,selectedFiles:k.length,compressionRate:x,estimatedTokensSaved:v-f}}}detectTaskDomains(e,t){let n=e.toLowerCase(),s=new Set;for(let[o,i]of Object.entries(TS))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 Re.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 Re.readIndex(e);return i?i.relevantFiles.filter(a=>o.has(a.path)):[]}async getFilesDomains(e,t){return Re.getFileCategories(e,t)}fallbackSelection(e,t){let n=t.maxFiles||50,s=t.minScore||30,o=t.tokenBudget||Gp,i=e.filter(p=>p.score>=s).sort((p,m)=>m.score-p.score),a=0,c=[];for(let p of i){let m=Math.ceil(p.size/this.CHARS_PER_TOKEN);if(a+m>o||c.length>=n)break;c.push(p),a+=m}let u=Math.ceil(e.reduce((p,m)=>p+m.size,0)/this.CHARS_PER_TOKEN);return{files:c,domains:[],metrics:{totalFiles:e.length,selectedFiles:c.length,compressionRate:u>0?(u-a)/u:0,estimatedTokensSaved:u-a}}}suggestRelatedDomains(e){let t=new Set,n={payments:["api","database","services"],auth:["api","database","users"],api:["services","types"],database:["types","services"],frontend:["types","utilities"],testing:["services","api"]};for(let s of e){let o=n[s];if(o)for(let i of o)e.includes(i)||t.add(i)}return Array.from(t)}},ES=new xo});import Jp from"node:path";var ec,To,AS,Wp=w(()=>{"use strict";zs();Q();ec=[{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"}],To=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 ec)if(c.test(a)){t.set(u,(t.get(u)||0)+1),n.has(u)||n.set(u,new Set);let p=Jp.dirname(i.path);n.get(u).add(`**/${Jp.basename(p)}/**`)}}let s=this.extractDirectoryDomains(e);for(let[i,a]of s)t.set(i,(t.get(i)||0)+a);let o=[];for(let[i,a]of t)if(a>=2){let c=ec.find(u=>u.domain===i);o.push({name:i,description:`Files related to ${i}`,keywords:c?[i]:[i],filePatterns:Array.from(n.get(i)||[]),fileCount:a})}return o.sort((i,a)=>a.fileCount-i.fileCount).slice(0,this.maxDomains)}extractDirectoryDomains(e){let t=new Map;for(let n of e){let s=n.path.split("/");for(let o of s.slice(0,-1)){let i=o.toLowerCase();["src","lib","app","core","dist","build"].includes(i)||i.length>2&&!i.startsWith(".")&&t.set(i,(t.get(i)||0)+1)}}return t}categorizeFilesHeuristic(e,t){let n=[],s=b();for(let o of e){let i=[],a=o.path.toLowerCase();for(let m of t){let d=0;for(let g of m.keywords)a.includes(g.toLowerCase())&&(d+=1);for(let{pattern:g,domain:f}of ec)f===m.name&&g.test(a)&&(d+=2);for(let g of m.filePatterns){let f=g.replace(/\*\*/g,"").replace(/\//g,"");a.includes(f.toLowerCase())&&(d+=1)}d>0&&i.push({domain:m.name,score:d})}i.sort((m,d)=>d.score-m.score);let c=i.length>0?i.slice(0,3).map(m=>m.domain):["general"],u=c[0],p=i.length>0?Math.min(1,i[0].score/5):.1;n.push({path:o.path,categories:c,primaryDomain:u,confidence:p,categorizedAt:s,method:"heuristic"})}return n}async saveToCache(e,t,n){let s=b(),o={version:bt,projectId:e,domains:t,discoveredAt:s};await Re.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:bt,lastUpdate:s,fileCategories:n,domainIndex:i};await Re.writeCategories(e,a)}async loadFromCache(e){let[t,n]=await Promise.all([Re.readDomains(e),Re.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 Re.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 Re.readCategories(e);if(i){let a=new Set(t.map(d=>d.path)),u=[...i.fileCategories.filter(d=>!a.has(d.path)),...o],p={};for(let d of u)for(let g of d.categories)p[g]||(p[g]=[]),p[g].push(d.path);let m={version:bt,lastUpdate:b(),fileCategories:u,domainIndex:p};await Re.writeCategories(e,m)}return o}},AS=new To});import tc from"node:path";var nc,IS,jS,Eo,Bp,sc=w(()=>{"use strict";nc=30,IS=[/^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$/],jS=[/^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],Eo=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=nc){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=tc.basename(e.path);for(let n of IS)if(n.test(t)||n.test(e.path))return 20;return 0}calculateNameRelevance(e){let t=tc.basename(e.path);for(let s of jS)if(s.test(t))return 15;let n=tc.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}},Bp=new Eo});function rc(r,e){return{...$s[r],...e}}function Ao(r,e,t){return{message:r,hint:e,...t}}var Io=w(()=>{"use strict";jr();jr();l(rc,"getError");l(Ao,"createError")});import{execSync as oc}from"node:child_process";var jo,ic,Do,Ro,ac=w(()=>{"use strict";Io();jo={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"}},ic=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=jo[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=jo[e],s=t.error||{message:`${e} is not available`,hint:n?.installHint||`Install ${e} and try again`,docs:n?.docs};throw new Do(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=jo[s];return o?` ${s}: ${o.installHint}`:` ${s}: Install and try again`}).join(`
|
|
458
|
-
`);throw new
|
|
459
|
-
${n}`})}}isAvailable(e){return this.checkTool(e).available}getVersion(e){return this.checkTool(e).version}checkAll(e){let t=e||Object.keys(
|
|
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(`
|
|
460
454
|
`),s=null,o=[];for(let i of n){let a=i.match(/^##\s+(.+)$/);if(a){s&&(s.content=o.join(`
|
|
461
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(`
|
|
462
|
-
`).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
|
|
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}
|
|
463
457
|
|
|
464
458
|
${a.content}`)}}let o=[];for(let[i,a]of t)o.push(`## ${i}
|
|
465
459
|
|
|
@@ -467,44 +461,56 @@ ${a}`);return{content:o.join(`
|
|
|
467
461
|
|
|
468
462
|
---
|
|
469
463
|
|
|
470
|
-
`),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=
|
|
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(`
|
|
471
465
|
`),s=null,o=null,i=[],a=l(()=>{if(s){if(o){let c=i.join(`
|
|
472
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(`
|
|
473
|
-
`).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],
|
|
474
|
-
`).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
|
|
475
|
-
|
|
476
|
-
${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
|
|
477
|
-
`),this))},done(r,e){if(this.stop(),!
|
|
478
|
-
`),n=Math.max(r.length,...t.map(o=>o.length)),s="\u2500".repeat(n+2);console.log(
|
|
479
|
-
${
|
|
480
|
-
`),this)},progress(r,e,t){if(
|
|
481
|
-
`),this)}},h=
|
|
482
|
-
|
|
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
|
|
479
|
+
${r.map((n,s)=>{let o=n.status==="completed",i=s===e?" \u2190 current":"";return`${o?"- [x]":"- [ ]"} ${n.description}${i}`}).join(`
|
|
480
|
+
`)}`}function jd(r){return`### Rules
|
|
481
|
+
${Tt(r)}`}function _e(r){return`### Next
|
|
482
|
+
${r.map(t=>`- ${t.label}: \`${t.command}\``).join(`
|
|
483
|
+
`)}`}function Et(r){let e=[];for(let[t,n]of Object.entries(r))n!=null&&e.push(`- **${t}:** ${n}`);return e.join(`
|
|
484
|
+
`)}function _t(r,e){return e?`## ${r} \u2713
|
|
485
|
+
${e}`:`## ${r} \u2713`}function rn(r){return`> \u26A0\uFE0F ${r}`}function me(...r){return r.filter(Boolean).join(`
|
|
486
|
+
|
|
487
|
+
`)}var ps=y(()=>{"use strict";l(ze,"mdSection");l(Tt,"mdList");l(Ka,"mdTaskHeader");l(Ya,"mdSubtasks");l(jd,"mdRules");l(_e,"mdNextSteps");l(Et,"mdStats");l(_t,"mdDone");l(rn,"mdWarn");l(me,"mdJoin")});import rr from"chalk";function ct(r,e={}){if(e.quiet)return;let t=$d[r]||"idle",n=fn.getValidCommands(t);if(n.length===0)return;let s=n.map(o=>({cmd:`p. ${o}`,desc:Rd[o]||o}));console.log(rr.dim(`
|
|
488
|
+
Next:`));for(let o of s){let i=rr.cyan(o.cmd.padEnd(12));console.log(rr.dim(` ${i} \u2192 ${o.desc}`))}}function Eo(r){let e=$d[r]||"idle";return fn.getValidCommands(e).map(n=>({cmd:`p. ${n}`,desc:Rd[n]||n}))}function or(r){let e=fn.getStateInfo(r);console.log(rr.dim(`\u{1F4CD} State: ${rr.white(r.toUpperCase())} - ${e.description}`))}var Rd,$d,ms=y(()=>{"use strict";ua();Rd={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"},$d={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(ct,"showNextSteps");l(Eo,"getNextSteps");l(or,"showStateInfo")});import dt from"chalk";import En from"prompts";var Xa,Md,gs,Fd=y(()=>{"use strict";Tn();Xa=[{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."}],Md=[{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"}],gs=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,En.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 En({type:"select",name:"projectType",message:this.detectedType!=="unknown"?`Detected: ${this.getProjectTypeLabel(this.detectedType)}. Is this correct?`:"What type of project is this?",choices:Xa.map(t=>({title:t.title,description:t.description,value:t.value,selected:t.value===this.detectedType})),initial:Xa.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 En({type:"multiselect",name:"agents",message:"Which AI agents do you use?",choices:Md.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(dt.dim(`
|
|
483
489
|
Detected: ${e}
|
|
484
|
-
`));let t=await
|
|
490
|
+
`));let t=await En({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 En([{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 En([{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(dt.bold(" Configuration Summary")),console.log(dt.dim(` ${"\u2500".repeat(40)}`)),console.log(` ${dt.cyan("Project Type:")} ${this.getProjectTypeLabel(this.confirmedType)}`),console.log(` ${dt.cyan("AI Agents:")} ${this.selectedAgents.map(t=>this.getAgentLabel(t)).join(", ")}`),console.log(` ${dt.cyan("Stack:")} ${this.formatStackDisplay(this.confirmedStack)}`),console.log(` ${dt.cyan("Verbosity:")} ${this.preferences.verbosity}`),console.log(` ${dt.cyan("Auto-sync:")} ${this.preferences.autoSync?"Yes":"No"}`),console.log("");let e=await En({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(dt.bold.cyan(" Welcome to prjct-cli!")),console.log(dt.dim(" Let's set up your project in 60 seconds.")),console.log("")}printStepHeader(e){console.log(""),console.log(dt.dim(` Step ${this.currentStep}/${this.totalSteps}: ${e}`)),console.log("")}handleCancel(){this.aborted=!0,console.log(dt.yellow(`
|
|
485
491
|
Setup cancelled. Run again anytime.
|
|
486
|
-
`))}getProjectTypeLabel(e){return
|
|
487
|
-
`).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}},BS=new Fo,We=BS});var Oo,VS,gc,Zp=w(()=>{"use strict";Rn();Oo=class{static{l(this,"OutcomeAnalyzer")}async summarize(e){let t=await We.getAll(e);if(t.length===0)return{totalOutcomes:0,avgQualityScore:0,estimateAccuracy:0,topBlockers:[],topAgents:[],patternsDetected:[]};let n=t.reduce((m,d)=>m+d.qualityScore,0)/t.length,s=await We.getEstimateAccuracy(e),o=new Map;for(let m of t)for(let d of m.blockers||[])o.set(d,(o.get(d)||0)+1);let i=[...o.entries()].sort((m,d)=>d[1]-m[1]).slice(0,5).map(([m])=>m),c=(await this.getAgentMetrics(e)).sort((m,d)=>d.successRate-m.successRate).slice(0,3).map(m=>m.agent),p=(await this.detectPatterns(e)).map(m=>m.description);return{totalOutcomes:t.length,avgQualityScore:Math.round(n*10)/10,estimateAccuracy:s,topBlockers:i,topAgents:c,patternsDetected:p}}async getAgentMetrics(e){let t=await We.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(k=>k.completedAsPlanned),u=Math.round(c.length/a*100),p=i.reduce((k,v)=>k+v.qualityScore,0)/a,m=i.filter(k=>{if(!k.variance)return!1;let v=this.parseVariance(k.variance),x=this.parseDuration(k.estimatedDuration);return x===0?!1:Math.abs(v)/x<=.2}),d=Math.round(m.length/a*100),g=new Map;for(let k of i.filter(v=>v.completedAsPlanned))for(let v of k.tags||[])g.set(v,(g.get(v)||0)+1);let f=[...g.entries()].sort((k,v)=>v[1]-k[1]).slice(0,3).map(([k])=>k);s.push({agent:o,tasksCompleted:a,successRate:u,avgQualityScore:Math.round(p*10)/10,estimateAccuracy:d,bestFor:f})}return s}async detectPatterns(e){let t=await We.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 We.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}},VS=new Oo,gc=VS});var ir,_o,fc,hc=w(()=>{"use strict";zn();Q();ir=3,_o=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]}`,p=t.get(u)||{count:0,tasks:[]};p.count++,p.tasks.push(s.taskId),t.set(u,p)}}let n=[];for(let[s,{count:o,tasks:i}]of t)if(o>=2){let[a,c]=s.split("|");n.push({pattern:`Files "${a}" and "${c}" frequently change together (${o} tasks)`,occurrences:o,confidence:this.calculateConfidence(o),category:"file_cochange",sourceTasks:i})}return n.sort((s,o)=>o.occurrences-s.occurrences)}extractStackPatterns(e){let t=new Map;for(let n of e)if(n.feedback?.stackConfirmed)for(let s of n.feedback.stackConfirmed){let o=t.get(s)||{count:0,tasks:[]};o.count++,o.tasks.push(n.taskId),t.set(s,o)}return Array.from(t.entries()).map(([n,{count:s,tasks:o}])=>({pattern:`Project uses ${n}`,occurrences:s,confidence:this.calculateConfidence(s),category:"tech_stack",sourceTasks:o}))}extractArchitecturePatterns(e){let t=new Map;for(let n of e)if(n.feedback?.patternsDiscovered)for(let s of n.feedback.patternsDiscovered){let o=t.get(s)||{count:0,tasks:[]};o.count++,o.tasks.push(n.taskId),t.set(s,o)}return Array.from(t.entries()).map(([n,{count:s,tasks:o}])=>({pattern:n,occurrences:s,confidence:this.calculateConfidence(s),category:"architecture",sourceTasks:o}))}extractGotchaPatterns(e){let t=new Map;for(let n of e)if(n.feedback?.issuesEncountered)for(let s of n.feedback.issuesEncountered){let o=t.get(s)||{count:0,tasks:[]};o.count++,o.tasks.push(n.taskId),t.set(s,o)}return Array.from(t.entries()).filter(([n,{count:s}])=>s>=2).map(([n,{count:s,tasks:o}])=>({pattern:`Known gotcha: ${n}`,occurrences:s,confidence:this.calculateConfidence(s),category:"gotcha",sourceTasks:o}))}extractOutcomePatterns(e){let t=[],n=new Map,s=new Map;for(let i of e){for(let a of i.learnings.whatWorked){let c=n.get(a)||{count:0,ids:[]};c.count++,c.ids.push(i.id),n.set(a,c)}for(let a of i.learnings.whatDidnt){let c=s.get(a)||{count:0,ids:[]};c.count++,c.ids.push(i.id),s.set(a,c)}}for(let[i,{count:a,ids:c}]of n)t.push({pattern:`What works: ${i}`,occurrences:a,confidence:this.calculateConfidence(a),category:"workflow",sourceTasks:c});for(let[i,{count:a,ids:c}]of s)t.push({pattern:`Known issue: ${i}`,occurrences:a,confidence:this.calculateConfidence(a),category:"gotcha",sourceTasks:c});let o=e.filter(i=>i.effort.variance.percentage>30);return o.length>=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(`
|
|
488
|
-
`)}},
|
|
489
|
-
`);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=
|
|
490
|
-
`)}async addFeatureOutcome(e,t){await this.update(e,n=>({...n,outcomes:[t,...n.outcomes],aggregates:
|
|
492
|
+
`))}getProjectTypeLabel(e){return Xa.find(t=>t.value===e)?.title||"Unknown"}getAgentLabel(e){return Md.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 Qa from"node:path";var hS,yS,Ao,wS,Xe,An=y(()=>{"use strict";re();bt();Fe();hS="outcomes",yS="outcomes.jsonl",Ao=class{static{l(this,"OutcomeRecorder")}getOutcomesDir(e){let t=T.getGlobalProjectPath(e);return Qa.join(t,hS)}getOutcomesPath(e){return Qa.join(this.getOutcomesDir(e),yS)}async record(e,t){let n={...t,id:ae()},s=this.getOutcomesPath(e);return await yt(Qa.dirname(s)),await Ii(s,JSON.stringify(n)),n}async getAll(e){let t=this.getOutcomesPath(e);if(!await $(t))return[];let n=await Gn(t);return n.trim()?n.trim().split(`
|
|
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
|
+
`)}},ec=new Do});var jo,_d,nc=y(()=>{"use strict";qi();Mt();te();jo=class extends xe{static{l(this,"OutcomeStorage")}constructor(){super("outcomes.json")}getDefault(){return{...Au,lastUpdated:""}}getMdFilename(){return"outcomes.md"}getLayer(){return"progress"}getEventType(e){return`outcomes.${e}d`}toMarkdown(e){let t=["# OUTCOMES",""];if(e.outcomes.length===0&&(!e.taskOutcomes||e.taskOutcomes.length===0))return t.push("_No outcomes recorded yet._"),t.push(""),t.join(`
|
|
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(`
|
|
491
497
|
\u{1F3AF} Orchestrating: ${e.join(", ")} domains detected
|
|
492
|
-
`))}startAgent(e,t,n){if(this.quiet)return;this.currentAgent=e,this.startTime=Date.now();let s=
|
|
493
|
-
`),this.currentAgent=null}status(e,t){this.quiet||console.log(`${e} ${t}`)}complete(e,t){if(this.quiet)return;let n=t?` ${
|
|
494
|
-
`)}function
|
|
495
|
-
`)}var
|
|
498
|
+
`))}startAgent(e,t,n){if(this.quiet)return;this.currentAgent=e,this.startTime=Date.now();let s=kS(t);console.log(Nt.cyan(`\u250C\u2500 ${s} ${e} (${t})`)),n&&console.log(Nt.dim(`\u2502 ${n}`))}progress(e){this.quiet||!this.currentAgent||console.log(Nt.dim(`\u2502 \u2514\u2500\u2500 ${e}`))}progressList(e){if(!(this.quiet||!this.currentAgent))for(let t of e)console.log(Nt.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?Nt.green("\u2713"):Nt.red("\u2717");console.log(`\u2514\u2500 ${s} ${e?"Complete":"Failed"} ${Nt.dim(`(${n})`)}
|
|
499
|
+
`),this.currentAgent=null}status(e,t){this.quiet||console.log(`${e} ${t}`)}complete(e,t){if(this.quiet)return;let n=t?` ${Nt.dim(`[${this.formatDuration(t)}]`)}`:"";console.log(Nt.green(`\u2705 ${e}${n}`))}formatDuration(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}},Ro=new rc});import Ne from"chalk";function bS(r){let e=0;for(let n of r)e=(e<<5)-e+n.charCodeAt(0),e=e&e;let t=Math.abs(e)%Ud.length;return Ud[t]}function PS(r,e,t="\u25B6"){let n=Ne.dim(String(r+1).padStart(2)),o=bS(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=Ne.green("\u2713 Complete");break;case"in_progress":a=Ne.yellow(`${t} Working...`);break;case"pending":a=Ne.gray("\u25CB Pending");break;case"failed":a=Ne.red("\u2717 Failed");break;case"blocked":a=Ne.gray("\u2298 Blocked");break;default:a=Ne.gray(`\u25CB ${e.status}`)}return` ${n} ${o} ${i} ${a}`}function CS(r){if(r.length===0)return"";let e=[];e.push(""),e.push(` ${Ne.bold.white("SUBTASK PROGRESS")}`),e.push(` ${Ne.dim("\u2500".repeat(58))}`);for(let t=0;t<r.length;t++)e.push(PS(t,r[t]));return e.push(""),e.join(`
|
|
500
|
+
`)}function Hd(r){console.log(CS(r))}var Ud,Gd=y(()=>{"use strict";Ud=[Ne.cyan,Ne.magenta,Ne.yellow,Ne.blue,Ne.green,Ne.redBright,Ne.magentaBright,Ne.cyanBright];l(bS,"getDomainColor");l(PS,"formatSubtaskLine");l(CS,"renderSubtaskProgress");l(Hd,"printSubtaskProgress")});function vS(r){return zd.includes(r)}async function xS(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 TS(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(`
|
|
501
|
+
`)}var zd,ES,$o,Wd=y(()=>{"use strict";zd=["ship","feature","spec","cleanup","migrate"];l(vS,"requiresReasoning");l(xS,"reason");l(TS,"formatPlan");ES={requiresReasoning:vS,reason:xS,formatPlan:TS,REASONING_REQUIRED_COMMANDS:zd},$o=ES});import ar from"node:fs/promises";var oc,AS,Qe,ic=y(()=>{"use strict";it();re();F();Hr();oc=class{static{l(this,"ContextBuilder")}_cache;_currentProjectId;constructor(){this._cache=new kt({ttl:5e3,maxSize:200}),this._currentProjectId=null}async build(e,t={}){let n=await R.getProjectId(e),s=T.getGlobalProjectPath(n);return this._currentProjectId!==null&&this._currentProjectId!==n&&this._cache.clear(),this._currentProjectId=n,{projectId:n,projectPath:e,globalPath:s,paths:{now:T.getFilePath(n,"core","now.md"),next:T.getFilePath(n,"core","next.md"),context:T.getFilePath(n,"core","context.md"),shipped:T.getFilePath(n,"progress","shipped.md"),metrics:T.getFilePath(n,"progress","metrics.md"),ideas:T.getFilePath(n,"planning","ideas.md"),roadmap:T.getFilePath(n,"planning","roadmap.md"),specs:T.getFilePath(n,"planning","specs"),memory:T.getFilePath(n,"memory","context.jsonl"),patterns:T.getFilePath(n,"memory","patterns.json"),analysis:T.getFilePath(n,"analysis","repo-summary.md"),codePatterns:T.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 ar.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([ar.readFile(d,"utf-8"),ar.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 ar.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 ar.access(e),!0}catch(t){if(C(t))return!1;throw t}}getCacheStats(){return this._cache.stats()}},AS=new oc,Qe=AS});import{exec as IS}from"node:child_process";import ge from"node:fs/promises";import Bd from"node:os";import on from"node:path";import{promisify as DS}from"node:util";function Vd(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 ac(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function RS(r){if(r.verified||r.warnings.length===0)return null;let e=` Ground Truth Warnings:
|
|
496
502
|
`;return r.warnings.forEach(t=>{e+=` - ${t}
|
|
497
503
|
`}),r.recommendations.length>0&&(e+=`
|
|
498
504
|
Recommendations:
|
|
499
505
|
`,r.recommendations.forEach(t=>{e+=` -> ${t}
|
|
500
|
-
`})),e}async function
|
|
501
|
-
`).filter(Boolean).length,n.hasUncommittedChanges&&(e.push(`${n.uncommittedFiles} uncommitted file(s)`),t.push("Commit changes before shipping"))}catch{n.gitAvailable=!1}let s=cn.join(r.projectPath,"package.json");try{let i=await ue.readFile(s,"utf-8"),a=JSON.parse(i);n.currentVersion=a.version,n.hasPackageJson=!0}catch(i){if(S(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 ue.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}.*${Pc(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(S(i))n.shippedExists=!1;else throw i}if(n.hasPackageJson)try{let i=await ue.readFile(s,"utf-8"),a=JSON.parse(i);n.hasTestScript=!!a.scripts?.test}catch(i){if(S(i)||i instanceof SyntaxError)n.hasTestScript=!1;else throw i}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function dd(r){let e=[],t=[],n={},s=r.paths.next;try{let a=await ue.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(S(a))n.nextExists=!1,n.taskCount=0;else throw a}let o=r.paths.roadmap;try{let a=await ue.readFile(o,"utf-8");n.roadmapExists=!0;let c=r.params.description||r.params.feature;c&&new RegExp(Pc(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(S(a))n.roadmapExists=!1;else throw a}let i=r.paths.now;try{let a=await ue.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(S(a))n.hasActiveTask=!1;else throw a}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function md(r){let e=[],t=[],n={},s=r.paths.now;try{let i=await ue.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(S(i))n.nowExists=!1,n.hasActiveTask=!1;else throw i}let o=r.paths.next;try{let a=((await ue.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(S(i))n.pendingTasks=0;else throw i}return{verified:e.length===0,actual:n,warnings:e,recommendations:t}}async function gd(r){let e=[],t=[],n={},s=cn.join(r.projectPath,".prjct/prjct.config.json");try{let i=await ue.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(S(i))n.alreadyInitialized=!1;else if(i instanceof SyntaxError)n.alreadyInitialized=!1,e.push("Existing config has invalid JSON");else throw i}let o=cn.join(cd.homedir(),".prjct-cli");try{await ue.access(o,ue.constants.W_OK),n.globalPathWritable=!0}catch(i){if(S(i))try{await ue.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 fd(r){let e=[],t=[],n={},s=cn.join(r.projectPath,".prjct/prjct.config.json");try{let a=await ue.readFile(s,"utf-8");n.hasConfig=!0,n.config=JSON.parse(a)}catch(a){if(S(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=cn.join(cd.homedir(),".prjct-cli/projects",o||"");try{await ue.access(i),n.globalStorageExists=!0}catch(a){if(S(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 hd(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 ue.access(cn.join(r.projectPath,i)),n.detectedFiles.push(i)}catch(a){if(!S(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 ue.stat(cn.join(r.projectPath,i))).isDirectory()&&n.detectedSrcDirs.push(i)}catch(a){if(!S(a))throw a}return{verified:!0,actual:n,warnings:e,recommendations:t}}async function yd(r){let e=[],t=[],n={},s=r.paths.specs;try{await ue.access(s),n.specsExists=!0;let i=await ue.readdir(s);n.existingSpecs=i.filter(a=>a.endsWith(".md")),n.specCount=n.existingSpecs.length}catch(i){if(S(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 Sd(r,e,t){let n=wd[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 ak(r,e,t){let n=await Sd(r,e,t);return{...e,groundTruth:{...n,verifiedAt:new Date().toISOString(),command:r}}}function ck(r){return["done","ship","feature","spec","now","init","sync","analyze"].includes(r)}var ok,wd,lk,Ho,kd=w(()=>{"use strict";M();ok=rk(sk);l(ld,"formatDuration");l(Pc,"escapeRegex");l(ik,"formatWarnings");l(ud,"verifyDone");l(pd,"verifyShip");l(dd,"verifyFeature");l(md,"verifyNow");l(gd,"verifyInit");l(fd,"verifySync");l(hd,"verifyAnalyze");l(yd,"verifySpec");wd={done:ud,ship:pd,feature:dd,now:md,init:gd,sync:fd,analyze:hd,spec:yd};l(Sd,"verify");l(ak,"prepareCommand");l(ck,"requiresVerification");lk={verify:Sd,prepareCommand:ak,requiresVerification:ck,verifiers:wd,formatWarnings:ik,formatDuration:ld,escapeRegex:Pc,verifyDone:ud,verifyShip:pd,verifyFeature:dd,verifyNow:md,verifyInit:gd,verifySync:fd,verifyAnalyze:hd,verifySpec:yd},Ho=lk});function pk(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 dk(r){if(!r||typeof r!="string")return{detected:!1};for(let{pattern:e,type:t,description:n}of uk)if(e.test(r))return{detected:!0,type:t,pattern:e.source,description:n,message:`Potential hallucination detected: ${n}`,suggestion:pk(t)};return{detected:!1}}function mk(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 gk(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 fk(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 hk(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 uk,Cc,yk,ys,bd=w(()=>{"use strict";uk=[{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(pk,"getHallucinationSuggestion");l(dk,"detectHallucination");l(mk,"isSimilarError");l(gk,"analyzeErrorPattern");l(fk,"generateEscalationMessage");l(hk,"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=>mk(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=gk(s.errors);return{status:"BLOCKED",command:e,context:t,attempts:s.attempts,duration:s.lastAttempt-s.firstAttempt,errorPattern:o,message:fk(e,o,this.maxAttempts),suggestion:hk(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 dk(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}}},yk=new Cc,ys=yk});function vc(r,e){let t=cr(e),n=wk[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 Sk(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 kk(r,e,t){let n=cr(t),s=vc(r,t),o=vc(e,t),i=s.getTime()-o.getTime(),a=Math.round(i/(1e3*60*60*24));return Math.floor(a/n.sprintLengthDays)+1}function Go(r,e=sn){let t=cr(e);if(r.length===0)return{sprints:[],averageVelocity:0,velocityTrend:"stable",estimationAccuracy:0,overEstimated:[],underEstimated:[],lastUpdated:new Date().toISOString()};let n=bk(r,e),s=Pk(n,t.accuracyTolerance),o=s.slice(-t.windowSize),i=xk(o),a=Ck(o),c=vk(r,t.accuracyTolerance),{overEstimated:u,underEstimated:p}=Tk(r);return{sprints:s,averageVelocity:i,velocityTrend:a,estimationAccuracy:c,overEstimated:u,underEstimated:p,lastUpdated:new Date().toISOString()}}function Cd(r,e,t=sn){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 bk(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=kk(i,s,e);if(!t.has(a)){let c=vc(i,e),u=Sk(c,e);t.set(a,{sprintNumber:a,startDate:c,endDate:u,outcomes:[]})}t.get(a).outcomes.push(o)}return t}function Pk(r,e){let t=[];for(let[,n]of r){let s=n.outcomes.reduce((u,p)=>u+Ek(p),0),o=n.outcomes.filter(u=>u.variance).map(u=>Tc(u)),i=o.length>0?Math.round(o.reduce((u,p)=>u+p,0)/o.length):0,a=o.filter(u=>Math.abs(u)<=e).length,c=o.length>0?Math.round(a/o.length*100):0;t.push({sprintNumber:n.sprintNumber,startDate:n.startDate.toISOString(),endDate:n.endDate.toISOString(),pointsCompleted:s,tasksCompleted:n.outcomes.length,avgVariance:i,estimationAccuracy:c})}return t.sort((n,s)=>n.sprintNumber-s.sprintNumber)}function Ck(r){if(r.length<3)return"stable";let e=r.map(p=>p.pointsCompleted),t=e.length,n=0,s=0,o=0,i=0;for(let p=0;p<t;p++)n+=p,s+=e[p],o+=p*e[p],i+=p*p;let a=(t*o-n*s)/(t*i-n*n),c=s/t;if(c===0)return"stable";let u=a/c;return u>.1?"improving":u<-.1?"declining":"stable"}function vk(r,e){let t=r.filter(s=>s.variance);if(t.length===0)return 0;let n=t.filter(s=>{let o=Tc(s);return Math.abs(o)<=e});return Math.round(n.length/t.length*100)}function xk(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 Tk(r){let e=new Map;for(let s of r){if(!s.variance)continue;let o=Tc(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 Tc(r){if(!r.variance)return 0;let e=xc(r.estimatedDuration),t=xc(r.actualDuration);return e<=0?0:Math.round((t-e)/e*100)}function xc(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 vd(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(`
|
|
502
|
-
`)}function
|
|
506
|
+
`})),e}async function Jd(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=Vd(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(on.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 qd(r){let e=[],t=[],n={};try{let{stdout:i}=await jS("git status --porcelain",{cwd:r.projectPath});n.hasUncommittedChanges=i.trim().length>0,n.uncommittedFiles=i.trim().split(`
|
|
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 ZS(r){if(!r.estimatedDuration)return 0;let e=uc(r.estimatedDuration);if(e<=0)return 0;let t=op[0],n=Number.POSITIVE_INFINITY;for(let s of op){let o=Math.abs(s.typical-e);o<n&&(n=o,t=s)}return t.points}function cr(r){return{sprintLengthDays:r.sprintLengthDays??7,startDay:r.startDay??"monday",windowSize:r.windowSize??6,accuracyTolerance:r.accuracyTolerance??20}}var WS,op,pc=y(()=>{"use strict";Yn();WS={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};l(lc,"getSprintStart");l(BS,"getSprintEnd");l(VS,"getSprintNumber");l(Fo,"calculateVelocity");l(ip,"projectCompletion");l(JS,"bucketBySprint");l(qS,"buildSprintVelocities");l(KS,"detectTrend");l(YS,"calculateOverallAccuracy");l(XS,"calculateAverageVelocity");l(QS,"detectEstimationPatterns");l(dc,"parseVariancePercent");l(uc,"parseDurationMinutes");l(ap,"formatVelocityContext");op=[{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(ZS,"derivePoints");l(cr,"resolveConfig")});import{exec as ek}from"node:child_process";import tk from"node:fs/promises";import Oo from"node:path";import{promisify as nk}from"node:util";async function cp(r,e,t={}){let n=Date.now(),s=t.maxFiles??30,o=t.minScore??.1,i=t.includeTests??!1,a=ak(r),c=await ck(e),u=await lk(e),d=[];for(let p of c){if(!i&&dk(p))continue;let g=uk(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 ak(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 ck(r){let e=[];async function t(n,s=""){try{let o=await tk.readdir(n,{withFileTypes:!0});for(let i of o){let a=Oo.join(n,i.name),c=Oo.join(s,i.name);if(i.isDirectory()){if(ik.has(i.name)||i.name.startsWith("."))continue;await t(a,c)}else if(i.isFile()){let u=Oo.extname(i.name).toLowerCase();ok.has(u)&&e.push(c)}}}catch(o){C(o)}}return l(t,"walk"),await t(r),e}async function lk(r){let e=new Map;try{let{stdout:t}=await sk(`git log -30 --pretty=format:"%H %ct" --name-only | awk '
|
|
503
509
|
/^[a-f0-9]{40}/ { commit=$1; timestamp=$2; next }
|
|
504
510
|
NF { files[$0]++; if (!lastmod[$0]) lastmod[$0]=timestamp }
|
|
505
511
|
END { for (f in files) print files[f], lastmod[f], f }
|
|
506
512
|
'`,{cwd:r,maxBuffer:10485760}),n=Math.floor(Date.now()/1e3),s=t.trim().split(`
|
|
507
|
-
`).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],
|
|
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 uk(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(rk))for(let S of f)if(c.includes(S)&&e.some(v=>f.includes(v)||v.includes(g)||g.includes(v))){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=Oo.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 dk(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 sk,rk,ok,ik,lp=y(()=>{"use strict";F();sk=nk(ek),rk={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"]},ok=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".swift",".rb",".php",".c",".cpp",".h",".hpp",".cs",".vue",".svelte"]),ik=new Set(["node_modules",".git","dist","build",".next",".nuxt",".output","coverage",".cache","__pycache__",".pytest_cache","vendor","target",".turbo",".vercel"]);l(cp,"findRelevantFiles");l(ak,"extractKeywords");l(ck,"getAllCodeFiles");l(lk,"getGitRecency");l(uk,"scoreFile");l(dk,"isTestFile")});import{exec as pk}from"node:child_process";import{promisify as mk}from"node:util";async function up(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 hk(r);o=c.hotFiles,i=c.branchOnlyFiles,a=c.analysisWindow}else o=await fk(r,t);return o=o.filter(c=>!yk(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 fk(r,e){let{stdout:t}=await lr(`git log -${e} --pretty=format:"%ct" --name-only | awk '
|
|
508
514
|
/^[0-9]+$/ { timestamp=$1; next }
|
|
509
515
|
NF {
|
|
510
516
|
count[$0]++
|
|
@@ -514,7 +520,7 @@ Recommendations:
|
|
|
514
520
|
for (f in count) print count[f], lastmod[f], f
|
|
515
521
|
}
|
|
516
522
|
' | sort -rn`,{cwd:r,maxBuffer:10485760}),n=[],s=t.trim().split(`
|
|
517
|
-
`).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),
|
|
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),k=u/i,v=S*.6+k*.4,D;f<1?D="just now":f<24?D=`${f}h ago`:g<7?D=`${g}d ago`:g<30?D=`${Math.floor(g/7)}w ago`:D=`${Math.floor(g/30)}mo ago`,n.push({path:m,changes:u,heatScore:Math.round(v*100)/100,lastChanged:D,lastChangedAt:new Date(d*1e3).toISOString()})}return n.sort((a,c)=>c.heatScore-a.heatScore)}async function hk(r){let{stdout:e}=await lr("git branch --show-current",{cwd:r}),t=e.trim(),n="main";try{await lr("git rev-parse --verify main",{cwd:r})}catch{n="master"}let{stdout:s}=await lr(`git diff --name-only ${n}...HEAD`,{cwd:r}),o=s.trim().split(`
|
|
518
524
|
`).filter(Boolean),{stdout:i}=await lr(`git log ${n}..HEAD --pretty=format:"%ct" --name-only | awk '
|
|
519
525
|
/^[0-9]+$/ { timestamp=$1; next }
|
|
520
526
|
NF {
|
|
@@ -525,10 +531,10 @@ Recommendations:
|
|
|
525
531
|
for (f in count) print count[f], lastmod[f], f
|
|
526
532
|
}
|
|
527
533
|
'`,{cwd:r,maxBuffer:10*1024*1024}),a=[],c=i.trim().split(`
|
|
528
|
-
`).filter(Boolean),u=Math.floor(Date.now()/1e3),
|
|
529
|
-
`);return{file:r,language:o,signatures:a,fallback:!1,metrics:
|
|
530
|
-
`),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,
|
|
531
|
-
`).length,m=i[0].trim(),
|
|
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],k=u-f,v=Math.floor(k/86400),D=Math.floor(k/3600),q=Math.max(0,1-v/14),Me=g/d,qe=q*.5+Me*.5,ht;D<1?ht="just now":D<24?ht=`${D}h ago`:ht=`${v}d ago`,a.push({path:S,changes:g,heatScore:Math.round(qe*100)/100,lastChanged:ht,lastChangedAt:new Date(f*1e3).toISOString()})}return{hotFiles:a.sort((m,p)=>p.heatScore-m.heatScore),branchOnlyFiles:o,analysisWindow:`${n}..HEAD`}}function yk(r){let e=r.split("/").pop()||"";for(let t of gk)if(t.startsWith("*.")){if(e.endsWith(t.slice(1)))return!0}else if(e===t)return!0;return!1}var lr,gk,dp=y(()=>{"use strict";lr=mk(pk),gk=["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb",".gitignore",".env",".env.local","*.md","CHANGELOG.md","LICENSE"];l(up,"getRecentFiles");l(fk,"getHotFilesFromCommits");l(hk,"getBranchOnlyFiles");l(yk,"shouldIgnore")});function mc(r){return!r||r.length===0?0:Math.ceil(r.length/4)}function pp(r,e){let t=wk[e],n=r/1e3*t.input,s=r/1e3*t.output*.3;return{inputSaved:n,outputPotential:s,total:n+s}}function kk(r){return r<.001?"<$0.01":r<.01?`$${r.toFixed(3)}`:`$${r.toFixed(2)}`}function gp(r,e){let t=mc(r),n=mc(e),s=Math.max(0,t-n),o=t>0?(t-n)/t:0,i=pp(s,Sk),a=mp.map(c=>({model:c,...pp(s,c)}));return{tokens:{original:t,filtered:n,saved:s},compression:Math.max(0,Math.min(1,o)),cost:{saved:i.total,formatted:kk(i.total),byModel:a}}}function gc(r){let e=mc(r);return{tokens:{original:e,filtered:e,saved:0},compression:0,cost:{saved:0,formatted:"$0.00",byModel:mp.map(t=>({model:t,inputSaved:0,outputPotential:0,total:0}))}}}var wk,Sk,mp,fp=y(()=>{"use strict";wk={"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}},Sk="claude-sonnet-4.5";l(mc,"countTokens");mp=["claude-sonnet-4.5","claude-opus-4.5","claude-opus-4-6","gpt-4o","gemini-1.5-pro"];l(pp,"calculateModelCost");l(kk,"formatCostSaved");l(gp,"measureCompression");l(gc,"noCompression")});import bk from"node:fs/promises";import fc from"node:path";async function wp(r,e=process.cwd()){let t=fc.isAbsolute(r)?r:fc.join(e,r),n;try{n=await bk.readFile(t,"utf-8")}catch(u){if(C(u))return{file:r,language:"unknown",signatures:[],fallback:!0,fallbackReason:"File not found",metrics:gc("")};throw u}let s=fc.extname(r).toLowerCase(),o=Pk[s]||"unknown",i=Tk[o];if(!i||i.length===0)return{file:r,language:o,signatures:[],fallback:!0,fallbackReason:`No extraction patterns for ${o}`,metrics:gc(n)};let a=Ek(n,i),c=a.map(u=>`${u.exported?"export ":""}${u.type} ${u.name}: ${u.signature}`).join(`
|
|
535
|
+
`);return{file:r,language:o,signatures:a,fallback:!1,metrics:gp(n,c)}}function Ek(r,e){let t=[],n=r.split(`
|
|
536
|
+
`),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:Ak(m),exported:o.exported||!1,line:d,docstring:p})}}return t.sort((o,i)=>o.line-i.line)}function Ak(r){return r.replace(/\{$/,"").replace(/\s+/g," ").trim()}var Pk,hp,Ck,vk,xk,yp,Tk,Sp=y(()=>{"use strict";F();fp();Pk={".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"},hp=[{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}],Ck=[{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}],vk=[{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}],xk=[{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}],yp=[{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}],Tk={typescript:hp,javascript:hp,python:Ck,go:vk,rust:xk,java:yp,csharp:yp,php:[],ruby:[],unknown:[]};l(wp,"extractSignatures");l(Ek,"extractFromContent");l(Ak,"cleanSignature")});import{createHash as Ik}from"node:crypto";import Pp from"node:fs/promises";import Cp from"node:path";function kp(r){return Ik("sha256").update(r.toLowerCase().trim()).digest("hex").slice(0,16)}async function bp(r){try{let e=Cp.join(r,"storage","classification-cache.json"),t=await Pp.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return C(e)?Wi:(console.warn("[classifier] Failed to load cache:",w(e)),Wi)}}async function hc(r,e){try{let t=Cp.join(r,"storage","classification-cache.json");await Pp.writeFile(t,JSON.stringify(e,null,2))}catch(t){console.warn("[classifier] Failed to save cache:",w(t))}}function jk(r,e,t){let n=r.entries[e];return!n||n.projectId!==t||Date.now()-new Date(n.classifiedAt).getTime()>Dk?null:n.classification}function Rk(r,e){return r.confirmedPatterns.find(n=>n.descriptionHash===e)?.classification??null}async function $k(r,e){let t=process.env.ANTHROPIC_API_KEY;if(!t)return null;let n=vp(e),s=Ji("classification")||"",o=`Classify this software engineering task into a domain.
|
|
532
538
|
|
|
533
539
|
Task: "${r}"
|
|
534
540
|
|
|
@@ -536,166 +542,166 @@ Available domains in this project: ${n.join(", ")}
|
|
|
536
542
|
Available agents: ${e.agents.join(", ")||"none"}
|
|
537
543
|
Stack: ${e.stack?.language||"unknown"} / ${e.stack?.framework||"unknown"}
|
|
538
544
|
|
|
539
|
-
${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),
|
|
540
|
-
`);return{path:c.path,content:
|
|
541
|
-
`).filter(Boolean),i=0,a=0,c=0;for(let m of o){let
|
|
542
|
-
`)}_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`}},
|
|
543
|
-
`);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=
|
|
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=Zt.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 Fk(r,e){let t=vp(e),n=new Map;for(let[p,g]of Object.entries(Mk)){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 fu;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=Ok(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 vp(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 Ok(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 Dk,Mk,yc,_k,xp,Tp=y(()=>{"use strict";zs();Wr();F();Dk=3600*1e3;l(kp,"hashDescription");l(bp,"loadCache");l(hc,"saveCache");l(jk,"lookupCache");l(Rk,"lookupPatterns");l($k,"classifyWithLLM");Mk={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(Fk,"classifyWithHeuristic");l(vp,"buildAvailableDomains");l(Ok,"getFilePatterns");yc=class{static{l(this,"DomainClassifier")}async classify(e,t,n,s){let o=kp(e),i=await bp(n),a=jk(i,o,t);if(a)return{classification:a,source:"cache"};let c=Rk(i,o);if(c)return{classification:c,source:"history"};let u=await $k(e,s);if(u)return i.entries[o]={classification:u,classifiedAt:new Date().toISOString(),source:"llm",descriptionHash:o,projectId:t},await hc(n,i),{classification:u,source:"llm"};let d=Fk(e,s);return i.entries[o]={classification:d,classifiedAt:new Date().toISOString(),source:"heuristic",descriptionHash:o,projectId:t},await hc(n,i),{classification:d,source:"heuristic"}}async confirmClassification(e,t,n){let s=kp(e),o=await bp(n);o.confirmedPatterns.some(i=>i.descriptionHash===s)||(o.confirmedPatterns.push({descriptionHash:s,classification:t,confirmedAt:new Date().toISOString(),taskDescription:e}),await hc(n,o))}},_k=new yc,xp=_k});import{exec as Nk}from"node:child_process";import ur from"node:fs/promises";import Lk from"node:os";import In from"node:path";import{promisify as Uk}from"node:util";var Ep,Ap,wc,Hk,_o,Sc=y(()=>{"use strict";pc();it();re();Yn();Ct();lp();dp();Sp();F();An();Tp();cs();Ep=Uk(Nk),Ap=["database","backend","frontend","testing","devops"],wc=class{static{l(this,"OrchestratorExecutor")}async execute(e,t,n){let s=await R.getProjectId(n),o=T.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),cp(e,t,{maxFiles:10,minScore:.15}),up(t,{commits:10,maxFiles:10})]),i=s.files.slice(0,3),a=await Promise.all(i.map(async c=>{try{let u=await wp(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(`
|
|
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([Ep("git branch --show-current",{cwd:e}),Ep("git status --porcelain",{cwd:e})]),s=t.stdout.trim()||"main",o=n.stdout.trim().split(`
|
|
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 Ft.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 Xe.getAll(e);if(t.length===0)return null;let n=Fo(t,en);return n.sprints.length===0?null:ap(n)}catch{return null}}async loadRepoAnalysis(e){try{let t=In.join(e,"analysis","repo-analysis.json"),n=await ur.readFile(t,"utf-8");return JSON.parse(n)}catch(t){return C(t)||console.warn("Failed to load repo-analysis.json:",w(t)),null}}async detectDomains(e,t,n){let s=T.getGlobalProjectPath(t),o=await this.getAvailableAgentNames(s),i={hasFrontend:!1,hasBackend:!0,hasDatabase:!1,hasTesting:!1,hasDocker:!1};try{let m=await O.read(t);m.domains&&(i=m.domains)}catch{}let a={domains:i,agents:o,stack:n?{language:n.ecosystem}:void 0},{classification:c}=await xp.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=In.join(e,"agents");return(await ur.readdir(t)).filter(s=>s.endsWith(".md")).map(s=>s.replace(".md",""))}catch{return[]}}async loadAgents(e,t){let n=T.getGlobalProjectPath(t),s=In.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=In.join(s,u);try{let m=await ur.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=so(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=In.join(Lk.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=In.join(t,`${i}.md`),c=In.join(t,i,"SKILL.md");try{let u=await ur.readFile(c,"utf-8");return{name:i,content:u,filePath:c}}catch{try{let u=await ur.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=Ap.indexOf(a),d=Ap.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 O.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?"...":""}`}},Hk=new wc,_o=Hk});function Gk(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 kc,zk,Pe,Ip=y(()=>{"use strict";bt();te();Qt();Qt();l(Gk,"generateApprovalPrompt");kc=class{static{l(this,"PlanMode")}activePlans;constructor(){this.activePlans=new Map}requiresPlanning(e){return Ui.includes(e)}isDestructive(e){return Hi.includes(e)}isToolAllowedInPlanning(e){return Fr.includes(e)}getAllowedTools(e,t){return e?t.filter(n=>Fr.includes(n)):t}startPlanning(e,t,n){let s={id:ae(),projectId:e,command:t,params:n,status:Y.GATHERING,startedAt:b(),gatheredInfo:[],analysis:null,proposedPlan:null,userFeedback:null,approvedAt:null,executionStartedAt:null,completedAt:null,steps:[],currentStep:0};return this.activePlans.set(e,s),s}getActivePlan(e){return this.activePlans.get(e)||null}isInPlanningMode(e){let t=this.getActivePlan(e);return t?[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:b()})}updateStatus(e,t){let n=this.getActivePlan(e);n&&(n.status=t,t===Y.APPROVED?n.approvedAt=b():t===Y.EXECUTING?n.executionStartedAt=b():(t===Y.COMPLETED||t===Y.ABORTED)&&(n.completedAt=b()))}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=b(),n.steps=(n.proposedPlan?.steps||[]).map((s,o)=>({index:o,description:typeof s=="string"?s:s.description||"",status:"pending",tool:typeof s=="string"?void 0:s.tool,args:typeof s=="string"?void 0:s.args})),{approved:!0,planId:n.id,steps:n.steps,message:`Plan approved. ${n.steps.length} steps to execute.`})}rejectPlan(e,t=null){let n=this.getActivePlan(e);return n?(n.status=Y.REJECTED,n.userFeedback=t,n.completedAt=b(),this.activePlans.delete(e),{rejected:!0,planId:n.id,reason:t,message:"Plan rejected. No changes made."}):null}startExecution(e){let t=this.getActivePlan(e);return!t||t.status!==Y.APPROVED?null:(t.status=Y.EXECUTING,t.executionStartedAt=b(),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=b(),n.currentStep++,this.getNextStep(e))}failStep(e,t){let n=this.getActivePlan(e);return n?(n.steps[n.currentStep].status="failed",n.steps[n.currentStep].error=t,{failed:!0,step:n.currentStep+1,error:t,options:["retry","skip","abort"]}):null}completePlan(e){let t=this.getActivePlan(e);if(!t)return null;t.status=Y.COMPLETED,t.completedAt=b();let n={planId:t.id,command:t.command,totalSteps:t.steps.length,completedSteps:t.steps.filter(s=>s.status==="completed").length,failedSteps:t.steps.filter(s=>s.status==="failed").length,duration:this._calculateDuration(t.executionStartedAt,t.completedAt)};return this.activePlans.delete(e),n}abortPlan(e,t="User requested"){let n=this.getActivePlan(e);if(!n)return null;n.status=Y.ABORTED,n.completedAt=b(),n.abortReason=t;let s={aborted:!0,planId:n.id,reason:t,completedSteps:n.steps.filter(o=>o.status==="completed").length,totalSteps:n.steps.length};return this.activePlans.delete(e),s}generateApprovalPrompt(e,t){return Gk(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(`
|
|
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`}},zk=new kc,Pe=zk});function Wk(r){let e=r.trim().toLowerCase(),t=e.replace(/[.\s-]/g,"");return No[t]?No[t]:No[e]?No[e]:e}function Lo(r){let e=new Set,t=[];for(let n of r){let s=Wk(n);e.has(s)||(e.add(s),t.push(n))}return t}var No,bc=y(()=>{"use strict";No={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(Wk,"normalizeFrameworkName");l(Lo,"deduplicateTechStack")});import{z as Ce}from"zod";function Dp(r){let e=[];e.push(`## CONSTRAINTS (Read Before Acting)
|
|
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=Lo(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])=>Bk[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(`
|
|
544
550
|
Context: ${r.fileCount} files in project.`),e.join(`
|
|
545
|
-
`)}var
|
|
546
|
-
`,"utf-8"),
|
|
547
|
-
${[["project",r.projectName],["path",r.projectPath],["git",r.isGitRepo?"true":"false"],["branch",r.gitBranch],["platform",
|
|
551
|
+
`)}var A$,Bk,jp=y(()=>{"use strict";bc();A$=Ce.object({projectPath:Ce.string(),language:Ce.string().optional(),framework:Ce.string().optional(),techStack:Ce.array(Ce.string()).default([]),domains:Ce.object({hasFrontend:Ce.boolean().default(!1),hasBackend:Ce.boolean().default(!1),hasDatabase:Ce.boolean().default(!1),hasTesting:Ce.boolean().default(!1),hasDocker:Ce.boolean().default(!1)}).optional(),fileCount:Ce.number().optional(),availableAgents:Ce.array(Ce.string()).default([]),analysisLanguages:Ce.array(Ce.string()).default([]),analysisFrameworks:Ce.array(Ce.string()).default([]),analysisPackageManager:Ce.string().optional()}),Bk={hasFrontend:"Frontend (UI/components)",hasBackend:"Backend (APIs/servers)",hasDatabase:"Database (SQL/ORM)",hasTesting:"Testing (unit/integration)",hasDocker:"Docker/containers"};l(Dp,"buildAntiHallucinationBlock")});import{z as At}from"zod";var Vk,Rp,$p=y(()=>{"use strict";Vk=At.object({agents:At.boolean(),patterns:At.boolean(),checklist:At.boolean(),modules:At.array(At.string())}),Rp=At.object({version:At.string(),description:At.string().optional(),commands:At.record(At.string(),Vk).refine(r=>"*"in r,{message:'Config must include a "*" wildcard entry for unknown commands'})})});function Pc(r,e){return e.filter(t=>new RegExp(`\\b${t}\\b`).test(r)).length}function Mp(r,e){let t=(e.frontmatter?.description||"").toLowerCase(),n=e.content.toLowerCase(),s=e.frontmatter?.["allowed-tools"]||[],o=`${r} ${t} ${n}`,i=Pc(o,Jk),a=Pc(o,qk),c=Pc(o,Kk);return s.some(d=>Yk.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 Jk,qk,Kk,Yk,Fp=y(()=>{"use strict";Jk=["build","create","add","implement","fix","refactor","update","modify","change","write","generate","scaffold","migrate","optimize","improve","enhance","redesign","rewrite"],qk=["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"],Yk=["Write","Edit","Bash"];l(Pc,"countMatches");l(Mp,"classifyCommand")});import Cc from"node:fs/promises";import Xk from"node:path";async function _p(){if(dr)return dr;let r=await Cc.readFile(vc,"utf-8"),e=JSON.parse(r);return dr=Rp.parse(e),dr}function Qk(r){return Np.get(r)}function Zk(r,e){Np.set(r,e)}function tb(r,e){let t=r,n=Op.get(t);return n&&sb(n.entry,e)?(n.count++,n.count>=eb):(Op.set(t,{entry:e,count:1}),!1)}async function nb(r,e){let t=await Cc.readFile(vc,"utf-8"),n=JSON.parse(t);n.commands[r]=e,await Cc.writeFile(vc,`${JSON.stringify(n,null,2)}
|
|
552
|
+
`,"utf-8"),dr=null}function sb(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 Lp(r,e,t){if(e in r.commands&&e!=="*")return{entry:r.commands[e],source:"config"};let n=Qk(e);if(n)return{entry:n,source:"cache"};if(t){let s=Mp(e,t);return Zk(e,s),tb(e,s)&&nb(e,s).catch(()=>{}),{entry:s,source:"classified"}}return{entry:r.commands["*"],source:"wildcard"}}var vc,dr,Np,Op,eb,Up=y(()=>{"use strict";$p();kn();Fp();vc=Xk.join(be,"core/config/command-context.config.json"),dr=null;l(_p,"loadCommandContextConfig");Np=new Map;l(Qk,"getCachedClassification");l(Zk,"cacheClassification");Op=new Map,eb=3;l(tb,"trackClassification");l(nb,"persistClassification");l(sb,"isSameEntry");l(Lp,"resolveCommandContextFull")});import rb from"node:os";import{z as Lt}from"zod";function ob(){return typeof globalThis<"u"&&"Bun"in globalThis?"bun":"node"}function ib(r){return{darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD"}[r]??r}function Hp(r){let e=r.platform??rb.platform(),t=r.runtime??ob(),n=r.date??new Date().toISOString().split("T")[0];return`<env>
|
|
553
|
+
${[["project",r.projectName],["path",r.projectPath],["git",r.isGitRepo?"true":"false"],["branch",r.gitBranch],["platform",ib(e)],["runtime",t],["date",n],["model",r.model],["provider",r.provider]].filter(([,i])=>i!==void 0).map(([i,a])=>`${i}: ${a}`).join(`
|
|
548
554
|
`)}
|
|
549
|
-
</env>`}var
|
|
550
|
-
... (truncated to ~${e} tokens)`}function
|
|
551
|
-
`);return
|
|
552
|
-
`),s.role&&
|
|
553
|
-
`),s.skills?.length&&
|
|
554
|
-
`),
|
|
555
|
+
</env>`}var W$,Gp=y(()=>{"use strict";W$=Lt.object({projectName:Lt.string(),projectPath:Lt.string(),isGitRepo:Lt.boolean().default(!0),gitBranch:Lt.string().optional(),platform:Lt.string().optional(),runtime:Lt.string().optional(),date:Lt.string().optional(),model:Lt.string().optional(),provider:Lt.string().optional()});l(ob,"detectRuntime");l(ib,"normalizePlatform");l(Hp,"buildEnvironmentBlock")});function Wp(r){let e=r.getAllocationFor("injection");return{...Ho,totalPrompt:e}}function Dn(r,e){let t=e*Bp;return r.length<=t?r:`${r.substring(0,t)}
|
|
556
|
+
... (truncated to ~${e} tokens)`}function zp(r){return Math.ceil(r.length/Bp)}function Vp(r,e){if(e.length===0||r.length===0)return r;let t=new Set;for(let n of e){let s=ab[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 Ho,Bp,ab,Uo,Jp=y(()=>{"use strict";Ho={autoContext:500,agentContent:400,skillContent:500,stateData:1e3,memories:600,totalPrompt:8e3};l(Wp,"budgetsFromCoordinator");Bp=4;l(Dn,"truncateToTokenBudget");l(zp,"estimateTokens");ab={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(Vp,"filterSkillsByDomains");Uo=class{static{l(this,"InjectionBudgetTracker")}used=0;budgets;constructor(e={}){this.budgets={...Ho,...e}}addSection(e,t){let n=Dn(e,t),s=zp(n);if(this.used+s>this.budgets.totalPrompt){let o=this.budgets.totalPrompt-this.used;if(o<=0)return"";let i=Dn(n,o);return this.used+=zp(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 qp from"node:fs/promises";import jn from"node:path";var xc,cb,Kp,Yp=y(()=>{"use strict";Ct();F();Fe();kn();sc();jp();Up();Gp();Jp();bc();cs();xc=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 $(e)){let s=await qp.readFile(e,"utf-8");return this._templateCache.set(e,{content:s,loadedAt:n}),s}}catch(s){C(s)||console.error(`Template loading warning: ${w(s)}`)}return null}clearTemplateCache(){this._templateCache.clear(),this._checklistsCache=null,this._checklistsCacheTime=0,this._checklistRoutingCache=null,this._checklistRoutingCacheTime=0}setCoordinator(e){this._coordinator=e}getCoordinator(){return this._coordinator}getEffectiveBudgets(){return this._coordinator?Wp(this._coordinator):Ho}resetContext(){this._currentContext=null}setContext(e){this._currentContext=e}async loadModule(e){let t=Ae(`global/modules/${e}`);if(t)return t;let n=jn.join(be,"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=as("checklists/");if(n.length>0){for(let s of n)if(s.endsWith(".md")){let o=Ae(s);if(o){let i=jn.basename(s,".md");t[i]=o}}}else{let s=jn.join(be,"templates","checklists");if(await $(s)){let o=(await qp.readdir(s)).filter(i=>i.endsWith(".md"));for(let i of o){let a=i.replace(".md",""),c=jn.join(s,i),u=await this.getTemplate(c);u&&(t[a]=u)}}}}catch(n){C(n)||console.error(`Checklist loading warning: ${w(n)}`)}return this._checklistsCache=t,this._checklistsCacheTime=e,t}async getProjectState(e){if(!e)return null;let t=this._stateCache.get(e);if(t&&Date.now()-t.timestamp<this._stateCacheTTL)return t.state;try{let[n,s]=await Promise.all([O.read(e),ce.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 Za.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: ${w(o)}`)}n.push("---"),n.push("");let s=n.join(`
|
|
557
|
+
`);return Dn(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=jn.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 _p();p=Lp(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
|
+
`),s.role&&d.push(`Role: ${s.role}
|
|
559
|
+
`),s.skills?.length&&d.push(`Skills: ${s.skills.join(", ")}
|
|
560
|
+
`),d.push(`
|
|
555
561
|
Apply specialized expertise. Read agent file for details if needed.
|
|
556
562
|
|
|
557
|
-
`)),
|
|
558
|
-
`),e.frontmatter["allowed-tools"]&&
|
|
559
|
-
`);let f=t;(f.params?.task||f.params?.description)&&
|
|
560
|
-
`);let
|
|
563
|
+
`)),d.push(`TASK: ${e.frontmatter.description}
|
|
564
|
+
`),e.frontmatter["allowed-tools"]&&d.push(`TOOLS: ${e.frontmatter["allowed-tools"].join(", ")}
|
|
565
|
+
`);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?jn.basename(S):jn.basename(S),I=Hp({projectName:P,projectPath:S,isGitRepo:!0,gitBranch:u?.realContext?.gitBranch});d.push(`
|
|
561
567
|
${I}
|
|
562
|
-
`)}if(u){let
|
|
568
|
+
`)}if(u){let P=u.sealedAnalysis;if(d.push(`
|
|
563
569
|
## PROJECT ANALYSIS (Sealed)
|
|
564
|
-
`),
|
|
565
|
-
`),
|
|
566
|
-
`),
|
|
567
|
-
`),
|
|
568
|
-
`),
|
|
569
|
-
`),
|
|
570
|
-
`),
|
|
571
|
-
`),
|
|
572
|
-
`),
|
|
573
|
-
`),
|
|
574
|
-
`),
|
|
570
|
+
`),d.push(`**Ecosystem**: ${u.project.ecosystem}
|
|
571
|
+
`),d.push(`**Primary Domain**: ${u.primaryDomain}
|
|
572
|
+
`),d.push(`**Domains**: ${u.detectedDomains.join(", ")}
|
|
573
|
+
`),P){if(P.languages.length>0&&d.push(`**Languages**: ${P.languages.join(", ")}
|
|
574
|
+
`),P.frameworks.length>0&&d.push(`**Frameworks**: ${P.frameworks.join(", ")}
|
|
575
|
+
`),P.packageManager&&d.push(`**Package Manager**: ${P.packageManager}
|
|
576
|
+
`),P.sourceDir&&d.push(`**Source Dir**: ${P.sourceDir}
|
|
577
|
+
`),P.testDir&&d.push(`**Test Dir**: ${P.testDir}
|
|
578
|
+
`),d.push(`**Files Analyzed**: ${P.fileCount}
|
|
579
|
+
`),d.push(`**Analysis Status**: ${P.status}${P.commitHash?` (commit: ${P.commitHash.slice(0,8)})`:""}
|
|
580
|
+
`),P.patterns.length>0){d.push(`
|
|
575
581
|
### Code Patterns (Follow These)
|
|
576
|
-
`);for(let I of
|
|
577
|
-
`)}if(
|
|
582
|
+
`);for(let I of P.patterns)d.push(`- **${I.name}**: ${I.description}${I.location?` (${I.location})`:""}
|
|
583
|
+
`)}if(P.antiPatterns.length>0){d.push(`
|
|
578
584
|
### Anti-Patterns (Avoid These)
|
|
579
|
-
`);for(let I of
|
|
580
|
-
`)}}
|
|
581
|
-
`)}let
|
|
582
|
-
`),
|
|
585
|
+
`);for(let I of P.antiPatterns)d.push(`- **${I.issue}** in \`${I.file}\` \u2014 ${I.suggestion}
|
|
586
|
+
`)}}d.push(`
|
|
587
|
+
`)}let k=p.patterns,v=n?.codePatterns||"";if(k&&v&&v.trim()){let P=this.extractPatternSummary(v);P&&(d.push(`## CODE PATTERNS
|
|
588
|
+
`),d.push(P),d.push(`
|
|
583
589
|
Full patterns: Read analysis/patterns.md
|
|
584
|
-
`))}let
|
|
590
|
+
`))}let D=n?.analysis||"";if(k&&D&&D.trim()){let P=D.match(/Stack[:\s]+([^\n]+)/i)||D.match(/Technology[:\s]+([^\n]+)/i),I=P?P[1].trim():"detected";d.push(`
|
|
585
591
|
## STACK
|
|
586
592
|
Stack: ${I}
|
|
587
|
-
`),
|
|
588
|
-
`)}if(u){if(u.agents.length>0){
|
|
593
|
+
`),v||d.push(`Read analysis/repo-summary.md + similar files before coding. Match patterns exactly.
|
|
594
|
+
`)}if(u){if(u.agents.length>0){d.push(`
|
|
589
595
|
### LOADED AGENTS (Project-Specific Specialists)
|
|
590
596
|
|
|
591
|
-
`);for(let I of u.agents){
|
|
592
|
-
`),I.effort&&
|
|
593
|
-
`),I.model&&
|
|
594
|
-
`),I.skills.length>0&&
|
|
595
|
-
`);let
|
|
596
|
-
${
|
|
597
|
+
`);for(let I of u.agents){d.push(`#### Agent: ${I.name} (${I.domain})
|
|
598
|
+
`),I.effort&&d.push(`Effort: ${I.effort}
|
|
599
|
+
`),I.model&&d.push(`Model: ${I.model}
|
|
600
|
+
`),I.skills.length>0&&d.push(`Skills: ${I.skills.join(", ")}
|
|
601
|
+
`);let ke=Dn(I.content,this.getEffectiveBudgets().agentContent);d.push(`\`\`\`markdown
|
|
602
|
+
${ke}
|
|
597
603
|
\`\`\`
|
|
598
604
|
|
|
599
|
-
`)}}let
|
|
605
|
+
`)}}let P=Vp(u.skills,u.detectedDomains);if(P.length>0){d.push(`### LOADED SKILLS (From Agent Frontmatter)
|
|
600
606
|
|
|
601
|
-
`);for(let I of
|
|
602
|
-
`);let
|
|
603
|
-
${
|
|
607
|
+
`);for(let I of P){d.push(`#### Skill: ${I.name}
|
|
608
|
+
`);let ke=Dn(I.content,this.getEffectiveBudgets().skillContent);d.push(`\`\`\`markdown
|
|
609
|
+
${ke}
|
|
604
610
|
\`\`\`
|
|
605
611
|
|
|
606
|
-
`)}}}let
|
|
607
|
-
`),
|
|
612
|
+
`)}}}let q=this.getModulesForCommand(m,p);if(q.length>0)for(let P of q){let I=await this.loadModule(P);I&&(d.push(`
|
|
613
|
+
`),d.push(I))}if(c?.isPlanning&&(d.push(`
|
|
608
614
|
## PLAN MODE
|
|
609
615
|
Read-only. Gather info \u2192 Analyze \u2192 Propose plan \u2192 Wait for approval.
|
|
610
|
-
`),c.allowedTools&&
|
|
611
|
-
`)),c?.requiresApproval&&
|
|
616
|
+
`),c.allowedTools&&d.push(`Tools: ${c.allowedTools.join(", ")}
|
|
617
|
+
`)),c?.requiresApproval&&d.push(`
|
|
612
618
|
## APPROVAL REQUIRED
|
|
613
619
|
Show changes, list affected files, ask for confirmation.
|
|
614
|
-
`),
|
|
615
|
-
${
|
|
616
|
-
`)}else
|
|
620
|
+
`),S){let P=u?.sealedAnalysis,I=[...P?.frameworks||[],...u?.project?.conventions||[]],ke={projectPath:S,language:u?.project?.ecosystem,framework:P?.frameworks?.[0],techStack:Lo(I),domains:this.extractDomains(n),fileCount:t.files?.length||t.filteredSize||0,availableAgents:u?.agents?.map(H=>H.name)||[],analysisLanguages:P?.languages||[],analysisFrameworks:P?.frameworks||[],analysisPackageManager:P?.packageManager};d.push(`
|
|
621
|
+
${Dp(ke)}
|
|
622
|
+
`)}else d.push(this.buildCriticalRules());if(u?.realContext){let P=u.realContext;if(d.push(`
|
|
617
623
|
### CODEBASE CONTEXT
|
|
618
624
|
|
|
619
|
-
`),
|
|
625
|
+
`),d.push(`**Git State**: Branch \`${P.gitBranch}\` | ${P.gitStatus}
|
|
620
626
|
|
|
621
|
-
`),
|
|
622
|
-
`),
|
|
623
|
-
`),
|
|
624
|
-
`);for(let I of
|
|
625
|
-
`);
|
|
626
|
-
`)}if(
|
|
627
|
-
`);for(let I of
|
|
627
|
+
`),P.relevantFiles.length>0){d.push(`**Relevant Files** (scored by task relevance):
|
|
628
|
+
`),d.push(`| Score | File | Why |
|
|
629
|
+
`),d.push(`|-------|------|-----|
|
|
630
|
+
`);for(let I of P.relevantFiles.slice(0,8))d.push(`| ${I.score} | ${I.path} | ${I.reason} |
|
|
631
|
+
`);d.push(`
|
|
632
|
+
`)}if(P.signatures.length>0){d.push(`**Code Signatures** (top files):
|
|
633
|
+
`);for(let I of P.signatures)d.push(`\`\`\`typescript
|
|
628
634
|
// ${I.path}
|
|
629
635
|
${I.content}
|
|
630
636
|
\`\`\`
|
|
631
|
-
`);
|
|
632
|
-
`)}if(
|
|
637
|
+
`);d.push(`
|
|
638
|
+
`)}if(P.recentFiles.length>0){d.push("**Recently Changed**: ");let I=P.recentFiles.slice(0,5).map(ke=>`${ke.path} (${ke.lastChanged})`).join(", ");d.push(`${I}
|
|
633
639
|
|
|
634
|
-
`)}}let
|
|
635
|
-
## FILES: ${
|
|
636
|
-
`),
|
|
640
|
+
`)}}let Me=t.files||[];if(Me.length>0){let P=Me.slice(0,5).join(", ");d.push(`
|
|
641
|
+
## FILES: ${Me.length} available. Top: ${P}
|
|
642
|
+
`),d.push(`Read BEFORE modifying. Use Glob/Grep to find more.
|
|
637
643
|
|
|
638
|
-
`)}else
|
|
639
|
-
## PROJECT: ${
|
|
644
|
+
`)}else S&&d.push(`
|
|
645
|
+
## PROJECT: ${S}
|
|
640
646
|
Read files before modifying.
|
|
641
647
|
|
|
642
|
-
`);let
|
|
648
|
+
`);let qe=this.filterRelevantState(n);if(qe&&(d.push(`
|
|
643
649
|
## PRJCT STATE (Project Management Data)
|
|
644
|
-
`),
|
|
645
|
-
`)),u?.velocityContext&&(
|
|
650
|
+
`),d.push(qe),d.push(`
|
|
651
|
+
`)),u?.velocityContext&&(d.push(`
|
|
646
652
|
### VELOCITY (Historical Estimation Data)
|
|
647
653
|
|
|
648
|
-
`),
|
|
654
|
+
`),d.push(u.velocityContext),d.push(`
|
|
649
655
|
|
|
650
|
-
`)),o&&Object.keys(o).some(
|
|
656
|
+
`)),o&&Object.keys(o).some(P=>o[P])){d.push(`
|
|
651
657
|
## PROJECT DEFAULTS (apply automatically)
|
|
652
|
-
`);for(let[
|
|
653
|
-
`)}if(i?.plan&&i.plan.length>0){if(
|
|
658
|
+
`);for(let[P,I]of Object.entries(o))I&&d.push(`- ${P}: ${I}
|
|
659
|
+
`)}if(i?.plan&&i.plan.length>0){if(d.push(`
|
|
654
660
|
## THINK FIRST (reasoning from analysis)
|
|
655
|
-
`),i.conclusions&&i.conclusions.length>0){
|
|
656
|
-
`);for(let
|
|
657
|
-
`)}
|
|
658
|
-
`);for(let
|
|
659
|
-
`);
|
|
660
|
-
`)}if(a&&a.length>0){
|
|
661
|
+
`),i.conclusions&&i.conclusions.length>0){d.push(`Conclusions:
|
|
662
|
+
`);for(let P of i.conclusions)d.push(` \u2192 ${P}
|
|
663
|
+
`)}d.push(`Plan:
|
|
664
|
+
`);for(let P=0;P<i.plan.length;P++)d.push(` ${P+1}. ${i.plan[P]}
|
|
665
|
+
`);d.push(`Confidence: ${Math.round((i.confidence||.5)*100)}%
|
|
666
|
+
`)}if(a&&a.length>0){d.push(`
|
|
661
667
|
## CONTEXT (apply these)
|
|
662
|
-
`);for(let
|
|
663
|
-
`),
|
|
664
|
-
`)}if(
|
|
668
|
+
`);for(let P of a)d.push(`- **${P.title}**: ${P.content}
|
|
669
|
+
`),P.tags&&P.tags.length>0&&d.push(` Tags: ${P.tags.join(", ")}
|
|
670
|
+
`)}if(d.push(`
|
|
665
671
|
---
|
|
666
|
-
`),
|
|
672
|
+
`),d.push(e.content),u?.requiresFragmentation&&u.subtasks){d.push(`
|
|
667
673
|
### SUBTASKS (Execute in Order)
|
|
668
674
|
|
|
669
|
-
`),
|
|
670
|
-
`),
|
|
671
|
-
`);for(let I of u.subtasks){let
|
|
672
|
-
`)}let
|
|
673
|
-
**FOCUS ON SUBTASK #${
|
|
674
|
-
`),
|
|
675
|
-
`),
|
|
676
|
-
`),
|
|
675
|
+
`),d.push("**IMPORTANT**: Focus on the CURRENT subtask. Use `p. done` when complete to advance.\n\n"),d.push(`| # | Domain | Description | Status |
|
|
676
|
+
`),d.push(`|---|--------|-------------|--------|
|
|
677
|
+
`);for(let I of u.subtasks){let ke=I.status==="in_progress"?"\u25B6\uFE0F **CURRENT**":I.status==="completed"?"\u2705 Done":I.status==="failed"?"\u274C Failed":"\u23F3 Pending";d.push(`| ${I.order} | ${I.domain} | ${I.description} | ${ke} |
|
|
678
|
+
`)}let P=u.subtasks.find(I=>I.status==="in_progress");if(P&&(d.push(`
|
|
679
|
+
**FOCUS ON SUBTASK #${P.order}**: ${P.description}
|
|
680
|
+
`),d.push(`Agent: ${P.agent} | Domain: ${P.domain}
|
|
681
|
+
`),P.dependsOn.length>0&&d.push(`Dependencies: ${P.dependsOn.join(", ")}
|
|
682
|
+
`),P.handoff)){let I=P.handoff;d.push(`
|
|
677
683
|
### Previous Subtask Handoff
|
|
678
684
|
|
|
679
|
-
`),
|
|
685
|
+
`),d.push(`**From:** ${I.fromSubtask}
|
|
680
686
|
|
|
681
|
-
`),
|
|
682
|
-
`);for(let
|
|
683
|
-
`);if(I.filesChanged.length>0){
|
|
687
|
+
`),d.push(`**What was done:**
|
|
688
|
+
`);for(let ke of I.whatWasDone)d.push(`- ${ke}
|
|
689
|
+
`);if(I.filesChanged.length>0){d.push(`
|
|
684
690
|
**Files changed:**
|
|
685
|
-
`);for(let
|
|
686
|
-
`)}
|
|
691
|
+
`);for(let ke of I.filesChanged)d.push(`- \`${ke.path}\` (${ke.action})
|
|
692
|
+
`)}d.push(`
|
|
687
693
|
**Context for this subtask:**
|
|
688
694
|
${I.outputForNextAgent}
|
|
689
|
-
`)}
|
|
690
|
-
`)}let
|
|
695
|
+
`)}d.push(`
|
|
696
|
+
`)}let ht=this.getSchemaTypeForCommand(m);if(ht){let{renderSchemaForPrompt:P}=await Promise.resolve().then(()=>(Wr(),vu)),I=P(ht);I&&d.push(`
|
|
691
697
|
${I}
|
|
692
|
-
`)}if(
|
|
698
|
+
`)}if(p.checklist){let P=await this.loadChecklistRouting(),I=await this.loadChecklists();P&&Object.keys(I).length>0&&(d.push(`
|
|
693
699
|
## QUALITY CHECKLISTS
|
|
694
|
-
`),
|
|
695
|
-
`),
|
|
696
|
-
`),
|
|
697
|
-
`),
|
|
698
|
-
`))}return
|
|
700
|
+
`),d.push(`Apply relevant checklists based on task. Read checklist-routing.md for guidance.
|
|
701
|
+
`),d.push(`Available: ${Object.keys(I).join(", ")}
|
|
702
|
+
`),d.push(`Path: templates/checklists/{name}.md
|
|
703
|
+
`),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 Uo({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}
|
|
699
705
|
${a}`,c);u&&o.push(u)}return o.length>0?o.join(`
|
|
700
706
|
|
|
701
707
|
`):null}buildAnalysis(e,t){let n=[];return n.push(`# Analyze: ${e}
|
|
@@ -712,7 +718,7 @@ ${a}`,c);u&&o.push(u)}return o.length>0?o.join(`
|
|
|
712
718
|
`);a&&t.push(a)}let s=e.match(/### High Priority[\s\S]*?(?=###|##|$)/i);if(s){let a=s[0].substring(0,300);t.push(`
|
|
713
719
|
Avoid:
|
|
714
720
|
${a}`)}let o=t.join(`
|
|
715
|
-
`);return
|
|
721
|
+
`);return Dn(o,200)||null}getSchemaTypeForCommand(e){return{task:"subtaskBreakdown",bug:"classification"}[e]??null}buildCriticalRules(){return`
|
|
716
722
|
## RULES (CRITICAL)
|
|
717
723
|
1. **READ FIRST**: Use Read tool BEFORE modifying any file. Never assume code structure.
|
|
718
724
|
2. **MATCH PATTERNS**: Follow existing style, architecture, naming, imports exactly.
|
|
@@ -729,7 +735,7 @@ Context: ${this._currentContext?.files?.length||this._currentContext?.filteredSi
|
|
|
729
735
|
- Prefer structured output (JSON) over free text when applicable.
|
|
730
736
|
|
|
731
737
|
EXECUTE: Follow flow. Use tools. Decide.
|
|
732
|
-
`}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}}}},
|
|
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}}}},cb=new xc,Kp=cb});import Xp from"node:fs/promises";import pt from"node:path";var lb,ub,Tc,Ec,Go,Ac=y(()=>{"use strict";it();re();F();lb=["task","done","ship","resume","bug","enrich"],ub=["init","sync","pause","next","dash","history","undo","redo"],Tc=class{static{l(this,"TemplateExecutor")}async getNpmRoot(){return pt.dirname(xi.resolve("prjct-cli/package.json"))}async getProjectId(e){return R.getProjectId(e)}async buildContext(e,t,n){let s=await this.getProjectId(n),o=T.getGlobalProjectPath(s),a=await(Ke(),ut(st)).getActiveProvider(),c;try{let u=await this.getNpmRoot();c=pt.join(u,"templates")}catch{c=pt.join(__dirname,"..","..","templates")}return{projectPath:n,projectId:s,globalPath:o,command:e,args:t,agentName:a.displayName,agentSettingsPath:await T.getAgentSettingsPath(),paths:{orchestrator:pt.join(c,"agentic","orchestrator.md"),agentRouting:pt.join(c,"agentic","agent-routing.md"),taskFragmentation:pt.join(c,"agentic","task-fragmentation.md"),commandTemplate:pt.join(c,"commands",`${e}.md`),repoAnalysis:pt.join(o,"analysis","repo-analysis.json"),agentsDir:pt.join(o,"agents"),skillsDir:a.skillsDir,stateJson:pt.join(o,"storage","state.json")}}}requiresOrchestration(e){return lb.includes(e)?!0:!ub.includes(e)}async hasAgents(e){try{let t=await this.getProjectId(e),n=pt.join(T.getGlobalProjectPath(t),"agents");return(await Xp.readdir(n)).some(o=>o.endsWith(".md"))}catch(t){return C(t),!1}}async getAvailableAgents(e){try{let t=await this.getProjectId(e),n=pt.join(T.getGlobalProjectPath(t),"agents");return(await Xp.readdir(n)).filter(o=>o.endsWith(".md")).map(o=>o.replace(".md",""))}catch{return[]}}buildAgenticPrompt(e){let t=this.requiresOrchestration(e.command);return{prompt:`
|
|
733
739
|
## Agentic Execution Mode
|
|
734
740
|
|
|
735
741
|
You are executing a prjct command as ${e.agentName}. Follow the template-first approach.
|
|
@@ -812,13 +818,13 @@ When fragmenting tasks:
|
|
|
812
818
|
2. Track progress: currentSubtaskIndex, subtaskProgress
|
|
813
819
|
3. Each completed subtask generates a summary
|
|
814
820
|
4. Pass summary to next agent for context handoff
|
|
815
|
-
`,context:e,requiresOrchestration:t}}},
|
|
816
|
-
`+
|
|
817
|
-
`+
|
|
818
|
-
`+
|
|
819
|
-
`+
|
|
820
|
-
`+
|
|
821
|
-
`}},
|
|
821
|
+
`,context:e,requiresOrchestration:t}}},Ec=new Tc,Go=Ec});import{exec as db}from"node:child_process";import Qp from"node:fs/promises";import{promisify as pb}from"node:util";var mb,Rn,Re,Ic=y(()=>{"use strict";ao();mb=pb(db),Rn={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())}};Rn.register("Read",async r=>{try{return await nr.execute(async()=>await Qp.readFile(r,"utf-8"),`read-${r}`)}catch(e){return io(e)||tr(e),null}});Rn.register("Write",async(r,e)=>{try{return await nr.execute(async()=>await Qp.writeFile(r,e,"utf-8"),`write-${r}`),!0}catch(t){return io(t)||tr(t),!1}});Rn.register("Bash",async r=>{try{return await nr.execute(async()=>await mb(r),`bash-${r}`)}catch(e){let t=e;return{stdout:t.stdout||"",stderr:t.stderr||t.message||"Command failed"}}});Rn.register("GetTimestamp",async()=>new Date().toISOString());Rn.register("GetDate",async()=>new Date().toISOString().split("T")[0]);Rn.register("GetDateTime",async()=>new Date().toISOString());Re=Rn});import Dc from"node:fs/promises";import gb from"node:os";import Zp from"node:path";async function fb(r){try{let e=Zp.dirname(zo);await $(e)||await Dc.mkdir(e,{recursive:!0}),await Dc.writeFile(zo,`/p:${r}`)}catch{}}async function hb(){try{await $(zo)&&await Dc.unlink(zo)}catch{}}var zo,jc,yb,Wo,Rc=y(()=>{"use strict";F();Ld();Fe();Gd();Wd();ic();sp();rp();rs();Sc();Ip();Yp();Ac();cs();Ic();zo=Zp.join(gb.homedir(),".prjct-cli",".running");l(fb,"signalStart");l(hb,"signalEnd");jc=class{static{l(this,"CommandExecutor")}async signalStart(e){await fb(e)}async signalEnd(){await hb()}async execute(e,t,n){await this.signalStart(e);let s=t.task||t.description||"";if(fs.shouldEscalate(e,s)){let o=fs.getEscalationInfo(e,s);return await this.signalEnd(),{success:!1,error:o?.message,escalation:o,isLoopDetected:!0,suggestion:o?.suggestion}}try{let o=await Ea.load(e),i=await Qe.build(n,t),a=Pe.requiresPlanning(e),c=Pe.isDestructive(e),u=Pe.isInPlanningMode(i.projectId),d=null;a&&!u&&!t.skipPlanning?d=Pe.startPlanning(i.projectId,e,t):u&&(d=Pe.getActivePlan(i.projectId));let m=null;if(Mo.requiresVerification(e)){let P=await Qe.loadStateForCommand(i,e);m=await Mo.verify(e,i,P),!m.verified&&m.warnings.length>0&&console.log(Mo.formatWarnings(m))}let p=null;if($o.requiresReasoning(e)){let P=await Qe.loadStateForCommand(i,e);p=await $o.reason(e,i,P),p.reasoning&&!p.reasoning.allPassed&&(console.log("\u26A0\uFE0F Chain of Thought detected issues:"),console.log($o.formatPlan(p)))}let g=t.task||t.description||"",f=await Go.buildContext(e,g,n),S=Go.buildAgenticPrompt(f),k=null;if(Go.requiresOrchestration(e)&&g)try{k=await _o.execute(e,g,n),k.detectedDomains.length>0&&Ro.orchestrate(k.detectedDomains);for(let P of k.agents){let I=P.domain||P.name.replace(".md","");Ro.startAgent(P.name,I,`Loading ${I} specialist...`),Ro.endAgent(!0)}if(k.requiresFragmentation&&k.subtasks){let P=k.subtasks.map(I=>({id:I.id,domain:I.domain,description:I.description,status:I.status}));Hd(P)}}catch(P){console.warn(`\u26A0\uFE0F Orchestrator warning: ${w(P)}`)}let v={...i,agentsPath:f.paths.agentsDir,agentRoutingPath:f.paths.agentRouting,orchestratorPath:f.paths.orchestrator,taskFragmentationPath:f.paths.taskFragmentation,agenticDelegation:!0,agenticMode:!0},D=await Qe.loadState(i),q=null,Me=null;i.projectId&&(q={commit_footer:await pe.getSmartDecision(i.projectId,"commit_footer"),branch_naming:await pe.getSmartDecision(i.projectId,"branch_naming"),test_before_ship:await pe.getSmartDecision(i.projectId,"test_before_ship"),preferred_agent:await pe.getSmartDecision(i.projectId,`preferred_agent_${e}`)},Me=await pe.getRelevantMemories(i.projectId,{commandName:e,params:t},5));let qe={isPlanning:a||u,requiresApproval:c&&!t.approved,active:d,allowedTools:Pe.getAllowedTools(u,o.frontmatter["allowed-tools"]||[])},ht=await Kp.build(o,v,D,null,q,null,Me,qe,k);return console.log("\u{1F916} Template-first execution: Claude reads templates and decides"),S.requiresOrchestration&&console.log(` \u2192 Orchestration: ${f.paths.orchestrator}`),fs.recordSuccess(e,s),await this.signalEnd(),{success:!0,template:o,context:v,state:D,prompt:ht,agenticDelegation:!0,agenticMode:!0,agenticExecContext:f,agenticPrompt:S.prompt,requiresOrchestration:S.requiresOrchestration,agentsPath:v.agentsPath,agentRoutingPath:v.agentRoutingPath,orchestratorPath:f.paths.orchestrator,taskFragmentationPath:f.paths.taskFragmentation,reasoning:p,groundTruth:m,learnedPatterns:q,relevantMemories:Me,orchestratorContext:k,memory:{create:l(P=>pe.createMemory(i.projectId,P),"create"),autoRemember:l((P,I,ke)=>pe.autoRemember(i.projectId,P,I,ke),"autoRemember"),search:l(P=>pe.searchMemories(i.projectId,P),"search"),findByTags:l(P=>pe.findByTags(i.projectId,P),"findByTags"),getStats:l(()=>pe.getMemoryStats(i.projectId),"getStats")},plan:{active:d,isPlanning:a||u,isDestructive:c,requiresApproval:c&&!t.approved,recordInfo:l(P=>Pe.recordGatheredInfo(i.projectId,P),"recordInfo"),setAnalysis:l(P=>Pe.setAnalysis(i.projectId,P),"setAnalysis"),propose:l(P=>Pe.proposePlan(i.projectId,P),"propose"),approve:l(P=>Pe.approvePlan(i.projectId,P),"approve"),reject:l(P=>Pe.rejectPlan(i.projectId,P),"reject"),getApprovalPrompt:l(()=>Pe.generateApprovalPrompt(e,{changedFiles:[],filesToDelete:[],operation:e==="ship"?"git_push":e==="cleanup"?"delete_files":"run_command",warnings:[]}),"getApprovalPrompt"),startExecution:l(()=>Pe.startExecution(i.projectId),"startExecution"),getNextStep:l(()=>Pe.getNextStep(i.projectId),"getNextStep"),completeStep:l(P=>Pe.completeStep(i.projectId,P),"completeStep"),failStep:l(P=>Pe.failStep(i.projectId,P),"failStep"),abort:l(P=>Pe.abortPlan(i.projectId,P),"abort"),getStatus:l(()=>Pe.formatStatus(i.projectId),"getStatus"),getAllowedTools:l(()=>Pe.getAllowedTools(u,o.frontmatter["allowed-tools"]||[]),"getAllowedTools")}}}catch(o){await this.signalEnd();let i=fs.recordAttempt(e,s,{success:!1,error:w(o)});if(i.shouldEscalate){let a=fs.getEscalationInfo(e,s);return{success:!1,error:a?.message,escalation:a,isLoopDetected:!0,suggestion:a?.suggestion}}return{success:!1,error:w(o),attemptNumber:i.attemptNumber,isLooping:i.isLooping}}}async executeTool(e,t,n){if(!Re.isAllowed(e,n))throw new Error(`Tool ${e} not allowed for this command`);let s=Re.get(e);if(!s)throw new Error(`Tool ${e} not found`);return await s(...t)}async executeSimple(e,t,n){try{let o=(await Ea.load(e)).frontmatter["allowed-tools"]||[],i=await Qe.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:w(s)}}}},yb=new jc,Wo=yb});import Bo from"node:fs/promises";import wb from"node:https";import Sb from"node:os";import $c from"node:path";import It from"chalk";var Mc,em,tm=y(()=>{"use strict";F();Fe();Mc=class{static{l(this,"UpdateChecker")}packageName;cacheDir;cacheFile;checkInterval;constructor(){this.packageName="prjct-cli",this.cacheDir=$c.join(Sb.homedir(),".prjct-cli","config"),this.cacheFile=$c.join(this.cacheDir,"update-cache.json"),this.checkInterval=1440*60*1e3}async getCurrentVersion(){try{let e=$c.join(__dirname,"..","..","package.json");return JSON.parse(await Bo.readFile(e,"utf8")).version}catch(e){return console.error("Error reading package version:",w(e)),null}}async getLatestVersion(){return new Promise((e,t)=>{let n={hostname:"registry.npmjs.org",path:`/${this.packageName}/latest`,method:"GET",headers:{"User-Agent":"prjct-cli-update-checker",Accept:"application/json"}},s=wb.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 $(this.cacheFile))return JSON.parse(await Bo.readFile(this.cacheFile,"utf8"))}catch{}return null}async writeCache(e){try{await $(this.cacheDir)||await Bo.mkdir(this.cacheDir,{recursive:!0}),await Bo.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:`
|
|
822
|
+
`+It.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")+`
|
|
823
|
+
`+It.yellow("\u2502")+" "+It.bold("Update available!")+" "+It.dim(`${e.currentVersion} \u2192 ${e.latestVersion}`)+" "+It.yellow("\u2502")+`
|
|
824
|
+
`+It.yellow("\u2502")+" "+It.yellow("\u2502")+`
|
|
825
|
+
`+It.yellow("\u2502")+" Run: "+It.cyan("npm update -g prjct-cli")+" "+It.yellow("\u2502")+`
|
|
826
|
+
`+It.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")+`
|
|
827
|
+
`}},em=Mc});var le,We=y(()=>{"use strict";Rc();ic();Ic();it();re();tm();cn();te();Fe();Tn();le=class{static{l(this,"PrjctCommandsBase")}prjctDir;updateChecker;updateNotificationShown;commandExecutor;constructor(){this.prjctDir=".prjct",this.updateChecker=new em,this.updateNotificationShown=!1,this.commandExecutor=Wo}get agent(){return us.getAgent()}get agentInfo(){return us.getInfo()}get currentAuthor(){return an.getCurrentAuthor()}async initializeAgent(){return us.initialize()}async ensureProjectInit(e){return an.ensureInit(e)}async ensureAuthor(){return an.ensureAuthor()}async getGlobalProjectPath(e){return an.getGlobalPath(e)}async logToMemory(e,t,n){let s=await this.ensureAuthor();return Ye.log(e,t,n,s.name)}async _detectEmptyDirectory(e){return an.isEmptyDirectory(e)}async _detectExistingCode(e){return an.hasExistingCode(e)}_breakdownFeatureTasks(e){return ho.breakdownFeature(e)}_detectBugSeverity(e){return ho.detectBugSeverity(e)}async _assignAgentForTask(e,t,n){return us.assignForTask(e,t,n)}}});var nm={};Ln(nm,{PlanningCommands:()=>Mn});import $n from"node:path";async function kb(){if(!Fc){let{AnalysisCommands:r}=await Promise.resolve().then(()=>(Jo(),sm));Fc=new r}return Fc}var Fc,Mn,Vo=y(()=>{"use strict";lo();Pn();bt();Ct();F();ps();ms();sc();We();Fc=null;l(kb,"getAnalysisCommands");Mn=class extends le{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 gs(t).runNonInteractive());else if(a=await new gs(t).run(),a.skipped)return{success:!1,message:"Setup cancelled"};h.step(1,4,"Detecting author...");let c=await ls(),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 T.ensureProjectStructure(m);let p=T.getGlobalProjectPath(m),g={"core/now.md":`# NOW
|
|
822
828
|
|
|
823
829
|
No current task. Use \`/p:now\` to set focus.
|
|
824
830
|
`,"core/next.md":`# NEXT
|
|
@@ -838,29 +844,29 @@ No current task. Use \`/p:now\` to set focus.
|
|
|
838
844
|
`,"planning/roadmap.md":`# ROADMAP
|
|
839
845
|
|
|
840
846
|
`,"planning/specs/.gitkeep":`# Specs directory - created by /p:spec
|
|
841
|
-
`,"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[
|
|
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[v,D]of Object.entries(g))await Re.get("Write")($n.join(p,v),D);let f=await this._detectEmptyDirectory(t),S=await this._detectExistingCode(t);if(S||!f){h.step(3,4,"Analyzing project...");let v=await kb();if((await v.analyze({},t)).success)return h.step(4,4,"Generating agents..."),a?.agents?await v.sync(t,{aiTools:a.agents}):await v.sync(t),h.done("initialized"),this._printNextSteps(a),{success:!0,mode:"existing",projectId:m,wizard:a}}let k=n.idea;if(f&&!S){if(!k)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 v=$n.join(p,"planning","architect-session.md"),D=`# Architect Session
|
|
842
848
|
|
|
843
849
|
## Idea
|
|
844
|
-
${
|
|
850
|
+
${k}
|
|
845
851
|
|
|
846
852
|
## Status
|
|
847
853
|
Initialized - awaiting stack recommendation
|
|
848
854
|
|
|
849
855
|
Generated: ${new Date().toLocaleString()}
|
|
850
|
-
`;return await
|
|
851
|
-
`);let s=await this.getGlobalProjectPath(t),o
|
|
856
|
+
`;return await Re.get("Write")(v,D),await Ge.installGlobalConfig(),h.done("architect mode ready"),{success:!0,mode:"architect",projectId:m,idea:k,wizard:a}}return await Ge.installGlobalConfig(),h.done("initialized"),this._printNextSteps(a),{success:!0,projectId:m,wizard:a}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}_printNextSteps(e){if(console.log(""),console.log(" Quick start:"),console.log(" prjct sync Update context after changes"),console.log(" prjct task Start working on a task"),console.log(" prjct hooks Auto-sync on commit/checkout"),console.log(""),e){let t=e.agents.map(n=>{switch(n){case"claude":return"CLAUDE.md";case"cursor":return".cursorrules";case"windsurf":return".windsurfrules";case"copilot":return".github/copilot-instructions.md";case"gemini":return"GEMINI.md";default:return null}}).filter(Boolean);t.length>0&&(console.log(` Generated: ${t.join(", ")}`),console.log(""))}console.log(" Docs: https://prjct.app/docs"),console.log("")}async feature(e,t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;if(!e)return h.fail("description required"),{success:!1,error:"Description required"};let s=await 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 Qe.build(t,{description:e}),i=this._breakdownFeatureTasks(e),a=ae(),c=[];for(let m of i){let g=(await this._assignAgentForTask(m,t,o)).agent?.name||"generalist";c.push({task:m,agent:g})}await ce.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:L.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(w(n)),{success:!1,error:w(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 Qe.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 ce.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:L.getTimestamp()}),n.md?console.log(me(ze("Bug Reported",e),Et({Severity:a,Priority:m,Agent:u}),_e([{label:"Fix now",command:`prjct task "fix: ${e}" --md`},{label:"View queue",command:"prjct next --md"}]))):(h.done(`bug [${a}] \u2192 ${u}`),ct("bug")),{success:!0,bug:e,severity:a,agent:u}}catch(s){return n.md||h.fail(w(s)),{success:!1,error:w(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
|
|
857
|
+
`);let s=await this.getGlobalProjectPath(t),o=$n.join(s,"planning","architect-session.md"),i;try{i=await ne.readFile(o)}catch{return{success:!1,message:`\u274C No architect plan found.
|
|
852
858
|
|
|
853
859
|
Create a plan first:
|
|
854
860
|
1. Run /p:init in an empty directory
|
|
855
861
|
2. Answer the discovery questions
|
|
856
862
|
3. Plan will be auto-generated
|
|
857
863
|
4. Then run /p:architect execute`}}if(!i||i.trim()==="")return{success:!1,message:"\u274C Architect plan is empty"};console.log(`\u{1F4CB} Reading architect plan...
|
|
858
|
-
`);let a=i.match(/## Project Idea\n(.+)/s),c=i.match(/\*\*Stack:\*\*\n([\s\S]+?)\n\n/),u=i.match(/\*\*Implementation Steps:\*\*\n([\s\S]+?)\n\n/),
|
|
859
|
-
`)[0].trim():"Unknown project",m=c?c[1]:"Not specified",
|
|
864
|
+
`);let a=i.match(/## Project Idea\n(.+)/s),c=i.match(/\*\*Stack:\*\*\n([\s\S]+?)\n\n/),u=i.match(/\*\*Implementation Steps:\*\*\n([\s\S]+?)\n\n/),d=a?a[1].split(`
|
|
865
|
+
`)[0].trim():"Unknown project",m=c?c[1]:"Not specified",p=u?u[1]:"Not specified";return console.log(`\u{1F4DD} Project: ${d}`),console.log(`
|
|
860
866
|
\u{1F527} Stack:
|
|
861
867
|
${m}`),console.log(`
|
|
862
868
|
\u{1F4CB} Implementation Steps:
|
|
863
|
-
${
|
|
869
|
+
${p}`),console.log(`
|
|
864
870
|
${"=".repeat(60)}`),console.log("\u{1F916} READY TO GENERATE CODE"),console.log("=".repeat(60)),console.log(`
|
|
865
871
|
The architect plan is ready. Claude will now:
|
|
866
872
|
1. Read the architectural plan
|
|
@@ -869,7 +875,7 @@ The architect plan is ready. Claude will now:
|
|
|
869
875
|
4. Create starter files with boilerplate
|
|
870
876
|
`),console.log(`
|
|
871
877
|
\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.
|
|
872
|
-
`),await this.logToMemory(t,"architect_executed",{timestamp:
|
|
878
|
+
`),await this.logToMemory(t,"architect_executed",{timestamp:L.getTimestamp(),idea:d}),{success:!0,plan:i,idea:d}}catch(n){return console.error("\u274C Error:",w(n)),{success:!1,error:w(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=T.getGlobalProjectPath(o),u=$n.join(c,"planning","architect-session.md"),d=`# Architect Session
|
|
873
879
|
|
|
874
880
|
## Idea
|
|
875
881
|
${e}
|
|
@@ -884,14 +890,14 @@ Initialized - awaiting architecture design
|
|
|
884
890
|
4. Generate roadmap
|
|
885
891
|
|
|
886
892
|
Generated: ${new Date().toLocaleString()}
|
|
887
|
-
`;return await
|
|
893
|
+
`;return await Re.get("Write")(u,d),await this.logToMemory(t,"idea_architecture_started",{idea:e,timestamp:L.getTimestamp()}),n.md?console.log(me(ze("Idea Captured",e),Et({Mode:"architecture"}),_e([{label:"Continue planning",command:"prjct architect execute"}]))):(h.done("architecture session created"),console.log(`
|
|
888
894
|
\u{1F4A1} Use /p:architect execute to continue planning
|
|
889
|
-
`),{success:!0,mode:"architecture",idea:e}}else return h.spin("capturing idea..."),await
|
|
895
|
+
`)),{success:!0,mode:"architecture",idea:e}}else return n.md||h.spin("capturing idea..."),await Ee.addIdea(o,e),await this.logToMemory(t,"idea_captured",{idea:e,timestamp:L.getTimestamp()}),n.md?console.log(me(ze("Idea Captured",e),Et({Mode:"capture"}),_e([{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)}`),ct("idea")),{success:!0,mode:"capture",idea:e}}catch(s){return n.md||h.fail(w(s)),{success:!1,error:w(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=T.getGlobalProjectPath(s),m=$n.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(`
|
|
890
896
|
\u{1F4A1} Create one with /p:spec "feature name"
|
|
891
897
|
`),{success:!0,specs:[]}):(console.log(`
|
|
892
898
|
\u{1F4CB} SPECIFICATIONS
|
|
893
|
-
`),console.log("\u2550".repeat(50)),f.forEach((k
|
|
894
|
-
`),{success:!0,specs:f})}catch{return h.warn("no specs directory"),{success:!0,specs:[]}}}h.spin("creating spec...");let o=
|
|
899
|
+
`),console.log("\u2550".repeat(50)),f.forEach((S,k)=>{let v=S.replace(".md","").replace(/-/g," ");console.log(` ${k+1}. ${v}`)}),console.log(`${"\u2550".repeat(50)}
|
|
900
|
+
`),{success:!0,specs:f})}catch{return h.warn("no specs directory"),{success:!0,specs:[]}}}h.spin("creating spec...");let o=T.getGlobalProjectPath(s),i=$n.join(o,"planning","specs");await ne.ensureDir(i);let a=e.toLowerCase().replace(/\s+/g,"-"),c=$n.join(i,`${a}.md`),u=`# Specification: ${e}
|
|
895
901
|
|
|
896
902
|
## Overview
|
|
897
903
|
[Brief description of the feature]
|
|
@@ -921,27 +927,27 @@ Generated: ${new Date().toLocaleString()}
|
|
|
921
927
|
---
|
|
922
928
|
Created: ${new Date().toLocaleString()}
|
|
923
929
|
Status: Draft
|
|
924
|
-
`;return await
|
|
930
|
+
`;return await Re.get("Write")(c,u),await this.logToMemory(t,"spec_created",{feature:e,timestamp:L.getTimestamp()}),h.done(`spec created: ${a}.md`),console.log(`
|
|
925
931
|
\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
|
|
926
|
-
`),{success:!0,feature:e,specPath:c}}catch(n){return h.fail(
|
|
927
|
-
`).filter(Boolean)
|
|
928
|
-
`)}async getSessionInfo(e){return
|
|
932
|
+
`),{success:!0,feature:e,specPath:c}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}}});var qo,an,rm=y(()=>{"use strict";zt();lo();it();re();F();Fe();Tn();qo=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(()=>(Vo(),nm)),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 Rr.notInitialized();return t}async getGlobalPath(e){let t=await this.getProjectId(e);return await T.ensureProjectStructure(t),T.getGlobalProjectPath(t)}async ensureAuthor(){if(this.currentAuthor)return this.currentAuthor;let e=await ls();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 zn(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: ${w(t)}`),!0}}async hasExistingCode(e){try{let t=["src","lib","app","components","pages","api","main.go","main.rs","main.py"];return(await zn(e)).some(s=>t.includes(s))}catch(t){return C(t)||console.error(`Code check error: ${w(t)}`),!1}}async isConfigured(e){return await R.isConfigured(e)}async needsMigration(e){return await R.needsMigration(e)}},an=new qo});var bb,om,im,Oc,am,cm=y(()=>{"use strict";de();te();bb=1800*1e3,om=50,im=200,Oc=class{static{l(this,"SessionTracker")}async read(e){try{return M.getDoc(e,"session-tracker")??this.getDefault()}catch{return this.getDefault()}}async write(e,t){M.setDoc(e,"session-tracker",t)}getDefault(){return{current:null,config:{idleTimeoutMs:bb}}}isExpired(e,t){let n=new Date(e.lastActivity).getTime();return Date.now()-n>t}async touch(e){let t=await this.read(e),n=b();if(t.current&&!this.isExpired(t.current,t.config.idleTimeoutMs))return t.current.lastActivity=n,await this.write(e,t),t.current;let s={id:crypto.randomUUID(),projectId:e,status:"active",createdAt:n,lastActivity:n,commands:[],files:[]};return t.current=s,await this.write(e,t),s}async trackCommand(e,t,n){let s=await this.read(e);if(!s.current)return;let o=b();s.current.lastActivity=o,s.current.commands.push({command:t,timestamp:o,durationMs:n}),s.current.commands.length>om&&(s.current.commands=s.current.commands.slice(-om)),await this.write(e,s)}async trackFile(e,t,n){let s=await this.read(e);if(!s.current)return;let o=b();s.current.lastActivity=o,s.current.files.push({path:t,operation:n,timestamp:o}),s.current.files.length>im&&(s.current.files=s.current.files.slice(-im)),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:Os(s-o),idleSince:n.lastActivity,idleMs:a,expiresIn:Os(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}},am=new Oc});import{exec as Pb}from"node:child_process";import{promisify as Cb}from"node:util";var _c,vb,Ko,pr,lm=y(()=>{"use strict";de();F();cm();_c=Cb(Pb),vb={commitThreshold:10,dayThreshold:3,significantFiles:["package.json","tsconfig.json","Cargo.toml","go.mod","requirements.txt","pyproject.toml",".env.example","docker-compose.yml","Dockerfile"]},Ko=class{static{l(this,"StalenessChecker")}projectPath;config;constructor(e,t={}){this.projectPath=e,this.config={...vb,...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=M.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 _c("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([_c(`git rev-list --count ${t.lastSyncCommit}..HEAD`,{cwd:o}).catch(()=>null),_c(`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(`
|
|
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: ${w(n)}`,t}}formatStatus(e){let t=[];e.isStale?t.push("CLAUDE.md status: \u26A0\uFE0F STALE"):t.push("CLAUDE.md status: \u2713 Fresh");let n=[];if(e.lastSyncCommit&&n.push(`Last sync: ${e.lastSyncCommit}`),e.currentCommit&&n.push(`Current: ${e.currentCommit}`),e.commitsSinceSync>0&&n.push(`Commits since: ${e.commitsSinceSync}`),e.daysSinceSync>0&&n.push(`Days since: ${e.daysSinceSync}`),e.changedFiles.length>0&&n.push(`Files changed: ${e.changedFiles.length}`),n.length>0){let s=Math.max(...n.map(i=>i.length)),o="\u2500".repeat(s+2);t.push(`\u250C${o}\u2510`);for(let i of n)t.push(`\u2502 ${i.padEnd(s)} \u2502`);t.push(`\u2514${o}\u2518`)}if(e.significantChanges.length>0){t.push(""),t.push("Significant changes:");for(let s of e.significantChanges.slice(0,5))t.push(` \u2022 ${s}`);e.significantChanges.length>5&&t.push(` ... and ${e.significantChanges.length-5} more`)}return e.reason&&(t.push(""),t.push(e.reason)),e.isStale&&(t.push(""),t.push("Run `prjct sync` to update context")),t.join(`
|
|
934
|
+
`)}async getSessionInfo(e){return am.getInfo(e)}formatSessionInfo(e){let t=[];if(!e.active)return t.push("Session: \u25CB No active session"),t.join(`
|
|
929
935
|
`);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(`
|
|
930
|
-
`)}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}},pr=l((r,e)=>new
|
|
931
|
-
`)){let i=o.trim();i==="---COMMIT---"?(s&&s.size>0&&s.size<=
|
|
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}},pr=l((r,e)=>new Ko(r,e),"createStalenessChecker")});import um from"node:fs/promises";import Yo from"node:path";function mr(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 Ab(r,e){let t=[],n=e.replace(/\.[^.]+$/,"").split(/[/\\]/).filter(Boolean);for(let p of n)t.push(...mr(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(...mr(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(...mr(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(...mr(p));else{let g=p.startsWith("@")?p.split("/").slice(0,2).join("/"):p.split("/")[0];t.push(...mr(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&&!Tb.has(p)&&/^[a-z][a-z0-9]*$/.test(p))}async function dm(r,e){let t=[],n=await um.readdir(r,{withFileTypes:!0});for(let s of n){if(Eb.has(s.name))continue;let o=Yo.join(r,s.name);if(s.isDirectory())t.push(...await dm(o,e));else if(s.isFile()){let i=Yo.extname(s.name).toLowerCase();xb.has(i)&&t.push(Yo.relative(e,o))}}return t}async function Ib(r){let e=await dm(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 um.readFile(Yo.join(r,d),"utf-8"),p=Ab(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 jb(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]))};G.setDoc(r,Db,t)}async function pm(r,e){let t=await Ib(r);return jb(e,t),t}var xb,Tb,Eb,Db,mm=y(()=>{"use strict";de();xb=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".cs",".rb",".php",".vue",".svelte"]),Tb=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"]),Eb=new Set(["node_modules",".git","dist","build","out",".next","coverage",".cache",".turbo",".vercel","__pycache__","vendor","target"]);l(mr,"splitIdentifier");l(Ab,"tokenizeFile");l(dm,"listFiles");l(Ib,"buildIndex");Db="bm25-index";l(jb,"saveIndex");l(pm,"indexProject")});import Nc from"node:fs/promises";import Bt from"node:path";function Ob(r){let e=[],t,n=new RegExp(Fb.source,"g");for(;(t=n.exec(r))!==null;){let s=t[1];(s.startsWith(".")||s.startsWith("@/"))&&e.push(s)}return e}async function _b(r,e,t){let n;if(r.startsWith("@/"))n=Bt.join(t,"src",r.slice(2));else{let s=Bt.dirname(Bt.join(t,e));n=Bt.resolve(s,r)}for(let s of Mb){let o=n+s;try{if((await Nc.stat(o)).isFile())return Bt.relative(t,o)}catch{}}return null}async function gm(r,e){let t=[],n=await Nc.readdir(r,{withFileTypes:!0});for(let s of n){if($b.has(s.name))continue;let o=Bt.join(r,s.name);if(s.isDirectory())t.push(...await gm(o,e));else if(s.isFile()){let i=Bt.extname(s.name).toLowerCase();Rb.has(i)&&t.push(Bt.relative(e,o))}}return t}async function Nb(r){let e=await gm(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 Nc.readFile(Bt.join(r,u),"utf-8"),m=Ob(d),p=[];for(let g of m){let f=await _b(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 Lb(r,e){G.setDoc(r,fm,e)}function hm(r){return G.getDoc(r,fm)}async function ym(r,e){let t=await Nb(r);return Lb(e,t),t}var Rb,$b,Mb,Fb,fm,Lc=y(()=>{"use strict";de();Rb=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),$b=new Set(["node_modules",".git","dist","build","out",".next","coverage",".cache",".turbo",".vercel"]),Mb=["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"],Fb=/(?:import|from)\s+['"]([^'"]+)['"]/g;l(Ob,"extractImportSources");l(_b,"resolveImport");l(gm,"listFiles");l(Nb,"buildGraph");fm="import-graph";l(Lb,"saveGraph");l(hm,"loadGraph");l(ym,"indexImports")});function wm(r,e){let t=[...r.added,...r.modified],n=new Set(t),s=new Set,o=hm(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 Sm(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 km=y(()=>{"use strict";Lc();l(wm,"propagateChanges");l(Sm,"affectedDomains")});import Uc from"node:fs/promises";import Xo from"node:path";async function bm(r,e){let t=[],n=await Uc.readdir(r,{withFileTypes:!0}).catch(()=>[]);for(let s of n){let o=String(s.name);if(Hb.has(o)||o.startsWith(".")&&o!==".env.example")continue;let i=Xo.join(r,o);if(s.isDirectory())t.push(...await bm(i,e));else if(s.isFile()){let a=Xo.extname(o).toLowerCase();Ub.has(a)&&t.push(Xo.relative(e,i))}}return t}function Gb(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 zb(r){let e=await bm(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=Xo.join(r,a),[u,d]=await Promise.all([Uc.readFile(c,"utf-8"),Uc.stat(c)]);return{path:a,hash:Gb(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 Wb(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 Hc(r,e){let t=G.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)})(),G.setDoc(r,"file-hashes-meta",{fileCount:e.size,builtAt:new Date().toISOString()})}function Bb(r){let e=new Map;try{let t=G.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 Gc(r,e){let[t,n]=await Promise.all([zb(r),Promise.resolve(Bb(e))]);return{diff:Wb(t,n),currentHashes:t}}function Pm(r){return G.hasDoc(r,"file-hashes-meta")}var Ub,Hb,Cm=y(()=>{"use strict";de();Ub=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".css",".scss",".html",".vue",".svelte",".py",".go",".rs",".yaml",".yml",".toml"]),Hb=new Set(["node_modules",".git","dist","build","out",".next","coverage",".cache",".turbo",".vercel",".prjct"]);l(bm,"listProjectFiles");l(Gb,"hashContent");l(zb,"computeHashes");l(Wb,"diffHashes");l(Hc,"saveHashes");l(Bb,"loadHashes");l(Gc,"detectChanges");l(Pm,"hasHashRegistry")});import{exec as Vb}from"node:child_process";import{promisify as Jb}from"node:util";async function Yb(r,e=100){try{let{stdout:t}=await qb(`git log --name-only --pretty=format:'---COMMIT---' -${e}`,{cwd:r,maxBuffer:10485760}),n=[],s=null;for(let o of t.split(`
|
|
937
|
+
`)){let i=o.trim();i==="---COMMIT---"?(s&&s.size>0&&s.size<=xm&&n.push(s),s=new Set):i&&s&&Xb(i)&&s.add(i)}return s&&s.size>0&&s.size<=xm&&n.push(s),n}catch{return[]}}function Xb(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 Qb(r,e=100){let t=await Yb(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=Zb(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<vm||m<vm)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 Zb(r,e){return r<e?`${r}\0${e}`:`${e}\0${r}`}function tP(r,e){G.setDoc(r,eP,e)}async function Tm(r,e,t=100){let n=await Qb(r,t);return tP(e,n),n}var qb,Kb,vm,xm,eP,Em=y(()=>{"use strict";de();qb=Jb(Vb),Kb=.1,vm=2,xm=30;l(Yb,"parseGitLog");l(Xb,"isSourceFile");l(Qb,"buildMatrix");l(Zb,"pairKey");eP="cochange-index";l(tP,"saveMatrix");l(Tm,"indexCoChanges")});function $e(r){return`<!-- source: ${r.file}, ${r.type} -->`}function Vt(){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 Qo=y(()=>{"use strict";l($e,"cite");l(Vt,"defaultSources")});function nP(r,e){let t=r.sources||Vt();return`# ${r.name} - Project Rules
|
|
932
938
|
<!-- projectId: ${r.projectId} -->
|
|
933
939
|
<!-- Generated: ${new Date().toISOString()} -->
|
|
934
940
|
<!-- Ecosystem: ${r.ecosystem} | Type: ${r.projectType} -->
|
|
935
941
|
|
|
936
942
|
## THIS PROJECT (${r.ecosystem})
|
|
937
943
|
|
|
938
|
-
${
|
|
944
|
+
${$e(t.ecosystem)}
|
|
939
945
|
**Type:** ${r.projectType}
|
|
940
946
|
**Path:** ${r.repoPath}
|
|
941
947
|
|
|
942
948
|
### Commands (USE THESE, NOT OTHERS)
|
|
943
949
|
|
|
944
|
-
${
|
|
950
|
+
${$e(t.commands)}
|
|
945
951
|
| Action | Command |
|
|
946
952
|
|--------|---------|
|
|
947
953
|
| Install dependencies | \`${r.commands.install}\` |
|
|
@@ -953,9 +959,9 @@ ${De(t.commands)}
|
|
|
953
959
|
|
|
954
960
|
### Code Conventions
|
|
955
961
|
|
|
956
|
-
${
|
|
962
|
+
${$e(t.languages)}
|
|
957
963
|
- **Languages**: ${r.languages.join(", ")||"Not detected"}
|
|
958
|
-
${
|
|
964
|
+
${$e(t.frameworks)}
|
|
959
965
|
- **Frameworks**: ${r.frameworks.join(", ")||"Not detected"}
|
|
960
966
|
|
|
961
967
|
---
|
|
@@ -983,7 +989,7 @@ p. sync \u2192 p. task "desc" \u2192 [work] \u2192 p. done \u2192 p. ship
|
|
|
983
989
|
|
|
984
990
|
## PROJECT STATE
|
|
985
991
|
|
|
986
|
-
${
|
|
992
|
+
${$e(t.name)}
|
|
987
993
|
| Field | Value |
|
|
988
994
|
|-------|-------|
|
|
989
995
|
| Name | ${r.name} |
|
|
@@ -1001,24 +1007,24 @@ Load from \`~/.prjct-cli/projects/${r.projectId}/agents/\`:
|
|
|
1001
1007
|
|
|
1002
1008
|
**Workflow**: ${r.agents.workflow.join(", ")}
|
|
1003
1009
|
**Domain**: ${r.agents.domain.join(", ")||"none"}
|
|
1004
|
-
`}function
|
|
1005
|
-
`)}function
|
|
1006
|
-
`)}function
|
|
1007
|
-
`)}function
|
|
1008
|
-
`),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
|
|
1010
|
+
`}function sP(r,e){let t=r.sources||Vt(),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($e(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($e(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(`
|
|
1011
|
+
`)}function rP(r,e){let t=r.sources||Vt(),n=[];return n.push("# Copilot Instructions"),n.push(""),n.push(`This is ${r.name}, a ${r.ecosystem} project.`),n.push(""),n.push($e(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($e(t.commands)),n.push("## Commands"),n.push(`- Test: \`${r.commands.test}\``),n.push(`- Build: \`${r.commands.build}\``),n.join(`
|
|
1012
|
+
`)}function oP(r,e){let t=r.sources||Vt(),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($e(t.languages)),n.push("## Stack"),n.push(`- ${r.languages.join(", ")}`),r.frameworks.length>0&&n.push(`- ${r.frameworks.join(", ")}`),n.push(""),n.push($e(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(`
|
|
1013
|
+
`)}function iP(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(`
|
|
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 Am(r){return{claude:nP,cursor:sP,copilot:rP,windsurf:oP,continue:iP}[r]||null}var zc=y(()=>{"use strict";Qo();l(nP,"formatForClaude");l(sP,"formatForCursor");l(rP,"formatForCopilot");l(oP,"formatForWindsurf");l(iP,"formatForContinue");l(Am,"getFormatter")});import{exec as aP}from"node:child_process";import cP from"node:os";import gr from"node:path";import{promisify as lP}from"node:util";function Im(r){return Zo[r]||null}async function Wc(r){try{return await uP(`which ${r}`),!0}catch{return!1}}async function ei(r=process.cwd()){let e=[];return await Wc("claude")&&e.push("claude"),(await Wc("cursor")||await $(gr.join(r,".cursor")))&&e.push("cursor"),await $(gr.join(r,".github"))&&e.push("copilot"),(await Wc("windsurf")||await $(gr.join(r,".windsurf")))&&e.push("windsurf"),(await $(gr.join(r,".continue"))||await $(gr.join(cP.homedir(),".continue")))&&e.push("continue"),e}async function Dm(r,e=process.cwd()){if(r==="auto"){let t=await ei(e);return t.length>0?t:["claude"]}return r==="all"?dP:r.filter(t=>Zo[t])}var uP,Zo,fr,dP,Bc=y(()=>{"use strict";Fe();uP=lP(aP),Zo={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"}},fr=["claude"],dP=Object.keys(Zo);l(Im,"getAIToolConfig");l(Wc,"commandExists");l(ei,"detectInstalledTools");l(Dm,"resolveToolIds")});import Vc from"node:fs/promises";import Jc from"node:path";async function jm(r,e,t,n=fr){let s=[];for(let o of n){let i=Im(o);if(!i){s.push({toolId:o,outputFile:"",outputPath:"",success:!1,error:`Unknown tool: ${o}`});continue}let a=await pP(r,i,e,t);s.push(a)}return s}async function pP(r,e,t,n){let s=Am(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 Vc.mkdir(Jc.dirname(i),{recursive:!0});try{let a=await Vc.readFile(i,"utf-8"),c=er(a);if(!c.valid){console.warn(`\u26A0\uFE0F ${e.outputFile} has invalid preserve blocks:`);for(let u of c.errors)console.warn(` ${u}`)}o=Zs(o,a)}catch{}return await Vc.writeFile(i,o,"utf-8"),{toolId:e.id,outputFile:e.outputFile,outputPath:i,success:!0}}catch(o){return{toolId:e.id,outputFile:e.outputFile,outputPath:"",success:!1,error:w(o)}}}var Rm=y(()=>{"use strict";F();ro();zc();Bc();l(jm,"generateAIToolContexts");l(pP,"generateForTool")});var $m=y(()=>{"use strict";zc();Rm();Bc()});import qc from"node:fs/promises";import Ut from"node:path";var ti,Mm=y(()=>{"use strict";re();Xn();Zn();es();ts();Qo();te();ro();Va();ti=class{static{l(this,"ContextFileGenerator")}config;constructor(e){this.config=e}async writeWithPreservation(e,t){let n=t;try{let s=await qc.readFile(e,"utf-8"),o=er(s);if(!o.valid){let i=Ut.basename(e);console.warn(`\u26A0\uFE0F ${i} has invalid preserve blocks:`);for(let a of o.errors)console.warn(` ${a}`)}n=Zs(t,s)}catch{}await qc.writeFile(e,n,"utf-8")}async generate(e,t,n,s,o){let i=Ut.join(this.config.globalPath,"context");return await Promise.all([this.generateClaudeMd(i,e,t,n,s,o),this.generateNowMd(i),this.generateNextMd(i),this.generateIdeasMd(i),this.generateShippedMd(i)]),["context/CLAUDE.md","context/now.md","context/next.md","context/ideas.md","context/shipped.md"]}async generateClaudeMd(e,t,n,s,o,i){let a=o.filter(p=>p.type==="workflow").map(p=>p.name),c=o.filter(p=>p.type==="domain").map(p=>p.name),u=i||Vt(),d=`# ${n.name} - Project Rules
|
|
1009
1015
|
<!-- projectId: ${this.config.projectId} -->
|
|
1010
1016
|
<!-- Generated: ${b()} -->
|
|
1011
1017
|
<!-- Ecosystem: ${n.ecosystem} | Type: ${n.projectType} -->
|
|
1012
1018
|
|
|
1013
1019
|
## THIS PROJECT (${n.ecosystem})
|
|
1014
1020
|
|
|
1015
|
-
${
|
|
1021
|
+
${$e(u.ecosystem)}
|
|
1016
1022
|
**Type:** ${n.projectType}
|
|
1017
1023
|
**Path:** ${this.config.projectPath}
|
|
1018
1024
|
|
|
1019
1025
|
### Commands (USE THESE, NOT OTHERS)
|
|
1020
1026
|
|
|
1021
|
-
${
|
|
1027
|
+
${$e(u.commands)}
|
|
1022
1028
|
| Action | Command |
|
|
1023
1029
|
|--------|---------|
|
|
1024
1030
|
| Install dependencies | \`${s.install}\` |
|
|
@@ -1030,9 +1036,9 @@ ${De(u.commands)}
|
|
|
1030
1036
|
|
|
1031
1037
|
### Code Conventions
|
|
1032
1038
|
|
|
1033
|
-
${
|
|
1039
|
+
${$e(u.languages)}
|
|
1034
1040
|
- **Languages**: ${n.languages.join(", ")||"Not detected"}
|
|
1035
|
-
${
|
|
1041
|
+
${$e(u.frameworks)}
|
|
1036
1042
|
- **Frameworks**: ${n.frameworks.join(", ")||"Not detected"}
|
|
1037
1043
|
|
|
1038
1044
|
---
|
|
@@ -1060,7 +1066,7 @@ p. sync \u2192 p. task "desc" \u2192 [work] \u2192 p. done \u2192 p. ship
|
|
|
1060
1066
|
|
|
1061
1067
|
## PROJECT STATE
|
|
1062
1068
|
|
|
1063
|
-
${
|
|
1069
|
+
${$e(u.name)}
|
|
1064
1070
|
| Field | Value |
|
|
1065
1071
|
|-------|-------|
|
|
1066
1072
|
| Name | ${n.name} |
|
|
@@ -1078,7 +1084,7 @@ Load from \`~/.prjct-cli/projects/${this.config.projectId}/agents/\`:
|
|
|
1078
1084
|
|
|
1079
1085
|
**Workflow**: ${a.join(", ")}
|
|
1080
1086
|
**Domain**: ${c.join(", ")||"none"}
|
|
1081
|
-
`,m=
|
|
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
|
|
1082
1088
|
|
|
1083
1089
|
**${t.description}**
|
|
1084
1090
|
|
|
@@ -1089,21 +1095,21 @@ ${s?`Branch: ${s}`:""}
|
|
|
1089
1095
|
_No active task_
|
|
1090
1096
|
|
|
1091
1097
|
Use \`p. task "description"\` to start working.
|
|
1092
|
-
`;await this.writeWithPreservation(
|
|
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
|
|
1093
1099
|
|
|
1094
1100
|
${t.tasks.length>0?t.tasks.map((s,o)=>`${o+1}. ${s.description}${s.priority?` [${s.priority}]`:""}`).join(`
|
|
1095
1101
|
`):"_Empty queue_"}
|
|
1096
|
-
`;await this.writeWithPreservation(
|
|
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
|
|
1097
1103
|
|
|
1098
1104
|
${t.ideas.length>0?t.ideas.map(s=>`- ${s.text}${s.priority?` [${s.priority}]`:""}`).join(`
|
|
1099
1105
|
`):"_No ideas captured yet_"}
|
|
1100
|
-
`;await this.writeWithPreservation(
|
|
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}
|
|
1101
1107
|
|
|
1102
1108
|
${t.shipped.length>0?t.shipped.slice(-10).map(s=>`- **${s.name}**${s.version?` v${s.version}`:""} - ${s.shippedAt}`).join(`
|
|
1103
1109
|
`):"_Nothing shipped yet_"}
|
|
1104
1110
|
|
|
1105
1111
|
**Total shipped:** ${t.shipped.length}
|
|
1106
|
-
`;await this.writeWithPreservation(
|
|
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
|
|
1107
1113
|
<!-- package: ${e.relativePath} -->
|
|
1108
1114
|
<!-- monorepo: ${s.name} -->
|
|
1109
1115
|
<!-- Generated: ${b()} -->
|
|
@@ -1111,7 +1117,7 @@ ${t.shipped.length>0?t.shipped.slice(-10).map(s=>`- **${s.name}**${s.version?` v
|
|
|
1111
1117
|
|
|
1112
1118
|
## THIS PACKAGE
|
|
1113
1119
|
|
|
1114
|
-
**Name:** ${
|
|
1120
|
+
**Name:** ${d}
|
|
1115
1121
|
**Path:** ${e.relativePath}
|
|
1116
1122
|
**Version:** ${u}
|
|
1117
1123
|
**Monorepo:** ${s.name}
|
|
@@ -1143,7 +1149,7 @@ ${t.overrides.length>0?`
|
|
|
1143
1149
|
|
|
1144
1150
|
| Field | Value |
|
|
1145
1151
|
|-------|-------|
|
|
1146
|
-
| Package | ${
|
|
1152
|
+
| Package | ${d} |
|
|
1147
1153
|
| Monorepo | ${s.name} |
|
|
1148
1154
|
| Branch | ${n.branch} |
|
|
1149
1155
|
| Ecosystem | ${s.ecosystem} |
|
|
@@ -1156,8 +1162,8 @@ Load from \`~/.prjct-cli/projects/${this.config.projectId}/agents/\`:
|
|
|
1156
1162
|
|
|
1157
1163
|
**Workflow**: ${a.join(", ")}
|
|
1158
1164
|
**Domain**: ${c.join(", ")||"none"}
|
|
1159
|
-
`}}});import
|
|
1160
|
-
`)}},
|
|
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()}
|
|
1161
1167
|
${s.join(`
|
|
1162
1168
|
`)}`;return r.replace(o,`---
|
|
1163
1169
|
${c}
|
|
@@ -1166,10 +1172,10 @@ ${s.join(`
|
|
|
1166
1172
|
`)}
|
|
1167
1173
|
---
|
|
1168
1174
|
|
|
1169
|
-
${r}`}function
|
|
1175
|
+
${r}`}function rl(){return Be.join(sl.homedir(),".claude","skills")}async function nl(r,e,t,n){let s=rl(),o=Be.join(s,e),i=Be.join(o,"SKILL.md"),a=await Jt.readFile(r,"utf-8"),c=CP(a,t,n);return await Jt.mkdir(o,{recursive:!0}),await Jt.writeFile(i,c,"utf-8"),{name:e,filePath:i,source:t,sha:n}}async function vP(r){let e={installed:[],skipped:[],errors:[]};if(!vo.isAvailable("git")){let n=vo.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=Be.join(sl.tmpdir(),`prjct-skill-${Date.now()}`);try{let n=`https://github.com/${r.owner}/${r.repo}.git`;await Um(`git clone --depth 1 ${n} ${t}`,{timeout:Or("GIT_CLONE")});let s;try{let{stdout:a}=await Um("git rev-parse HEAD",{cwd:t,timeout:Or("TOOL_CHECK")});s=a.trim()}catch{}let o=await Gm(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 nl(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 yr.addEntry(u),e.installed.push(c)}catch(c){e.errors.push(`Failed to install ${a.name}: ${w(c)}`)}}finally{try{await Jt.rm(t,{recursive:!0,force:!0})}catch{}}return e}async function xP(r){let e={installed:[],skipped:[],errors:[]},t=r.localPath;try{await Jt.access(t)}catch{return e.errors.push(`Local path not found: ${t}`),e}if((await Jt.stat(t)).isFile()){let s=Be.basename(Be.dirname(t));try{let o=await nl(t,s,r),i={name:s,source:{type:"local",url:t},installedAt:new Date().toISOString(),filePath:o.filePath};await yr.addEntry(i),e.installed.push(o)}catch(o){e.errors.push(`Failed to install from ${t}: ${w(o)}`)}}else{let s=await Gm(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 nl(o.filePath,o.name,r),a={name:o.name,source:{type:"local",url:t},installedAt:new Date().toISOString(),filePath:i.filePath};await yr.addEntry(a),e.installed.push(i)}catch(i){e.errors.push(`Failed to install ${o.name}: ${w(i)}`)}}return e}async function TP(r){let e=rl(),t=Be.join(e,r);try{await Jt.rm(t,{recursive:!0,force:!0})}catch{}let n=Be.join(e,`${r}.md`);try{await Jt.rm(n,{force:!0})}catch{}return yr.removeEntry(r)}async function EP(r){let e=Hm(r);switch(e.type){case"github":return vP(e);case"local":return xP(e);default:return{installed:[],skipped:[],errors:[`Unsupported source type: ${e.type}`]}}}var Um,zm,Wm=y(()=>{"use strict";F();Qt();Wa();Nm();Um=PP(bP);l(Hm,"parseSource");l(Gm,"discoverSkills");l(CP,"injectSourceMetadata");l(rl,"getInstallDir");l(nl,"installSkillFile");l(vP,"installFromGitHub");l(xP,"installFromLocal");l(TP,"remove");l(EP,"install");zm={install:EP,remove:TP,parseSource:Hm,getInstallDir:rl}});import mt from"node:fs/promises";import AP from"node:os";import lt from"node:path";async function Bm(r,e,t,n){let s=[],o=lt.join(r,"agents");try{let c=await mt.readdir(o);for(let u of c)u.endsWith(".md")&&await mt.unlink(lt.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=>IP(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=>DP(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=lt.join(r,"agents"),t=[];try{let n=await mt.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 Jm(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=Ae(`subagents/${o}.md`);if(!i){let a=lt.join(__dirname,"..","..","templates","subagents",`${o}.md`);try{i=await mt.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 IP(r,e){let t="";try{let n=lt.join(__dirname,"..","..","templates","subagents","workflow",`${r}.md`);t=await mt.readFile(n,"utf-8"),t=await Jm(t)}catch(n){B.debug("Workflow agent template not found, generating minimal",{name:r,error:K(n)}),t=RP(r)}await mt.writeFile(lt.join(e,`${r}.md`),t,"utf-8")}async function DP(r,e,t,n,s){let o="";try{let i=lt.join(__dirname,"..","..","templates","subagents","domain",`${r}.md`);o=await mt.readFile(i,"utf-8"),o=await Jm(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=$P(r,t,n)}o=jP(o,r,s),await mt.writeFile(lt.join(e,`${r}.md`),o,"utf-8")}function jP(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=[`
|
|
1170
1176
|
## Recent Learnings (from completed tasks)
|
|
1171
|
-
`];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
|
|
1172
|
-
`)}function
|
|
1177
|
+
`];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 RP(r){return`---
|
|
1173
1179
|
name: ${r}
|
|
1174
1180
|
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"}
|
|
1175
1181
|
tools: Read, Write, Glob
|
|
@@ -1185,7 +1191,7 @@ When invoked:
|
|
|
1185
1191
|
1. Read \`.prjct/prjct.config.json\` \u2192 extract \`projectId\`
|
|
1186
1192
|
2. Read \`~/.prjct-cli/projects/{projectId}/storage/state.json\`
|
|
1187
1193
|
3. Execute requested operation
|
|
1188
|
-
`}function
|
|
1194
|
+
`}function $P(r,e,t){return`---
|
|
1189
1195
|
name: ${r}
|
|
1190
1196
|
description: ${r.charAt(0).toUpperCase()+r.slice(1)} specialist for ${e.name}
|
|
1191
1197
|
tools: Read, Write, Glob, Grep
|
|
@@ -1205,18 +1211,17 @@ Domain specialist for ${r} tasks.
|
|
|
1205
1211
|
## Your Role
|
|
1206
1212
|
|
|
1207
1213
|
You are the ${r} expert for this project. Apply best practices for the detected stack.
|
|
1208
|
-
`}function
|
|
1209
|
-
`).filter(Boolean);e.hasChanges=i.length>0;for(let u of i){let
|
|
1210
|
-
`).filter(Boolean).map(u=>{let[p,m,d]=u.split("|");return{hash:p,message:m,date:d}});let{stdout:c}=await Nn('git log --oneline --since="1 week ago" | wc -l',{cwd:r});e.weeklyCommits=parseInt(c.trim(),10)||0}catch(t){H.debug("Git analysis failed (not a git repo?)",{error:V(t)})}return e}async function Lt(r,e){try{return await yg.access(bl.join(r,e)),!0}catch(t){return H.debug("File not found",{filename:e,error:V(t)}),!1}}async function Sg(r){let e={fileCount:0,version:"0.0.0",name:bl.basename(r),ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]};try{let{stdout:t}=await Nn('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){H.debug("File count failed",{path:r,error:V(t)}),e.fileCount=0}try{let t=bl.join(r,"package.json"),n=JSON.parse(await yg.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 Lt(r,"tsconfig.json")?e.languages.push("TypeScript"):e.languages.push("JavaScript")}catch(t){H.debug("No package.json found",{path:r,error:V(t)})}return await Lt(r,"Cargo.toml")&&(e.ecosystem="Rust",e.languages.push("Rust")),await Lt(r,"go.mod")&&(e.ecosystem="Go",e.languages.push("Go")),(await Lt(r,"requirements.txt")||await Lt(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 kg(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 Lt(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 Lt(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 Lt(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 Lt(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 Lt(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 bg(r,e){let t=Kt(),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 Pg(r){return new li(r).detect()}var Nn,Cg=w(()=>{"use strict";zt();oi();Yn();hg();Nn=mC(dC);l(wg,"analyzeGit");l(Lt,"fileExists");l(Sg,"gatherStats");l(kg,"detectCommands");l(bg,"buildSources");l(Pg,"detectStack")});import{exec as gC}from"node:child_process";import ui from"node:fs/promises";import pi from"node:path";import{promisify as fC}from"node:util";var hC,Pl,Cl,vg,xg=w(()=>{"use strict";M();hC=fC(gC),Pl={async contextFilesExist(r){let e=Date.now(),t=["context/CLAUDE.md"],n=[];for(let s of t){let o=pi.join(r,s);try{await ui.access(o)}catch{n.push(s)}}return{name:"Context files exist",passed:n.length===0,output:n.length===0?`${t.length} files verified`:void 0,error:n.length>0?`Missing: ${n.join(", ")}`:void 0,durationMs:Date.now()-e}},async jsonFilesValid(r){let e=Date.now(),t=["storage/state.json"],n=[];for(let s of t){let o=pi.join(r,s);try{let i=await ui.readFile(o,"utf-8");JSON.parse(i)}catch(i){S(i)||n.push(`${s}: ${i instanceof SyntaxError?"invalid JSON":"read error"}`)}}return{name:"JSON files valid",passed:n.length===0,output:n.length===0?`${t.length} files validated`:void 0,error:n.length>0?n.join("; "):void 0,durationMs:Date.now()-e}},async noSensitiveData(r){let e=Date.now(),t=pi.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 ui.readdir(t);for(let i of o){if(!i.endsWith(".md"))continue;let a=await ui.readFile(pi.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(!S(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}}},Cl=class{static{l(this,"SyncVerifier")}async verify(e,t,n){let s=Date.now(),o=[],i=n?.failFast??!1,a=0,c=[Pl.contextFilesExist(t),Pl.jsonFilesValid(t),Pl.noSensitiveData(t)];for(let d of c){let g=await d;if(o.push(g),!g.passed&&i){a=n?.checks?.filter(f=>f.enabled!==!1).length??0;break}}if((!i||o.every(d=>d.passed))&&n?.checks)for(let d of n.checks){if(d.enabled===!1){a++;continue}let g=await this.runCustomCheck(d,e);if(o.push(g),!g.passed&&i){let f=n.checks.slice(n.checks.indexOf(d)+1);a+=f.filter(k=>k.enabled!==!1).length;break}}let p=o.filter(d=>!d.passed).length,m=o.filter(d=>d.passed).length;return{passed:p===0,checks:o,totalMs:Date.now()-s,failedCount:p,passedCount:m,skippedCount:a}}async runCustomCheck(e,t){let n=Date.now(),s=e.command||(e.script?`sh ${e.script}`:null);if(!s)return{name:e.name,passed:!1,error:"No command or script specified",durationMs:Date.now()-n};try{let{stdout:o,stderr:i}=await hC(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}}}},vg=new Cl});import yr from"node:fs/promises";import wr from"node:path";var di,Sr,Tg=w(()=>{"use strict";as();jm();_m();Um();Jm();tl();zt();En();ct();K();Vr();rn();at();Zr();no();fa();so();ro();oo();Xm();Q();Yn();hc();yc();Ym();Zm();cc();mg();Cg();xg();di=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 ai(e)).filter(i=>!gr.includes(i));s=[...gr,...o]}else t.aiTools[0]==="auto"?(s=await ai(e),s.length===0&&(s=["claude"])):t.aiTools[0]==="all"?s=await Vm("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=P.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await this.ensureDirectories(),await ga(this.projectId);try{let N=await hp(this.projectId);N>0&&H.info("Swept legacy JSON files into SQLite",{swept:N})}catch(N){H.debug("Legacy JSON sweep failed (non-critical)",{error:V(N)})}let[i,a,c,u]=await Promise.all([wg(this.projectPath),Sg(this.projectPath),kg(this.projectPath),Pg(this.projectPath)]),p=t.full===!0,m,d=!0,g=!0,f=new Set;if(!p&&Lm(this.projectId))try{let{diff:N,currentHashes:wf}=await rl(this.projectPath,this.projectId),Vl=N.added.length+N.modified.length+N.deleted.length;if(Vl===0&&!t.changedFiles?.length)d=!1,g=!1,m={isIncremental:!0,filesChanged:0,filesUnchanged:N.unchanged.length,indexesRebuilt:!1,agentsRegenerated:!1,affectedDomains:[]};else{let Ri=Fm(N,this.projectId);f=Om(Ri.allAffected);let Sf=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);d=Ri.allAffected.some(gn=>{let kf=gn.substring(gn.lastIndexOf("."));return Sf.has(kf)}),g=Ri.directlyChanged.some(gn=>gn==="package.json"||gn==="tsconfig.json"||gn.includes("Dockerfile")||gn.includes("docker-compose")),m={isIncremental:!0,filesChanged:Vl,filesUnchanged:N.unchanged.length,indexesRebuilt:d,agentsRegenerated:g,affectedDomains:Array.from(f)}}sl(this.projectId,wf)}catch(N){H.debug("Incremental detection failed, falling back to full sync",{error:V(N)})}else try{let{currentHashes:N}=await rl(this.projectPath,this.projectId);sl(this.projectId,N)}catch(N){H.debug("Hash computation failed (non-critical)",{error:V(N)})}if(d)try{await Promise.all([Im(this.projectPath,this.projectId),Mm(this.projectPath,this.projectId),zm(this.projectPath,this.projectId)])}catch(N){H.debug("File ranking index build failed (non-critical)",{error:V(N)})}let k;if(g)try{let N=await X.getAggregatedFeedback(this.projectId);(N.patternsDiscovered.length>0||N.knownGotchas.length>0||N.agentAccuracy.length>0)&&(k=N)}catch{}let v=g?await cg(this.globalPath,u,a,k):await lg(this.globalPath),x=pg(v,this.projectId,this.globalPath),$=g?await dg(v):[],J=bg(a,c),Pe=await this.generateContextFiles(i,a,c,v,J),Ge={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:v.filter(N=>N.type==="workflow").map(N=>N.name),domain:v.filter(N=>N.type==="domain").map(N=>N.name)},sources:J},gt=await qm(Ge,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 C=Date.now()-n,I=await this.recordSyncMetrics(a,Pe,v,C);await this.archiveStaleData(),await this.autoLearnFromHistory(),await _e.installGlobalConfig(),await _e.syncCommands();let we;try{let N=await R.readConfig(this.projectPath);we=await vg.verify(this.projectPath,this.globalPath,N?.verification)}catch(N){H.debug("Verification failed (non-critical)",{error:V(N)})}return{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:i,stats:a,commands:c,stack:u,agents:v,skills:x,skillsInstalled:$,contextFiles:Pe,aiTools:gt.map(N=>({toolId:N.toolId,outputFile:N.outputFile,success:N.success})),syncMetrics:I,verification:we,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:V(o)}}}async ensureDirectories(){let e=["storage","context","agents","memory","analysis","config","sync"];await Promise.all(e.map(t=>yr.mkdir(wr.join(this.globalPath,t),{recursive:!0})))}async generateContextFiles(e,t,n,s,o){return new ci({projectId:this.projectId,projectPath:this.projectPath,globalPath:this.globalPath}).generate(e,t,n,s,o)}async updateProjectJson(e,t){let n=F.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};F.setDoc(this.projectId,"project",s)}async updateStateJson(e,t){let s={...await X.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 X.write(this.projectId,s);try{await Qm.generate(this.projectPath,s)}catch(o){H.debug("Local state generation failed (optional)",{error:V(o)})}}async logToMemory(e,t){let n=wr.join(this.globalPath,"memory","events.jsonl"),s={ts:b(),action:"sync",branch:e.branch,uncommitted:e.hasChanges,fileCount:t.fileCount,commitCount:e.commits};await yr.appendFile(n,`${JSON.stringify(s)}
|
|
1211
|
-
`,"utf-8")}async recordSyncMetrics(e,t,n,s){let i=0;for(let m of t)try{let d=wr.join(this.globalPath,m),g=await yr.readFile(d,"utf-8");i+=g.length}catch(d){H.debug("Context file not found for metrics",{file:m,error:V(d)})}for(let m of n)try{let d=wr.join(this.globalPath,"agents",`${m.name}.md`),g=await yr.readFile(d,"utf-8");i+=g.length}catch(d){H.debug("Agent file not found for metrics",{agent:m.name,error:V(d)})}let a=Math.floor(i/4),u=e.fileCount*500,p=u>0?Math.max(0,(u-a)/u):0;try{await yn.recordSync(this.projectId,{originalSize:u,filteredSize:a,duration:s,isWatch:!1,agents:n.filter(m=>m.type==="domain").map(m=>m.name)})}catch(m){H.debug("Failed to record sync metrics",{error:V(m)})}return{duration:s,originalSize:u,filteredSize:a,compressionRate:p}}async saveDraftAnalysis(e,t,n){try{let s=e.recentCommits[0]?.hash||null,o=[],i=[];try{let a=await X.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 Mt.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){H.debug("Failed to save draft analysis (non-critical)",{error:V(s)})}}async archiveStaleData(){if(this.projectId)try{let[e,t,n,s,o]=await Promise.all([Wt.archiveOldShipped(this.projectId).catch(()=>0),kt.markDormantIdeas(this.projectId).catch(()=>0),Oe.removeStaleCompleted(this.projectId).catch(()=>0),X.archiveStalePausedTasks(this.projectId).catch(()=>[]),Je.capEntries(this.projectId).catch(()=>0)]),i=e+t+n+s.length+o;if(i>0){H.info("Archived stale data",{shipped:e,dormant:t,staleQueue:n,stalePaused:s.length,memoryCapped:o,total:i});let a=Ze.getStats(this.projectId);H.debug("Archive stats",a)}}catch(e){H.debug("Archival failed (non-critical)",{error:V(e)})}}async autoLearnFromHistory(){if(this.projectId)try{let e=await X.getTaskHistory(this.projectId);if(e.length===0)return;let t=new Cn,n=await fc.learnFromTaskHistory(this.projectId,e,t);try{let s=await ed.getFeatureOutcomes(this.projectId);s.length>0&&await fc.learnFromOutcomes(this.projectId,s,t)}catch{}n.memoriesInjected>0&&H.info("Auto-learned from task history",{patternsExtracted:n.patternsExtracted,memoriesInjected:n.memoriesInjected,patternsSkipped:n.patternsSkipped})}catch(e){H.debug("Auto-learning failed (non-critical)",{error:V(e)})}}async getCliVersion(){try{let e=wr.join(__dirname,"..","..","package.json");return JSON.parse(await yr.readFile(e,"utf-8")).version||"0.0.0"}catch(e){return H.debug("Failed to read CLI version",{error:V(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:[]}}},Sr=new di});var pn=w(()=>{"use strict";$p();Up();Hp();zp();Wp();sc();Vp();cc();lc();qp();bm();Tm();Tg()});import Yt from"chalk";function Eg(r){return Math.ceil(r.length/yC)}function Ag(r){let e=r.split(`
|
|
1214
|
+
`}function qm(r,e,t){let n=[];for(let o of r)o.skill&&n.push({agent:o.name,skill:o.skill});let s={projectId:e,syncedAt:b(),skills:n.map(o=>({name:o.skill,linkedAgents:[o.agent]})),agentSkillMap:Object.fromEntries(n.map(o=>[o.agent,o.skill]))};return mt.writeFile(lt.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 Km(r){let e=[];try{let t=lt.join(__dirname,"..","..","templates","config","skill-mappings.json"),n=await mt.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=lt.join(AP.homedir(),".claude","skills");for(let{pkg:c,agent:u}of i){let d=c.split("/").pop()||c,m=lt.join(a,d,"SKILL.md"),p=lt.join(a,`${d}.md`),g=!1;try{await mt.access(m),g=!0}catch{try{await mt.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 k=await zm.install(S);k.installed.length>0?(e.push({name:d,agent:u,status:"installed"}),B.info(`Installed skill: ${d} for agent: ${u}`)):k.errors.length>0?(e.push({name:d,agent:u,status:"error"}),B.debug(`Failed to install skill ${d}`,{errors:k.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 Ym=y(()=>{"use strict";cs();zt();te();qn();Wm();l(Bm,"generateAgents");l(Vm,"loadExistingAgents");l(Jm,"resolveTemplateIncludes");l(IP,"generateWorkflowAgent");l(DP,"generateDomainAgent");l(jP,"injectFeedbackSection");l(RP,"generateMinimalWorkflowAgent");l($P,"generateMinimalDomainAgent");l(qm,"configureSkills");l(Km,"autoInstallSkills")});import Xm from"node:fs/promises";import Qm from"node:path";var ni,Zm=y(()=>{"use strict";ni=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=Qm.join(this.projectPath,"package.json"),t=await Xm.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async fileExists(e){try{return await Xm.access(Qm.join(this.projectPath,e)),!0}catch{return!1}}}});import{exec as MP}from"node:child_process";import eg from"node:fs/promises";import ol from"node:path";import{promisify as FP}from"node:util";async function tg(r){let e={branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0};try{let{stdout:t}=await Fn("git branch --show-current",{cwd:r});e.branch=t.trim()||"main";let{stdout:n}=await Fn("git rev-list --count HEAD",{cwd:r});e.commits=parseInt(n.trim(),10)||0;let{stdout:s}=await Fn("git shortlog -sn --all | wc -l",{cwd:r});e.contributors=parseInt(s.trim(),10)||0;let{stdout:o}=await Fn("git status --porcelain",{cwd:r}),i=o.trim().split(`
|
|
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 Fn('git log --oneline -20 --pretty=format:"%h|%s|%ad" --date=short',{cwd:r});e.recentCommits=a.split(`
|
|
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(`
|
|
1212
1217
|
`),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+=`
|
|
1213
|
-
${o}`)}return n&&(n.endLine=e.length-1,t.push(n)),t}function
|
|
1214
|
-
`).length});for(let a of n){let c=a.name.toLowerCase(),u=o.get(c);u?u.content.trim()!==a.content.trim()&&(
|
|
1218
|
+
${o}`)}return n&&(n.endLine=e.length-1,t.push(n)),t}function ll(r){return r.includes("<!-- prjct:preserve")}function pg(r,e){let t=dg(r),n=dg(e),s={hasChanges:!1,added:[],modified:[],removed:[],preserved:[],tokensBefore:ug(r),tokensAfter:ug(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)ll(a.content)&&s.preserved.push({name:a.name,lineCount:a.content.split(`
|
|
1219
|
+
`).length});for(let a of n){let c=a.name.toLowerCase(),u=o.get(c);u?u.content.trim()!==a.content.trim()&&(ll(u.content)||(s.modified.push({name:a.name,type:"modified",before:u.content,after:a.content,lineCount:a.content.split(`
|
|
1215
1220
|
`).length}),s.hasChanges=!0)):(s.added.push({name:a.name,type:"added",after:a.content,lineCount:a.content.split(`
|
|
1216
|
-
`).length}),s.hasChanges=!0)}for(let a of t){let c=a.name.toLowerCase();!i.has(c)&&!
|
|
1217
|
-
`).length}),s.hasChanges=!0)}return s}function
|
|
1218
|
-
`);if(n.push(""),n.push(c("\u{1F4CB} Changes to context files:")),n.push(""),r.added.length>0)for(let
|
|
1219
|
-
`)}function
|
|
1221
|
+
`).length}),s.hasChanges=!0)}for(let a of t){let c=a.name.toLowerCase();!i.has(c)&&!ll(a.content)&&(s.removed.push({name:a.name,type:"removed",before:a.content,lineCount:a.content.split(`
|
|
1222
|
+
`).length}),s.hasChanges=!0)}return s}function mg(r,e={}){let{colorize:t=!0}=e,n=[],s=t?qt.green:p=>p,o=t?qt.red:p=>p,i=t?qt.yellow:p=>p,a=t?qt.dim:p=>p,c=t?qt.bold:p=>p;if(!r.hasChanges)return n.push(a("No changes detected (context is up to date)")),n.join(`
|
|
1223
|
+
`);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 gg(r,e={}){let{colorize:t=!0}=e,n=[],s=t?qt.green:c=>c,o=t?qt.red:c=>c,i=t?qt.cyan:c=>c,a=t?qt.dim:c=>c;for(let c of r.added){if(n.push(i(`@@ +${c.name} @@`)),c.after)for(let u of c.after.split(`
|
|
1220
1225
|
`))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(`
|
|
1221
1226
|
`).slice(0,5))n.push(o(`- ${u}`));c.before.split(`
|
|
1222
1227
|
`).length>5&&n.push(a(` ... ${c.before.split(`
|
|
@@ -1227,11 +1232,11 @@ ${o}`)}return n&&(n.endLine=e.length-1,t.push(n)),t}function vl(r){return r.incl
|
|
|
1227
1232
|
`).slice(0,5))n.push(o(`- ${u}`));c.before.split(`
|
|
1228
1233
|
`).length>5&&n.push(a(` ... ${c.before.split(`
|
|
1229
1234
|
`).length-5} more lines`))}n.push("")}return n.join(`
|
|
1230
|
-
`)}var
|
|
1231
|
-
`));let u=[];r.contextFiles.length>0&&u.push(`${r.contextFiles.length} context files`);let
|
|
1232
|
-
`)}function
|
|
1235
|
+
`)}var LP,fg=y(()=>{"use strict";LP=4;l(ug,"estimateTokens");l(dg,"parseMarkdownSections");l(ll,"isPreservedSection");l(pg,"generateSyncDiff");l(mg,"formatDiffPreview");l(gg,"formatFullDiff")});import UP from"node:path";async function ul(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 Ge.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(`
|
|
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 ct("sync"),{success:!0,data:r,metrics:{elapsed:t,contextFilesCount:n,agentCount:s,fileCount:r.stats.fileCount}}}async function hg(r){try{let e=await Ye.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=L.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 Sr(r){return r>=1e6?`${(r/1e6).toFixed(1)}M`:r>=1e3?`${(r/1e3).toFixed(1)}K`:r.toLocaleString()}function dl(r){return r<1e3?`${Math.round(r)}ms`:`${(r/1e3).toFixed(1)}s`}function yg(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 wg(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 | ${Sr(r.totalTokensSaved)} tokens |`),i.push(`| Compression | ${(r.compressionRate*100).toFixed(0)}% |`),i.push(`| Cost saved | ${Qn(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 | ${dl(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: ${Sr(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(`
|
|
1237
|
+
`)}function Sg(r,e){let t=[];t.push(`# Repository Analysis
|
|
1233
1238
|
`),t.push(`Generated: ${new Date().toLocaleString()}
|
|
1234
|
-
`);let n=
|
|
1239
|
+
`);let n=UP.basename(e);if(t.push(`## Project: ${n}
|
|
1235
1240
|
`),t.push(`## Stack Detected
|
|
1236
1241
|
`),r.packageJson){let i=r.packageJson;if(t.push(`### JavaScript/TypeScript
|
|
1237
1242
|
`),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
|
|
@@ -1244,37 +1249,37 @@ ${o}`)}return n&&(n.endLine=e.length-1,t.push(n)),t}function vl(r){return r.incl
|
|
|
1244
1249
|
`),t.push(`- **Total Files**: ${r.fileCount}`),t.push(`- **Directories**: ${s?.slice(0,15).join(", ")||"none"}${(s?.length||0)>15?` (+${(s?.length||0)-15} more)`:""}`),r.hasDockerfile&&t.push("- **Docker**: Detected"),r.hasDockerCompose&&t.push("- **Docker Compose**: Detected"),r.hasReadme&&t.push("- **Documentation**: README.md found"),t.push("");let o=r.gitStats;return t.push(`## Git Statistics
|
|
1245
1250
|
`),t.push(`- **Total Commits**: ${o?.totalCommits||0}`),t.push(`- **Contributors**: ${o?.contributors||0}`),t.push(`- **Age**: ${o?.age||"unknown"}`),t.push(""),r.gitLog&&(t.push(`## Recent Activity
|
|
1246
1251
|
`),r.gitLog.split(`
|
|
1247
|
-
`).slice(0,5).forEach(a=>{if(a.trim()){let[c,,u,
|
|
1252
|
+
`).slice(0,5).forEach(a=>{if(a.trim()){let[c,,u,d]=a.split("|");t.push(`- \`${c}\` ${d} (${u})`)}}),t.push("")),t.push(`## Recommendations
|
|
1248
1253
|
`),t.push("Based on detected stack, consider generating specialized agents using `/p:sync`.\n"),t.push(`---
|
|
1249
1254
|
`),t.push("*This analysis was generated automatically. For updated information, run `/p:analyze` again.*\n"),t.join(`
|
|
1250
|
-
`)}var
|
|
1251
|
-
`),
|
|
1255
|
+
`)}var kg=y(()=>{"use strict";Pn();Kr();cn();ms();Tn();We();l(ul,"showSyncResult");l(hg,"getSessionActivity");l(Sr,"formatTokens");l(dl,"formatDuration");l(yg,"generateSparkline");l(wg,"generateStatsMarkdown");l(Sg,"generateAnalysisSummary")});var sm={};Ln(sm,{AnalysisCommands:()=>On});import pl from"node:fs/promises";import bg from"node:path";import Pg from"prompts";var On,Jo=y(()=>{"use strict";rd();rs();od();Pn();Kr();cn();fg();Gr();de();Yr();F();ps();ms();Tn();kg();We();On=class extends le{static{l(this,"AnalysisCommands")}async analyze(e={},t=process.cwd()){try{await this.initializeAgent(),console.log(`\u{1F50D} Analyzing repository...
|
|
1256
|
+
`),je.init(t);let n=await Qe.build(t,e),s={packageJson:await je.readPackageJson(),cargoToml:await je.readCargoToml(),goMod:await je.readGoMod(),requirements:await je.readRequirements(),directories:await je.listDirectories(),fileCount:await je.countFiles(),gitStats:await je.getGitStats(),gitLog:await je.getGitLog(20),hasDockerfile:await je.fileExists("Dockerfile"),hasDockerCompose:await je.fileExists("docker-compose.yml"),hasReadme:await je.fileExists("README.md"),hasTsconfig:await je.fileExists("tsconfig.json"),hasViteConfig:await je.fileExists("vite.config.ts")||await je.fileExists("vite.config.js"),hasNextConfig:await je.fileExists("next.config.js")||await je.fileExists("next.config.mjs")},o=Sg(s,t),i=await R.getProjectId(t),a=n.paths.analysis||T.getFilePath(i,"analysis","repo-summary.md");await Re.get("Write")(a,o),await this.logToMemory(t,"repository_analyzed",{timestamp:L.getTimestamp(),fileCount:s.fileCount,gitCommits:s.gitStats.totalCommits}),await sd(i,t);let u=await(Ke(),ut(st)).getActiveProvider(),d=await Ge.installGlobalConfig();return d.success&&console.log(`\u{1F4DD} Updated ${T.getDisplayPath(d.path)}`),console.log(`\u2705 Analysis complete!
|
|
1252
1257
|
`),console.log("\u{1F4C4} Full report: analysis/repo-summary.md"),console.log(`\u{1F4DD} Context: ~/.prjct-cli/projects/${i}/${u.contextFile}
|
|
1253
|
-
`),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:",
|
|
1254
|
-
${Dg(g)}`),!(await Ng({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"),xl(m,i))}h.spin("Syncing project...");let p=await Sr.sync(e,{aiTools:t.aiTools,full:t.full});return p.success?(h.stop(),xl(p,i)):(h.fail(p.error||"Sync failed"),{success:!1,error:p.error})}catch(n){return 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 yn.getSummary(s),i=await yn.getDailyStats(s,30),a=await $g(s),c=await le.getPatternsSummary(s);if(t.json){let g={session:a,patterns:c,totalTokensSaved:o.totalTokensSaved,estimatedCostSaved:o.estimatedCostSaved,compressionRate:o.compressionRate,syncCount:o.syncCount,avgSyncDuration:o.avgSyncDuration,topAgents:o.topAgents,last30DaysTokens:o.last30DaysTokens,trend:o.trend,dailyStats:i};return console.log(JSON.stringify(g,null,2)),{success:!0,data:g}}let u=P.getGlobalProjectPath(s),p="Unknown";try{p=JSON.parse(await br.readFile(El.join(u,"project.json"),"utf-8")).name||"Unknown"}catch{}let m=await yn.read(s),d=m.firstSync?new Date(m.firstSync).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"N/A";if(console.log(""),console.log("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"),console.log("\u2502 \u{1F4CA} prjct-cli Stats Dashboard \u2502"),console.log(`\u2502 Project: ${p.padEnd(20).slice(0,20)} | Since: ${d.padEnd(12).slice(0,12)} \u2502`),console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"),console.log(""),console.log("\u{1F3AF} TODAY'S ACTIVITY"),a.sessionDuration&&console.log(` Duration: ${a.sessionDuration}`),console.log(` Tasks completed: ${a.tasksCompleted}`),console.log(` Features shipped: ${a.featuresShipped}`),a.agentsUsed.length>0){let g=a.agentsUsed.slice(0,3).map(f=>`${f.name} (${f.count}\xD7)`).join(", ");console.log(` Agents used: ${g}`)}if(console.log(""),(c.decisions>0||c.preferences>0)&&(console.log("\u{1F9E0} PATTERNS LEARNED"),console.log(` Decisions: ${c.learnedDecisions} confirmed (${c.decisions} total)`),console.log(` Preferences: ${c.preferences} saved`),console.log(` Workflows: ${c.workflows} tracked`),console.log("")),console.log("\u{1F4B0} TOKEN SAVINGS"),console.log(` Total saved: ${kr(o.totalTokensSaved)} tokens`),console.log(` Compression: ${(o.compressionRate*100).toFixed(0)}% average reduction`),console.log(` Estimated cost: ${es(o.estimatedCostSaved)} saved`),console.log(""),console.log("\u26A1 PERFORMANCE"),console.log(` Syncs completed: ${o.syncCount.toLocaleString()}`),console.log(` Avg sync time: ${Tl(o.avgSyncDuration)}`),console.log(""),o.topAgents.length>0){console.log("\u{1F916} AGENT USAGE (all time)");let g=o.topAgents.reduce((f,k)=>f+k.usageCount,0);for(let f of o.topAgents){let k=g>0?(f.usageCount/g*100).toFixed(0):0;console.log(` ${f.agentName.padEnd(12)}: ${k}% (${f.usageCount} uses)`)}console.log("")}if(i.length>0){console.log("\u{1F4C8} TREND (last 30 days)");let g=Mg(i);if(console.log(` ${g} ${kr(o.last30DaysTokens)} tokens saved`),o.trend!==0){let f=o.trend>0?"\u2191":"\u2193",k=o.trend>0?"+":"";console.log(` ${f} ${k}${o.trend.toFixed(0)}% vs previous 30 days`)}console.log("")}if(console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log("Export: prjct stats --export > stats.md"),console.log(""),t.export){let g=Fg(o,i,p,d,a,c);return console.log(g),{success:!0,data:{markdown:g}}}return{success:!0,data:{...o,session:a,patterns:c}}}catch(n){return console.error("\u274C Error:",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=pr(e),i=await o.check(s),a=await o.getSessionInfo(s),c=await Mt.getStatus(s);return t.json?(console.log(JSON.stringify({success:!0,...i,session:a,analysis:c})),{success:!0,data:{...i,session:a,analysis:c}}):(console.log(""),console.log(o.formatStatus(i)),console.log(""),console.log(o.formatSessionInfo(a)),(c.hasSealed||c.hasDraft)&&(console.log(""),console.log("Analysis:"),c.hasSealed&&console.log(` Sealed: ${c.sealedCommit} (${c.sealedAt})`),c.hasDraft&&console.log(` Draft: ${c.draftCommit} (pending seal)`)),console.log(""),{success:!0,data:{...i,session:a,analysis:c}})}catch(n){let s=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 Mt.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 Mt.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=P.getGlobalProjectPath(s),i=e;try{i=JSON.parse(await br.readFile(El.join(o,"project.json"),"utf-8")).repoPath||e}catch{}let a=await Mt.semanticVerify(s,i);if(t.json)return console.log(JSON.stringify(a)),{success:a.passed,data:a};console.log(""),a.passed?(h.done("Semantic verification passed"),console.log(` ${a.passedCount}/${a.checks.length} checks passed (${a.totalMs}ms)`)):(h.fail("Semantic verification failed"),console.log(` ${a.failedCount}/${a.checks.length} checks failed`)),console.log(""),console.log("Check Results:");for(let c of a.checks){let u=c.passed?"\u2713":"\u2717",p=c.passed?`${c.output} (${c.durationMs}ms)`:c.error||"Failed";console.log(` ${u} ${c.name}: ${p}`)}return console.log(""),{success:a.passed,data:a}}catch(n){let s=y(n);return t.json?console.log(JSON.stringify({success:!1,error:s})):h.fail(s),{success:!1,error:s}}}}});import{exec as OC}from"node:child_process";import{promisify as _C}from"node:util";async function bi(r){if(process.platform!=="darwin")return Kg(r);try{let{stdout:e}=await NC(`security find-generic-password -s "${LC}" -a "${r}" -w 2>/dev/null`);return e.trim()||null}catch{return Kg(r)}}function Kg(r){let t={"linear-api-key":"LINEAR_API_KEY","jira-api-token":"JIRA_API_TOKEN"}[r];return process.env[t]||null}var NC,LC,Ul=w(()=>{"use strict";M();NC=_C(OC),LC="prjct-cli";l(bi,"getCredential");l(Kg,"getEnvFallback")});import mt from"node:fs";import{createServer as Pv}from"node:net";Fi();ei();pn();Ft();M();He();import SC from"node:path";ct();K();M();Q();var mi=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:P.getGlobalProjectPath(t),timestamp:b()}}async execute(e,t,n=process.cwd()){let s=this.metadata.get(e),o;if(s?.requiresProject===!1)o={projectId:"",projectPath:n,globalPath:"",timestamp:b()};else try{o=await this.buildContext(n)}catch(c){return{success:!1,error: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: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()}},L=new mi;var Ss=class extends pe{static{l(this,"AnalyticsCommands")}async dash(e="default",t=process.cwd()){try{let n=await this.ensureProjectInit(t);if(!n.success)return n;let s=await R.getProjectId(t);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=SC.basename(t),i=await X.getCurrentTask(s),a=await Oe.getActiveTasks(s),c=await Wt.getRecent(s,5),u=await kt.getPending(s);if(e==="compact"){let g=i?`\u{1F3AF} ${i.description.slice(0,30)}`:"\u{1F4A4} idle",f=`\u{1F4CB} ${a.length}`,k=`\u{1F680} ${c.length}`;return h.done(`${g} | ${f} | ${k}`),{success:!0,view:"compact"}}if(e==="week"||e==="month"){let g=e==="week"?7:30,f=U.getDaysAgo(g),k=P.getFilePath(s,"memory","context.jsonl"),v=[];try{v=(await Pt.readJsonLines(k)).filter(Pe=>new Date(Pe.timestamp)>=f)}catch{v=[]}let x={tasksCompleted:v.filter(J=>J.action==="task_completed").length,featuresShipped:v.filter(J=>J.action==="feature_shipped").length,totalActions:v.length};console.log(`
|
|
1255
|
-
\u{1F4CA} ${e.toUpperCase()} PROGRESS - ${
|
|
1256
|
-
`),console.log("\u2550".repeat(50)),console.log(` Tasks completed: ${
|
|
1257
|
-
Activity: ${
|
|
1258
|
-
`),{success:!0,view:e,metrics:
|
|
1259
|
-
\u{1F5FA}\uFE0F ROADMAP - ${
|
|
1260
|
-
`),console.log("\u2550".repeat(50)),!
|
|
1261
|
-
`);else{let
|
|
1262
|
-
`)[0].trim();console.log(` ${
|
|
1263
|
-
`),{success:!0,view:"roadmap"}}console.log(`
|
|
1264
|
-
\u{1F4CA} DASHBOARD - ${
|
|
1265
|
-
`),console.log("\u2550".repeat(50));let
|
|
1266
|
-
${
|
|
1267
|
-
\u{1F3AF} CURRENT FOCUS`),
|
|
1268
|
-
\u{1F4CB} QUEUE`),
|
|
1269
|
-
\u{1F680} RECENT SHIPS`),
|
|
1270
|
-
\u{1F4A1} IDEAS`),console.log(` ${
|
|
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:",w(n)),{success:!1,error:w(n)}}}async sync(e=process.cwd(),t={}){try{let n=await this.ensureProjectInit(e);if(!n.success)return n;let s=await R.getProjectId(e);if(!s)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let o=T.getGlobalProjectPath(s),i=Date.now();if(t.package){let m=await T.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 wr.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(_t(`Synced package: ${p.name}`)):h.done(`Synced package: ${p.name}`),{success:g.success}}let a=bg.join(o,"context","CLAUDE.md"),c=null;try{c=await pl.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 wr.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 pl.readFile(a,"utf-8")}catch{p=""}let g=pg(c,p);if(u||h.stop(),!g.hasChanges)return t.md?(console.log(_t("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 pl.writeFile(a,c,"utf-8")},"restoreOriginal");if(t.md){await f();let k=[];for(let D of g.added)k.push(`Added: ${D.name} (${D.lineCount} lines)`);for(let D of g.modified)k.push(`Modified: ${D.name} (${D.lineCount} lines)`);for(let D of g.removed)k.push(`Removed: ${D.name} (${D.lineCount} lines)`);let v=me("## Sync Preview",k.length>0?ze("Changes",Tt(k),3):"No section changes.",Et({"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(v),{success:!0,isPreview:!0,diff:g,message:"Preview complete (awaiting confirmation)"}}if(u){await f();let k={added:g.added.map(v=>({name:v.name,lineCount:v.lineCount})),modified:g.modified.map(v=>({name:v.name,lineCount:v.lineCount})),removed:g.removed.map(v=>({name:v.name,lineCount:v.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:k,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(mg(g)),t.preview)return await f(),{success:!0,isPreview:!0,diff:g,message:"Preview complete (no changes applied)"};let S=await Pg({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(`
|
|
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(`
|
|
1260
|
+
\u{1F4CA} ${e.toUpperCase()} PROGRESS - ${i}
|
|
1261
|
+
`),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
|
+
Activity: ${S}
|
|
1263
|
+
`),{success:!0,view:e,metrics:f}}if(e==="roadmap"){let m=await Qe.build(t),p=await Re.get("Read")(m.paths.roadmap);if(console.log(`
|
|
1264
|
+
\u{1F5FA}\uFE0F ROADMAP - ${i}
|
|
1265
|
+
`),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 k=f.split(`
|
|
1267
|
+
`)[0].trim();console.log(` ${S+1}. ${k}`)}),g.length>5&&console.log(` ... and ${g.length-5} more`)}return console.log(`${"\u2550".repeat(50)}
|
|
1268
|
+
`),{success:!0,view:"roadmap"}}if(n.md){let m=a?`${a.description}${a.startedAt?` (started ${L.calculateDuration(new Date(a.startedAt))} ago)`:""}`:"No active task",p=c.length>0?c.slice(0,5).map(S=>{let k=S.priority?` [${S.priority}]`:"";return`${S.description}${k}`}):["Queue is empty"],g=u.length>0?u.slice(0,5).map(S=>{let k=S.shippedAt?new Date(S.shippedAt).toLocaleDateString():"";return`${S.name}${k?` (${k})`:""}`}):["Nothing shipped yet"],f=me(`## Dashboard: ${i}`,ze("Current Focus",m,3),ze(`Queue (${c.length})`,Tt(p,!0),3),ze("Recent Ships",Tt(g),3),ze("Ideas",`${d.length} pending`,3),_e([{label:"Start task",command:"p. task"},{label:"Complete",command:"p. done"},{label:"Ship",command:"p. ship"}]));console.log(f)}else{console.log(`
|
|
1269
|
+
\u{1F4CA} DASHBOARD - ${i}
|
|
1270
|
+
`),console.log("\u2550".repeat(50));let m=pr(t),p=await m.check(o),g=m.getWarning(p);if(g&&console.log(`
|
|
1271
|
+
${g}`),console.log(`
|
|
1272
|
+
\u{1F3AF} CURRENT FOCUS`),a){if(console.log(` ${a.description}`),a.startedAt){let f=L.calculateDuration(new Date(a.startedAt));console.log(` Started: ${f} ago`)}}else console.log(" No active task. Use /p:work to start.");console.log(`
|
|
1273
|
+
\u{1F4CB} QUEUE`),c.length===0?console.log(" Queue is empty"):(c.slice(0,3).forEach((f,S)=>{let k=f.priority?`[${f.priority}]`:"";console.log(` ${S+1}. ${f.description.slice(0,40)} ${k}`)}),c.length>3&&console.log(` ... and ${c.length-3} more`)),console.log(`
|
|
1274
|
+
\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
|
+
\u{1F4A1} IDEAS`),console.log(` ${d.length} pending ideas`),console.log(`
|
|
1271
1276
|
${"\u2550".repeat(50)}`),console.log(`\u{1F4A1} /p:work to start | /p:done to complete | /p:ship to ship
|
|
1272
|
-
`)
|
|
1277
|
+
`)}return await this.logToMemory(t,"dash_viewed",{view:e,timestamp:L.getTimestamp()}),{success:!0,view:"default",stats:{currentTask:a?.description||null,queueCount:c.length,shippedCount:u.length,ideasCount:d.length}}}catch(s){return h.fail(w(s)),{success:!1,error:w(s)}}}async help(e="",t=process.cwd()){try{if(!e){console.log(`
|
|
1273
1278
|
PRJCT COMMANDS
|
|
1274
|
-
`),console.log("=".repeat(50));let i=
|
|
1275
|
-
${m?.title||u}:`),
|
|
1279
|
+
`),console.log("=".repeat(50));let i=U.getAllCategories(),a=U.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
|
+
${m?.title||u}:`),d.forEach(p=>{let g=p.params?` ${p.params}`:"";console.log(` ${p.name}${g}`),console.log(` ${p.description}`)})}),console.log(`
|
|
1276
1281
|
${"\u2550".repeat(50)}`),console.log(`\u{1F4A1} Use /p:help <command> for detailed help
|
|
1277
|
-
`),{success:!0,topic:"overview"}}let n=
|
|
1282
|
+
`),{success:!0,topic:"overview"}}let n=U.getByName(e);if(n){if(console.log(`
|
|
1278
1283
|
\u{1F4DA} HELP: /p:${n.name}
|
|
1279
1284
|
`),console.log("\u2550".repeat(50)),console.log(`Description: ${n.description}`),n.params&&console.log(`Parameters: ${n.params}`),n.usage&&(console.log(`
|
|
1280
1285
|
Usage:`),n.usage.claude&&console.log(` Claude: ${n.usage.claude}`),n.usage.terminal&&console.log(` Terminal: ${n.usage.terminal}`)),n.features){console.log(`
|
|
@@ -1284,7 +1289,7 @@ ${"\u2550".repeat(50)}
|
|
|
1284
1289
|
\u{1F4A1} Did you mean /p:${a.command}?`),console.log(` ${a.hint}
|
|
1285
1290
|
`),{success:!0,topic:e,suggestion:a.command};return console.log(`
|
|
1286
1291
|
\u2753 Unknown topic: ${e}`),console.log(` Use /p:help to see all commands
|
|
1287
|
-
`),{success:!1,error:`Unknown topic: ${e}`}}catch(n){return h.fail(
|
|
1292
|
+
`),{success:!1,error:`Unknown topic: ${e}`}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}_generateSparkline(e,t){let n=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],s=new Date,o=[];for(let a=t-1;a>=0;a--){let c=new Date(s);c.setDate(c.getDate()-a);let u=new Date(c.setHours(0,0,0,0)),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();it();re();Ct();F();import GP from"node:fs/promises";import zP from"node:path";var _n=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=T.getGlobalProjectPath(a),u=await O.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 _o.execute(s,o,t)}catch(f){console.error(`Warning: Orchestrator failed: ${w(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: ${w(n)}`}}}async loadRepoAnalysis(e){try{let t=zP.join(e,"analysis","repo-analysis.json"),n=await GP.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}}},LL=new _n;We();cn();Ct();de();F();We();async function ci(r){let e=await R.getProjectId(r),t={rotated:[],totalSize:0,freedSpace:0};if(!e)return{success:!0,results:t};let s=G.get(e,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(s>500){let o=s-500;G.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(ci,"cleanupMemory");async function li(r){let e=await R.getProjectId(r);if(!e)return;let n=G.get(e,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(n>500){let s=n-500;G.run(e,"DELETE FROM events WHERE id IN (SELECT id FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?)",s)}}l(li,"cleanupMemoryInternal");async function ml(r={},e=process.cwd()){try{if(r.memory===!0||r.type==="memory"){h.spin("cleaning memory...");let a=await ci(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=G.get(n,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(i>100){let a=i-100;G.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 Ee.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 - ${w(a)}`)}try{let c=(await ce.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 - ${w(a)}`)}return await li(e),await Ye.log(e,"cleanup_performed",{items:s.length,timestamp:L.getTimestamp()}),h.done(`${s.length} items cleaned`),{success:!0,cleaned:s}}catch(t){return h.fail(w(t)),{success:!1,error:w(t)}}}l(ml,"cleanup");cn();F();We();import Cg from"node:path";async function gl(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=Cg.join(T.getGlobalProjectPath(i),"planning","designs");await ne.ensureDir(a);let c="";switch(n){case"architecture":c=`# Architecture Design: ${o}
|
|
1288
1293
|
|
|
1289
1294
|
*Use templates/design/architecture.md for full design*
|
|
1290
1295
|
`;break;case"api":c=`# API Design: ${o}
|
|
@@ -1299,12 +1304,12 @@ ${"\u2550".repeat(50)}
|
|
|
1299
1304
|
`;break;case"flow":c=`# Flow Design: ${o}
|
|
1300
1305
|
|
|
1301
1306
|
*Use templates/design/flow.md for full design*
|
|
1302
|
-
`;break}let u=`${n}-${o.toLowerCase().replace(/\s+/g,"-")}.md`,
|
|
1307
|
+
`;break}let u=`${n}-${o.toLowerCase().replace(/\s+/g,"-")}.md`,d=Cg.join(a,u);return await ne.writeFile(d,c),await Ye.log(t,"design_created",{type:n,target:o,timestamp:L.getTimestamp()}),h.done(`${n} design created`),{success:!0,designPath:d,type:n,target:o}}catch(n){return h.fail(w(n)),{success:!1,error:w(n)}}}l(gl,"design");cn();F();We();import ys from"node:path";async function fl(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=T.getFilePath(e,"progress","sessions/current.json"),n=null;try{let s=await ne.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(`
|
|
1303
1308
|
Found abandoned session:
|
|
1304
|
-
`),console.log(` Task: ${n.task}`),n.startedAt){let s=
|
|
1309
|
+
`),console.log(` Task: ${n.task}`),n.startedAt){let s=L.calculateDuration(new Date(n.startedAt));console.log(` Started: ${s} ago`)}return n.context&&console.log(` Context: ${n.context.slice(0,100)}...`),console.log(`
|
|
1305
1310
|
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
|
|
1306
|
-
`),{success:!0,session:n}}catch(e){return h.fail(
|
|
1307
|
-
`).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 ne.writeFile(n,JSON.stringify(s,null,2)),await
|
|
1311
|
+
`),{success:!0,session:n}}catch(e){return h.fail(w(e)),{success:!1,error:w(e)}}}l(fl,"recover");async function hl(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=ys.join(T.getGlobalProjectPath(e),"snapshots");await ne.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=ys.join(t,"history.json"),c={snapshots:[],current:-1};try{let u=await ne.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 ne.writeFile(a,JSON.stringify(c,null,2)),await Ye.log(r,"undo_performed",{snapshotId:i,timestamp:L.getTimestamp()}),h.done("changes stashed (use /p:redo to restore)"),{success:!0,snapshotId:i}}catch(s){return h.failWithHint("GIT_OPERATION_FAILED"),{success:!1,error:w(s)}}}catch(e){return h.fail(w(e)),{success:!1,error:w(e)}}}l(hl,"undo");async function yl(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=ys.join(T.getGlobalProjectPath(e),"snapshots"),n=ys.join(t,"history.json"),s;try{let i=await ne.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(`
|
|
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 ne.writeFile(n,JSON.stringify(s,null,2)),await Ye.log(r,"redo_performed",{timestamp:L.getTimestamp()}),h.done("changes restored"),{success:!0}):(h.warn("no prjct undo point found"),{success:!1,message:"No prjct undo point found"}):(h.warn("no stashed changes"),{success:!1,message:"No stashed changes found"})}catch(i){return h.failWithHint("GIT_OPERATION_FAILED"),{success:!1,error:w(i)}}}catch(e){return h.fail(w(e)),{success:!1,error:w(e)}}}l(yl,"redo");async function wl(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=ys.join(T.getGlobalProjectPath(e),"snapshots"),n=ys.join(t,"history.json"),s;try{let o=await ne.readFile(n);s=JSON.parse(o)}catch(o){if(C(o)||o instanceof SyntaxError)return console.log(`
|
|
1308
1313
|
SNAPSHOT HISTORY
|
|
1309
1314
|
`),console.log("=".repeat(50)),console.log(" No snapshots yet."),console.log(` Use /p:undo to create a snapshot.
|
|
1310
1315
|
`),{success:!0,snapshots:[]};throw o}return console.log(`
|
|
@@ -1312,32 +1317,32 @@ ${"\u2550".repeat(50)}
|
|
|
1312
1317
|
`),console.log("=".repeat(50)),s.snapshots.length===0?(console.log(" No snapshots yet."),console.log(` Use /p:undo to create a snapshot.
|
|
1313
1318
|
`)):(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
|
|
1314
1319
|
`)),console.log(`${"=".repeat(50)}
|
|
1315
|
-
`),{success:!0,snapshots:s.snapshots,current:s.current}}catch(e){return h.fail(
|
|
1316
|
-
${
|
|
1320
|
+
`),{success:!0,snapshots:s.snapshots,current:s.current}}catch(e){return h.fail(w(e)),{success:!1,error:w(e)}}}l(wl,"history");var ws=class extends le{static{l(this,"MaintenanceCommands")}_cleanupMemory=ci;_cleanupMemoryInternal=li;async cleanup(e={},t=process.cwd()){let n=await this.ensureProjectInit(t);return n.success?ml(e,t):n}async design(e=null,t={},n=process.cwd()){let s=await this.ensureProjectInit(n);return s.success?gl(e,t,n):s}async recover(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?fl(e):t}async undo(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?hl(e):t}async redo(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?yl(e):t}async history(e=process.cwd()){let t=await this.ensureProjectInit(e);return t.success?wl(e):t}};import fe from"chalk";de();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){G.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)G.appendEvent(e,`perf.${o.metric}`,{metric:o.metric,value:o.value,unit:o.unit,context:t});return n}recordContextCorrectness(e,t){G.appendEvent(e,"perf.context_correctness",{metric:"context_correctness",...t})}recordSubtaskHandoff(e,t){G.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 G.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,k)=>S+k,0)/g.length),peakHeapMB:p(Math.max(...g)),avgRssMB:f.length>0?p(f.reduce((S,k)=>S+k,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,k)=>S+k,0)/f.length),min:Math.min(...f),max:Math.max(...f),count:f.length,unit:"ms"}}return o}},WP=new Sl,vg=WP;F();We();var ln={startup:{max:500,unit:"ms"},heapMB:{max:80,unit:"MB"},contextRate:{min:100,unit:"%"},handoffRate:{min:100,unit:"%"}};function ui(r,e,t){return t==="below"?r<=e?fe.green("\u2713"):fe.yellow("\u26A0"):r>=e?fe.green("\u2713"):fe.yellow("\u26A0")}l(ui,"statusIcon");var Ss=class extends le{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 vg.getReport(s,o);if(!(i.startup||i.memory||i.contextCorrectness||i.subtaskHandoff||i.commandDurations))return console.log(`
|
|
1321
|
+
${fe.dim("No performance data yet.")}`),console.log(`${fe.dim("Metrics are collected automatically as you use the CLI.")}
|
|
1317
1322
|
`),{success:!0,message:"No data"};if(console.log(`
|
|
1318
|
-
${
|
|
1319
|
-
${
|
|
1320
|
-
`),!(await
|
|
1323
|
+
${fe.cyan("Performance Report")} ${fe.dim(`(last ${o} days)`)}`),console.log("\u2550".repeat(55)),i.startup){let c=ui(i.startup.avg,ln.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: <${ln.startup.max}ms`)}`)}if(i.memory){let c=ui(i.memory.peakHeapMB,ln.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: <${ln.heapMB.max}MB`)}`)}if(i.contextCorrectness){let c=ui(i.contextCorrectness.rate,ln.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: ${ln.contextRate.min}%`)}`)}if(i.subtaskHandoff){let c=ui(i.subtaskHandoff.rate,ln.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: ${ln.handoffRate.min}%`)}`)}if(i.commandDurations&&Object.keys(i.commandDurations).length>0){console.log(`
|
|
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(w(n)),{success:!1,error:w(n)}}}};Vo();Pn();re();F();Fe();kn();We();import kl from"node:fs/promises";import BP from"node:path";import Z from"chalk";var ks=class extends le{static{l(this,"SetupCommands")}async start(){let t=await(Ke(),ut(st)).getActiveProvider();if(console.log(`\u{1F680} Setting up prjct for ${t.displayName}...
|
|
1325
|
+
`),!(await Ge.checkInstallation()).claudeDetected)return{success:!1,message:`\u274C ${t.displayName} not detected.
|
|
1321
1326
|
|
|
1322
1327
|
Please install it first:
|
|
1323
|
-
- ${t.displayName}: ${t.docsUrl}`};console.log("\u{1F4E6} Installing /p:* commands...");let s=await
|
|
1328
|
+
- ${t.displayName}: ${t.docsUrl}`};console.log("\u{1F4E6} Installing /p:* commands...");let s=await Ge.installCommands();if(!s.success)return{success:!1,message:`\u274C Installation failed: ${s.error}`};if(console.log(`
|
|
1324
1329
|
\u2705 Installed ${s.installed?.length??0} commands to:
|
|
1325
|
-
${
|
|
1330
|
+
${T.getDisplayPath(s.path||"")}`),(s.errors?.length??0)>0){console.log(`
|
|
1326
1331
|
\u26A0\uFE0F ${s.errors?.length??0} errors:`);for(let o of s.errors??[])console.log(` - ${o.file}: ${o.error}`)}return console.log(`
|
|
1327
1332
|
\u{1F389} Setup complete!`),console.log(`
|
|
1328
1333
|
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...
|
|
1329
|
-
`),e.force&&(console.log("\u{1F5D1}\uFE0F Removing existing installation..."),await
|
|
1334
|
+
`),e.force&&(console.log("\u{1F5D1}\uFE0F Removing existing installation..."),await Ge.uninstallCommands()),console.log("\u{1F4E6} Installing /p:* commands...");let t=await Ge.updateCommands();if(!t.success)return{success:!1,message:`\u274C Setup failed: ${t.error}`};if(console.log(`
|
|
1330
1335
|
\u2705 Installed ${t.installed?.length??0} commands`),(t.errors?.length??0)>0){console.log(`
|
|
1331
1336
|
\u26A0\uFE0F ${t.errors?.length??0} errors:`);for(let a of t.errors??[])console.log(` - ${a.file}: ${a.error}`)}console.log(`
|
|
1332
|
-
\u{1F4DD} Installing global configuration...`);let n=await
|
|
1337
|
+
\u{1F4DD} Installing global configuration...`);let n=await Ge.installGlobalConfig(),s=n.path?T.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(Ke(),ut(st)).getActiveProvider()).name==="claude"){console.log(`
|
|
1333
1338
|
\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(`
|
|
1334
1339
|
\u{1F389} Setup complete!
|
|
1335
|
-
`),this.showAsciiArt(),{success:!0,message:""}}async installStatusLine(){try{let e=
|
|
1340
|
+
`),this.showAsciiArt(),{success:!0,message:""}}async installStatusLine(){try{let e=T.getClaudeDir(),t=T.getClaudeSettingsPath(),n=BP.join(e,"prjct-statusline.sh"),s=`#!/bin/bash
|
|
1336
1341
|
# prjct Status Line for Claude Code
|
|
1337
1342
|
# Shows version update notifications and current task
|
|
1338
1343
|
|
|
1339
1344
|
# Current CLI version (embedded at install time)
|
|
1340
|
-
CLI_VERSION="${
|
|
1345
|
+
CLI_VERSION="${os}"
|
|
1341
1346
|
|
|
1342
1347
|
# Read JSON context from stdin (provided by Claude Code)
|
|
1343
1348
|
read -r json
|
|
@@ -1388,18 +1393,18 @@ fi
|
|
|
1388
1393
|
|
|
1389
1394
|
# Default: show prjct branding
|
|
1390
1395
|
echo "\u26A1 prjct"
|
|
1391
|
-
`;await
|
|
1392
|
-
${
|
|
1393
|
-
`)[0])),{success:!1,failed:o,output:c}}}l(
|
|
1396
|
+
`;await kl.writeFile(n,s,{mode:493});let o={};if(await $(t))try{o=JSON.parse(await kl.readFile(t,"utf8"))}catch{}return o.statusLine={type:"command",command:n},await kl.writeFile(t,JSON.stringify(o,null,2)),{success:!0}}catch(e){return{success:!1,error:w(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${os} 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("")}};rs();Ct();F();ps();ms();import Ig from"node:path";Fe();import Ze from"node:path";async function VP(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 $(Ze.join(r,"pnpm-lock.yaml"))?"pnpm":await $(Ze.join(r,"yarn.lock"))?"yarn":await $(Ze.join(r,"bun.lockb"))||await $(Ze.join(r,"bun.lock"))?"bun":(await $(Ze.join(r,"package-lock.json")),"npm")}l(VP,"detectPackageManager");function xg(r,e){return r==="yarn"?`yarn ${e}`:r==="pnpm"?`pnpm run ${e}`:r==="bun"?`bun run ${e}`:`npm run ${e}`}l(xg,"pmRun");function JP(r){return r==="yarn"?"yarn test":r==="pnpm"?"pnpm test":r==="bun"?"bun test":"npm test"}l(JP,"pmTest");async function bl(r){let e=Ze.join(r,"package.json"),t=await pn(e,null);if(t){let o=await VP(r,t),i=t.scripts||{},a={stack:"js",packageManager:o};return i.lint&&(a.lint={tool:o,command:xg(o,"lint")}),i.typecheck&&(a.typecheck={tool:o,command:xg(o,"typecheck")}),i.test&&(a.test={tool:o,command:JP(o)}),a}if(await $(Ze.join(r,"pytest.ini")))return{stack:"python",test:{tool:"pytest",command:"pytest"}};let n=await Gn(Ze.join(r,"pyproject.toml"),"");return n.includes("[tool.pytest")||n.includes("pytest")?{stack:"python",test:{tool:"pytest",command:"pytest"}}:await $(Ze.join(r,"Cargo.toml"))?{stack:"rust",test:{tool:"cargo",command:"cargo test"}}:await $(Ze.join(r,"go.mod"))?{stack:"go",test:{tool:"go",command:"go test ./..."}}:(await zn(r)).some(o=>o.endsWith(".sln")||o.endsWith(".csproj")||o.endsWith(".fsproj"))?{stack:"dotnet",test:{tool:"dotnet",command:"dotnet test"}}:await $(Ze.join(r,"pom.xml"))?{stack:"java",test:{tool:"maven",command:"mvn test"}}:await $(Ze.join(r,"gradlew"))&&(await $(Ze.join(r,"build.gradle"))||await $(Ze.join(r,"build.gradle.kts")))?{stack:"java",test:{tool:"gradle",command:"./gradlew test"}}:{stack:"unknown"}}l(bl,"detectProjectCommands");rs();F();Qt();import{exec as qP}from"node:child_process";import{promisify as KP}from"node:util";import Dt from"chalk";var YP=KP(qP),di=new Map,bs=new Map;function kr(r,e){return`workflow:${r}_${e}`}l(kr,"prefKey");async function Tg(r,e){let t=kr(e.hook,e.command);switch(e.scope){case"permanent":await pe.recordDecision(r,t,e.action,"workflow");break;case"session":di.set(t,e);break;case"once":bs.set(t,e);break}}l(Tg,"setWorkflowPreference");async function XP(r,e){let t={};for(let n of["before","after","skip"]){let s=kr(n,e),o=bs.get(s);if(o){n==="skip"?t.skip=o.action==="true":t[n]=o.action;continue}let i=di.get(s);if(i){n==="skip"?t.skip=i.action==="true":t[n]=i.action;continue}let a=await pe.getSmartDecision(r,s);a&&(n==="skip"?t.skip=a==="true":t[n]=a)}return t}l(XP,"getWorkflowPreferences");async function un(r,e,t,n={}){if(n.skipHooks)return{success:!0};let s=await XP(r,t);if(s.skip)return{success:!0,skipped:[t]};let o=s[e];if(!o)return{success:!0};let i=kr(e,t);bs.has(i)&&bs.delete(i),console.log(`
|
|
1397
|
+
${Dt.dim(`Running ${e}-${t}: ${o}`)}`);try{let a=Date.now();await YP(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(`${Dt.green("\u2713")} ${Dt.dim(`(${u})`)}`),{success:!0}}catch(a){console.log(Dt.red("\u2717 failed"));let c=w(a)||"Unknown error";return console.log(Dt.dim(c.split(`
|
|
1398
|
+
`)[0])),{success:!1,failed:o,output:c}}}l(un,"runWorkflowHooks");async function Pl(r){let e=[],t=["task","done","ship","sync"],n=["before","after","skip"];for(let s of t)for(let o of n){let i=kr(o,s),a=bs.get(i);if(a){e.push({key:`${o} ${s}`,action:a.action,scope:"once"});continue}let c=di.get(i);if(c){e.push({key:`${o} ${s}`,action:c.action,scope:"session"});continue}let u=await pe.getSmartDecision(r,i);u&&e.push({key:`${o} ${s}`,action:u,scope:"permanent"})}return e}l(Pl,"listWorkflowPreferences");async function Eg(r,e,t){let n=kr(e,t);return bs.delete(n),di.delete(n),await pe.recordDecision(r,n,"","workflow:remove"),!0}l(Eg,"removeWorkflowPreference");function Ag(r){if(r.length===0)return`${Dt.dim(Gs.NO_PREFERENCES)}
|
|
1394
1399
|
|
|
1395
|
-
Set one: "${
|
|
1396
|
-
`)}l(
|
|
1400
|
+
Set one: "${Gs.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"?Dt.green("permanent"):t.scope==="session"?Dt.yellow("session"):Dt.dim("once");e.push(` [${n}] ${t.key.padEnd(15)} \u2192 ${t.action}`)}return e.push(""),e.push(Dt.dim(`Modify: "${Gs.MODIFY_EXAMPLE}"`)),e.push(Dt.dim(`Remove: "${Gs.REMOVE_EXAMPLE}"`)),e.join(`
|
|
1401
|
+
`)}l(Ag,"formatWorkflowPreferences");We();var Ps=class extends le{static{l(this,"ShippingCommands")}async _runWithExitCode(e){let t=Re.get("Bash"),s=`bash -lc "set +e; ${e.replace(/"/g,'\\"')} 2>&1; echo __EXIT:$?"`,o=await t(s),i=`${o.stdout}
|
|
1397
1402
|
${o.stderr}`.trim(),a=i.split(`
|
|
1398
|
-
`),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,
|
|
1403
|
+
`),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(`
|
|
1399
1404
|
`).filter(m=>!m.startsWith("__EXIT:")).join(`
|
|
1400
|
-
`).trim();return{exitCode:Number.isFinite(u)?u:1,output:
|
|
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 O.getCurrentTask(o))?.description||"current work");let a=await un(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 He.addShipped(o,{name:i,version:d}),await this.logToMemory(t,"feature_shipped",{feature:i,version:d,timestamp:L.getTimestamp()}),await pe.learnDecision(o,"commit_footer","prjct","ship"),u.success&&await pe.recordDecision(o,"test_before_ship","true","ship"),(!c.success||!u.success)&&await pe.recordWorkflow(o,"quick_ship",{description:"Ship without full checks",feature_type:i.toLowerCase().includes("doc")?"docs":"other"}),await un(o,"after","ship",{projectPath:t,skipHooks:n.skipHooks}),n.md){let f=Eo("ship"),S=me(_t(`Shipped: ${i}`,`Version: ${d}`),ze("Results",Tt([`Lint: ${c.message}`,`Tests: ${u.message}`,`Commit: ${m.success?"created":m.message}`,`Push: ${p}`]),3),_e(f.map(k=>({label:k.desc,command:k.cmd}))));console.log(S)}else h.done(`v${d} shipped`),ct("ship");return{success:!0,feature:i,version:d}}catch(s){return h.fail(w(s)),{success:!1,error:w(s)}}}async _runLint(e){try{let t=await bl(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 bl(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=Ig.join(e,"package.json"),n=await ne.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 ne.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=Ig.join(n,"CHANGELOG.md"),o=await ne.readFile(s,`# Changelog
|
|
1401
1406
|
|
|
1402
|
-
`),i=`## [${t}] - ${
|
|
1407
|
+
`),i=`## [${t}] - ${L.formatDate(new Date)}
|
|
1403
1408
|
|
|
1404
1409
|
### Added
|
|
1405
1410
|
- ${e}
|
|
@@ -1408,23 +1413,22 @@ ${o.stderr}`.trim(),a=i.split(`
|
|
|
1408
1413
|
|
|
1409
1414
|
`,`# Changelog
|
|
1410
1415
|
|
|
1411
|
-
${i}`);await ne.writeFile(s,a)}catch(s){
|
|
1412
|
-
|
|
1413
|
-
Generated with [p/](https://www.prjct.app/)`;return await
|
|
1414
|
-
${
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
${me.dim("Projection:")}`),console.log(` Backlog: ${me.bold(`${p} pts`)} remaining`),console.log(` At current velocity: ~${m.sprints} sprints (${m.sprints*(o.sprintLengthDays??7)} days)`),console.log(` Estimated completion: ${me.bold(d)}`)}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{...sn,...n.velocity}}catch{}return sn}};Vc();zc();Rn();var MC=[1,2,3,5,8,13,21],FC={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}},Vg=l(r=>MC.includes(r),"isValidPoint"),Si=l(r=>FC[r],"pointsToMinutes"),Bg=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"),qg=l(r=>{let e=Si(r);return`${Bg(e.min)}\u2013${Bg(e.max)}`},"pointsToTimeRange");Wr();var ki=300*1e3,Me=new yt({ttl:ki,maxSize:100}),At=new yt({ttl:ki,maxSize:10}),Es=new yt({ttl:ki,maxSize:5}),As=new yt({ttl:ki,maxSize:5});function Nl(){Me.clear(),At.clear(),Es.clear(),As.clear()}l(Nl,"clearLinearCache");function Ll(){return{issues:Me.stats(),assignedIssues:At.stats(),teams:Es.stats(),projects:As.stats()}}l(Ll,"getLinearCacheStats");M();Ul();var UC={backlog:"backlog",unstarted:"todo",started:"in_progress",completed:"done",canceled:"cancelled",cancelled:"cancelled"},HC={0:"none",1:"urgent",2:"high",3:"medium",4:"low"},Xg={none:0,urgent:1,high:2,medium:3,low:4},Pi=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 bi("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(p=>p.key===s);if(!c)return null;let u=await c.issues({first:1,filter:{number:{eq:i}}});return u.nodes.length>0?this.mapIssue(u.nodes[0]):null}let t=await this.sdk.issue(e);return this.mapIssue(t)}catch{return null}}async createIssue(e){if(!this.sdk)throw new Error("Linear not initialized");let t=e.teamId||this.config?.defaultTeamId;if(!t)throw new Error("Team ID required for creating issues");let s=await(await this.sdk.createIssue({teamId:t,title:e.title,description:e.description,priority:e.priority?Xg[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=Xg[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:UC[t?.type||"backlog"]||"backlog",priority:HC[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 Pi;var Ci=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)Me.set(`issue:${o.id}`,o),Me.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)Me.set(`issue:${i.id}`,i),Me.set(`issue:${i.externalId}`,i);return o}async fetchIssue(e){this.ensureInitialized();let t=`issue:${e}`,n=Me.get(t);if(n)return n;let s=await qe.fetchIssue(e);return s&&(Me.set(`issue:${s.id}`,s),Me.set(`issue:${s.externalId}`,s)),s}async createIssue(e){this.ensureInitialized();let t=await qe.createIssue(e);return Me.set(`issue:${t.id}`,t),Me.set(`issue:${t.externalId}`,t),At.clear(),t}async updateIssue(e,t){this.ensureInitialized();let n=await qe.updateIssue(e,t);return Me.set(`issue:${n.id}`,n),Me.set(`issue:${n.externalId}`,n),n}async markInProgress(e){this.ensureInitialized(),await qe.markInProgress(e),Me.delete(`issue:${e}`),At.clear()}async markDone(e){this.ensureInitialized(),await qe.markDone(e),Me.delete(`issue:${e}`),At.clear()}async addComment(e,t){this.ensureInitialized(),await qe.addComment(e,t)}async getTeams(){this.ensureInitialized();let e=Es.get("teams");if(e)return e;let t=await qe.getTeams();return Es.set("teams",t),t}async getProjects(){this.ensureInitialized();let e=As.get("projects");if(e)return e;let t=await qe.getProjects();return As.set("projects",t),t}clearCache(){Nl()}getCacheStats(){return Ll()}ensureInitialized(){if(!this.initialized)throw new Error("Linear service not initialized. Call linearService.initialize() first or run `p. linear setup`.")}},dt=new Ci;ea();at();M();var Yg=1800*1e3,vi=class{static{l(this,"LinearSync")}async pullAll(e){let t=new Date().toISOString(),n=[];try{let s=await dt.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:Yg,issues:o};return F.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 dt.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 dt.markInProgress(t):n==="done"&&await dt.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||Yg;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 F.getDoc(e,"issues")}catch{return null}}saveIssues(e,t){F.setDoc(e,"issues",t)}updateIssueInCache(e,t,n){let s=this.loadIssues(e);s||(s=Fu("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}}},GC=new vi;wt();Ft();M();or();M();Ee();Ul();import zC from"node:fs/promises";import JC from"node:os";import WC from"node:path";function BC(r){return WC.join(JC.homedir(),".prjct-cli","projects",r,"config","credentials.json")}l(BC,"getCredentialsPath");async function xi(r){let e=BC(r);if(!await D(e))return{};try{return JSON.parse(await zC.readFile(e,"utf-8"))}catch(t){return console.error("[project-credentials] Failed to read credentials:",y(t)),{}}}l(xi,"getProjectCredentials");async function Hl(r){let e=await xi(r);return e.linear?.apiKey?e.linear.apiKey:bi("linear-api-key")}l(Hl,"getLinearApiKey");Rn();He();var Is=class extends pe{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 h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};if(e){let i=await mn(o,"before","task",{projectPath:t,skipHooks:n.skipHooks});if(!i.success)return{success:!1,error:`Hook failed: ${i.failed}`};let a=await Yo.execute("task",{task:e},t);if(!a.success)return h.fail(a.error||"Failed to execute task"),{success:!1,error:a.error};let c,u=e;if(/^[A-Z]+-\d+$/.test(e))try{let f=await xi(o),k=await Hl(o);if(k&&f.linear?.teamId){await dt.initializeFromApiKey(k,f.linear.teamId);let v=await dt.fetchIssue(e);v&&(c=e,u=`${e}: ${v.title}`,await dt.markInProgress(e))}}catch{}await X.startTask(o,{id:ie(),description:u,sessionId:ie(),linearId:c});let m=await Gc.getAvailableAgents(t),d=m.length>0?m.join(", "):"none (run p. sync)",g=a.orchestratorContext?.agents?.length||m.length;return h.done(`${e}`,{agents:g>0?g:void 0}),rr("working"),nt("task"),await this.logToMemory(t,"task_started",{task:e,agenticMode:!0,availableAgents:m,orchestratorContext:a.orchestratorContext,timestamp:U.getTimestamp()}),await mn(o,"after","task",{projectPath:t,skipHooks:n.skipHooks}),{...a,success:!0,task:e,agenticMode:!0,availableAgents:m,fibonacci:{isValidPoint:Vg,pointsToMinutes:Si,pointsToTimeRange:qg,storeEstimate:l(async f=>{let k=Si(f);return await X.updateCurrentTask(o,{estimatedPoints:f,estimatedMinutes:k.typical}),k},"storeEstimate")}}}else{let i=await X.getCurrentTask(o);return i?(h.done(`working on: ${i.description}`),{success:!0,task:i.description,currentTask:i}):(h.warn("no active task"),{success:!0,message:"No active task"})}}catch(s){return h.fail(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 X.getCurrentTask(s);if(!o)return h.warn("no active task"),{success:!0,message:"No active task to complete"};let i=await mn(s,"before","done",{projectPath:e,skipHooks:t.skipHooks});if(!i.success)return{success:!1,error:`Hook failed: ${i.failed}`};let a=o.description,c="",u=0;if(o.startedAt){let f=new Date(o.startedAt);c=U.calculateDuration(f),u=Math.round((Date.now()-f.getTime())/6e4)}let p=o.estimatedMinutes,m=o.estimatedPoints;try{await We.record(s,{sessionId:o.sessionId,command:"done",task:a,startedAt:o.startedAt,completedAt:U.getTimestamp(),estimatedDuration:p?Qg(p):"0m",actualDuration:c||"0m",variance:p?VC(u-p):"+0m",completedAsPlanned:!0,qualityScore:3,tags:[o.linearId].filter(Boolean)})}catch{}let d="";if(m&&p){let f=u-p,k=p>0?Math.round((u-p)/p*100):0,v=f>=0?"+":"";d=` | est: ${m}pt (${Qg(p)}) \u2192 ${v}${k}%`}await X.completeTask(s,t.feedback);let g=o.linearId;if(g)try{let f=await xi(s),k=await Hl(s);k&&f.linear?.teamId?(await dt.initializeFromApiKey(k,f.linear.teamId),await dt.markDone(g),h.done(`${a}${c?` (${c}${d})`:""} \u2192 Linear \u2713`)):h.done(`${a}${c?` (${c}${d})`:""}`)}catch{h.done(`${a}${c?` (${c}${d})`:""}`)}else h.done(`${a}${c?` (${c}${d})`:""}`);return rr("completed"),nt("done"),await this.logToMemory(e,"task_completed",{task:a,duration:c,estimatedPoints:m,estimatedMinutes:p,actualMinutes:u,timestamp:U.getTimestamp()}),await mn(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()){try{let t=await this.ensureProjectInit(e);if(!t.success)return t;let n=await R.getProjectId(e);if(!n)return h.failWithHint("NO_PROJECT_ID"),{success:!1,error:"No project ID found"};let s=await Oe.getActiveTasks(n);return s.length===0?(h.warn("queue empty"),{success:!0,message:"Queue is empty"}):(h.done(`${s.length} task${s.length!==1?"s":""} queued`),nt("next"),{success:!0,tasks:s,count:s.length})}catch(t){return h.fail(y(t)),{success:!1,error:y(t)}}}async pause(e="",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 X.getCurrentTask(s);if(!o)return h.warn("no active task to pause"),{success:!1,message:"No active task to pause"};await X.pauseTask(s,e);let i=o.description.slice(0,40);return h.done(`paused: ${i}${e?` (${e})`:""}`),rr("paused"),nt("pause"),await this.logToMemory(t,"task_paused",{task:o.description,reason:e,timestamp:U.getTimestamp()}),{success:!0,task:o.description,reason:e}}catch(n){return h.fail(y(n)),{success:!1,error:y(n)}}}async resume(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"};let o=await X.getCurrentTask(s);if(o)return h.warn("already working on a task"),{success:!1,message:`Already working on: ${o.description}`};let i=await X.resumeTask(s);return i?(h.done(`resumed: ${i.description.slice(0,40)}`),rr("working"),nt("resume"),await this.logToMemory(t,"task_resumed",{task:i.description,timestamp:U.getTimestamp()}),{success:!0,task:i.description}):(h.warn("no paused task to resume"),{success:!1,message:"No paused task found"})}catch(n){return h.fail(y(n)),{success:!1,error:y(n)}}}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 _l(s);return console.log(Jg(o)),{success:!0,preferences:o}}return{success:!0,projectId:s,input:e,setWorkflowPreference:l(async o=>{await Gg(s,{...o,createdAt:U.getTimestamp()})},"setWorkflowPreference"),removeWorkflowPreference:l(async(o,i)=>{await zg(s,o,i)},"removeWorkflowPreference"),listWorkflowPreferences:l(async()=>_l(s),"listWorkflowPreferences")}}catch(n){return h.fail(y(n)),{success:!1,error:y(n)}}}};function Qg(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(Qg,"formatMinutesToDuration");function VC(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(VC,"formatVariance");var Hn=class{static{l(this,"PrjctCommands")}workflow;planning;shipping;analytics;performanceCmds;maintenance;analysis;setupCmds;velocityCmds;contextCmds;agent;agentInfo;currentAuthor;prjctDir;constructor(){this.workflow=new Is,this.planning=new _n,this.shipping=new xs,this.analytics=new Ss,this.performanceCmds=new Ps,this.maintenance=new bs,this.analysis=new Ln,this.setupCmds=new Cs,this.velocityCmds=new Ts,this.contextCmds=new Un,this.agent=null,this.agentInfo=null,this.currentAuthor=null,this.prjctDir=".prjct"}async done(e=process.cwd()){return this.workflow.done(e)}async next(e=process.cwd()){return this.workflow.next(e)}async pause(e="",t=process.cwd()){return this.workflow.pause(e,t)}async resume(e=null,t=process.cwd()){return this.workflow.resume(e,t)}async workflowPrefs(e=null,t=process.cwd()){return this.workflow.workflow(e,t)}async init(e=null,t=process.cwd()){return this.planning.init(e,t)}async bug(e,t=process.cwd()){return this.planning.bug(e,t)}async idea(e,t=process.cwd()){return this.planning.idea(e,t)}async spec(e=null,t=process.cwd()){return this.planning.spec(e,t)}async ship(e,t=process.cwd()){return this.shipping.ship(e,t)}async dash(e="default",t=process.cwd()){return this.analytics.dash(e,t)}async help(e="",t=process.cwd()){return this.analytics.help(e,t)}async perf(e="7",t=process.cwd()){return this.performanceCmds.perf(e,t)}async velocity(e="0",t=process.cwd()){return this.velocityCmds.velocity(e,t)}async cleanup(e={},t=process.cwd()){return this.maintenance.cleanup(e,t)}async design(e=null,t={},n=process.cwd()){return this.maintenance.design(e,t,n)}async recover(e=process.cwd()){return this.maintenance.recover(e)}async undo(e=process.cwd()){return this.maintenance.undo(e)}async redo(e=process.cwd()){return this.maintenance.redo(e)}async history(e=process.cwd()){return this.maintenance.history(e)}async analyze(e={},t=process.cwd()){return this.analysis.analyze(e,t)}async sync(e=process.cwd(),t={}){return this.analysis.sync(e,t)}async stats(e=process.cwd(),t={}){return this.analysis.stats(e,t)}async status(e=process.cwd(),t={}){return this.analysis.status(e,t)}async seal(e=process.cwd(),t={}){return this.analysis.seal(e,t)}async verify(e=process.cwd(),t={}){return this.analysis.verify(e,t)}async context(e=null,t=process.cwd()){return this.contextCmds.context(e,t)}async start(){return this.setupCmds.start()}async setup(e={}){return this.setupCmds.setup(e)}async installStatusLine(){return this.setupCmds.installStatusLine()}showAsciiArt(){this.setupCmds.showAsciiArt()}async initializeAgent(){return this.workflow.initializeAgent()}async ensureProjectInit(e){return this.workflow.ensureProjectInit(e)}async ensureAuthor(){return this.workflow.ensureAuthor()}async getGlobalProjectPath(e){return this.workflow.getGlobalProjectPath(e)}async logToMemory(e,t,n){return this.workflow.logToMemory(e,t,n)}},yG=new Hn;ei();var Zg={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}},ef=[{name:"init",group:"core",description:"Deep project analysis and initialization",usage:{claude:'/p:init "[idea]"',terminal:'prjct init "[idea]"'},params:"[idea]",implemented:!0,hasTemplate:!0,requiresProject:!1,features:["Architect mode for blank projects","Auto tech stack recommendation","Analyzes existing codebases"]},{name:"idea",group:"core",description:"Transform ideas into complete technical architectures",usage:{claude:'/p:idea "build a CRM"',terminal:'prjct idea "build a CRM"'},params:"<description>",implemented:!0,hasTemplate:!0,requiresProject:!0,features:["Simple ideas -> Quick capture","Complex ideas -> Full architecture"]},{name:"task",group:"core",description:"Start task with agentic classification and 7-phase workflow",usage:{claude:'/p:task "<description>"',terminal:'prjct task "<description>"'},params:"<description>",implemented:!0,hasTemplate:!0,requiresProject:!0,features:["Agentic type classification","7-phase workflow","Git branch management","Task breakdown"]},{name:"spec",group:"core",description:"Create detailed specifications for complex features",usage:{claude:'/p:spec "Dark Mode"',terminal:'prjct spec "Dark Mode"'},params:"[feature]",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"pause",group:"core",description:"Pause active task to handle interruption",usage:{claude:'/p:pause ["reason"]',terminal:'prjct pause ["reason"]'},params:"[reason]",implemented:!0,hasTemplate:!0,requiresProject:!0,blockingRules:{check:"Active task exists",message:"No active task to pause"}},{name:"resume",group:"core",description:"Resume paused task or recover abandoned session",usage:{claude:"/p:resume",terminal:"prjct resume"},params:"[task_id]",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"next",group:"core",description:"Show priority queue or roadmap view",usage:{claude:"/p:next",terminal:"prjct next"},params:"[roadmap]",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"done",group:"core",description:"Mark current task as complete",usage:{claude:"/p:done",terminal:"prjct done"},implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"ship",group:"core",description:"Commit, push, and celebrate shipped feature",usage:{claude:'/p:ship "feature"',terminal:'prjct ship "feature"'},params:"<feature>",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"bug",group:"core",description:"Report and track bugs with priority",usage:{claude:'/p:bug "description"',terminal:'prjct bug "description"'},params:"<description>",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"dash",group:"core",description:"Unified dashboard - status, progress, and roadmap",usage:{claude:"/p:dash [view]",terminal:"prjct dash [view]"},params:"[week|month|roadmap|compact]",implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"stats",group:"core",description:"Value dashboard - token savings, performance, and impact",usage:{claude:"/p:stats",terminal:"prjct stats"},params:"[--json] [--export]",implemented:!0,hasTemplate:!0,requiresProject:!0,features:["Token savings tracking","Compression metrics","Cost estimates","30-day trends"]},{name:"sync",group:"core",description:"Sync project state and update workflow agents",usage:{claude:"/p:sync",terminal:"prjct sync [--package=<name>] [--full]"},implemented:!0,hasTemplate:!0,requiresProject:!0,features:["Incremental sync: only re-analyzes changed files (default)","Force full sync: --full bypasses incremental cache","Monorepo support: --package=<name> for single package sync","Nested PRJCT.md inheritance","Per-package CLAUDE.md generation"]},{name:"perf",group:"core",description:"Performance dashboard - startup, memory, context, and handoff metrics",usage:{claude:"/p:perf",terminal:"prjct perf [days]"},params:"[days]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["Startup time tracking","Memory usage snapshots","Context correctness rate","Subtask handoff rate","Command duration breakdown"]},{name:"velocity",group:"core",description:"Sprint-based velocity dashboard with trend detection and projections",usage:{claude:"/p:velocity",terminal:"prjct velocity [backlogPoints]"},params:"[backlogPoints]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["Sprint-by-sprint velocity breakdown","Trend detection (improving/stable/declining)","Estimation accuracy tracking","Over/under estimation pattern detection","Completion projections for backlog"]},{name:"suggest",group:"core",description:"Smart recommendations based on project state",usage:{claude:"/p:suggest",terminal:"prjct suggest"},implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"status",group:"core",description:"Check if CLAUDE.md context is stale and needs resync",usage:{claude:"/p:status",terminal:"prjct status"},params:"[--json]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["Compares current HEAD with last sync commit","Counts commits and days since sync","Detects significant file changes","Configurable staleness thresholds"]},{name:"seal",group:"core",description:"Seal the current draft analysis with a commit-hash signature",usage:{claude:"/p:seal",terminal:"prjct seal"},params:"[--json]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["Locks draft analysis with SHA-256 signature","Only sealed analysis feeds task context","Detects staleness when HEAD moves past sealed commit"]},{name:"verify",group:"core",description:"Verify integrity of sealed analysis",usage:{claude:"/p:verify",terminal:"prjct verify"},params:"[--json]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["Recomputes SHA-256 signature and compares","Detects if sealed analysis was modified"]},{name:"help",group:"core",description:"Contextual help and guidance",usage:{claude:"/p:help [topic]",terminal:"prjct help [topic]"},params:"[topic]",implemented:!0,hasTemplate:!0,requiresProject:!1},{name:"design",group:"optional",description:"Design system architecture, APIs, and components",usage:{claude:"/p:design [target]",terminal:"prjct design [target]"},params:"[target] --type architecture|api|component",implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"cleanup",group:"optional",description:"Clean up temp files and old entries",usage:{claude:"/p:cleanup",terminal:"prjct cleanup"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"analyze",group:"optional",description:"Analyze repository and sync tasks",usage:{claude:"/p:analyze",terminal:"prjct analyze"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"undo",group:"optional",description:"Revert to previous snapshot",usage:{claude:"/p:undo",terminal:"prjct undo"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0,features:["Git-based snapshots","Preserves redo history"]},{name:"redo",group:"optional",description:"Redo previously undone changes",usage:{claude:"/p:redo",terminal:"prjct redo"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"history",group:"optional",description:"View snapshot history",usage:{claude:"/p:history",terminal:"prjct history"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"recover",group:"optional",description:"Recover abandoned session with context",usage:{claude:"/p:recover",terminal:"prjct recover"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"git",group:"optional",description:"Smart git operations with context",usage:{claude:"/p:git [op]",terminal:"prjct git [op]"},params:"[operation]",implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"test",group:"optional",description:"Run tests with auto-fix",usage:{claude:"/p:test",terminal:"prjct test"},implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0},{name:"workflow",group:"optional",description:"Configure workflow hooks via natural language",usage:{claude:'/p:workflow ["config"]',terminal:'prjct workflow ["config"]'},params:'["natural language config"]',implemented:!0,hasTemplate:!0,requiresProject:!0,isOptional:!0,features:["Natural language configuration","Before/after hooks for task, done, ship, sync","Permanent, session, or one-time preferences"]},{name:"start",group:"setup",description:"First-time setup (install commands to editors)",usage:{claude:null,terminal:"prjct start"},implemented:!0,hasTemplate:!1,requiresProject:!1},{name:"setup",group:"setup",description:"Reconfigure editor installations",usage:{claude:"/p:setup",terminal:"prjct setup"},params:"[--force] [--editor <name>]",implemented:!0,hasTemplate:!0,requiresProject:!1},{name:"migrate",group:"setup",description:"Migrate project to UUID format + sync",usage:{claude:"/p:migrate",terminal:null},implemented:!0,hasTemplate:!0,requiresProject:!0},{name:"auth",group:"setup",description:"Manage cloud authentication",usage:{claude:"/p:auth [action]",terminal:"prjct auth [action]"},params:"[login|logout|status]",implemented:!0,hasTemplate:!0,requiresProject:!1},{name:"context",group:"setup",description:"Smart context filtering tools for AI agents",usage:{claude:null,terminal:"prjct context <tool> [args]"},params:"<tool> [args]",implemented:!0,hasTemplate:!1,requiresProject:!0,features:["files - Find relevant files for a task","signatures - Extract code structure (~90% compression)","imports - Analyze dependency graphs","recent - Find hot files from git history","summary - Intelligent file summarization"]},{name:"uninstall",group:"setup",description:"Complete system removal of prjct",usage:{claude:null,terminal:"prjct uninstall"},params:"[--force] [--backup] [--dry-run]",implemented:!0,hasTemplate:!1,requiresProject:!1,features:["Removes ~/.prjct-cli/ data","Cleans CLAUDE.md prjct section","Uninstalls Homebrew/npm packages","Backup option before deletion"]}];Zo();En();K();M();Ee();He();import{execSync as Ti}from"node:child_process";import Ke from"node:fs/promises";import qC from"node:os";import Qt from"node:path";import KC from"node:readline";import ae from"chalk";var Ei="<!-- prjct:start - DO NOT REMOVE THIS MARKER -->",Cr="<!-- prjct:end - DO NOT REMOVE THIS MARKER -->";async function Gl(r){let e=0;try{let t=await Ke.readdir(r,{withFileTypes:!0});for(let n of t){let s=Qt.join(r,n.name);if(n.isDirectory())e+=await Gl(s);else try{let o=await Ke.stat(s);e+=o.size}catch{}}}catch{}return e}l(Gl,"getDirectorySize");function tf(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(tf,"formatSize");async function XC(r){try{return(await Ke.readdir(r,{withFileTypes:!0})).filter(t=>t.isDirectory()).length}catch{return 0}}l(XC,"countDirectoryItems");function YC(){let r={homebrew:!1,npm:!1};try{Ti("brew list prjct-cli 2>/dev/null",{encoding:"utf-8"})&&(r.homebrew=!0,r.homebrewFormula="prjct-cli")}catch{}try{Ti("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 QC(){let r=[],e=Ip(),t=P.getGlobalBasePath(),n=await D(t),s=n?await XC(Qt.join(t,"projects")):0,o=n?await Gl(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=Qt.join(e.claude.config,"CLAUDE.md"),a=await D(i),c=!1;if(a)try{let Ge=await Ke.readFile(i,"utf-8");c=Ge.includes(Ei)&&Ge.includes(Cr)}catch{}r.push({path:i,type:"section",description:"prjct section in CLAUDE.md",exists:a&&c});let u=e.claude.commands,p=await D(u),m=p?await Gl(u):0;r.push({path:u,type:"directory",description:"Claude commands",size:m,exists:p});let d=e.claude.router,g=await D(d);r.push({path:d,type:"file",description:"Claude router",exists:g});let f=Qt.join(e.claude.config,"prjct-statusline.sh"),k=await D(f);r.push({path:f,type:"file",description:"Status line script",exists:k});let v=e.gemini.router,x=await D(v);r.push({path:v,type:"file",description:"Gemini router",exists:x});let $=Qt.join(e.gemini.config,"GEMINI.md"),J=await D($),Pe=!1;if(J)try{let Ge=await Ke.readFile($,"utf-8");Pe=Ge.includes(Ei)&&Ge.includes(Cr)}catch{}return J&&Pe&&r.push({path:$,type:"section",description:"prjct section in GEMINI.md",exists:!0}),r}l(QC,"gatherUninstallItems");async function ZC(r){try{let e=await Ke.readFile(r,"utf-8");if(!e.includes(Ei)||!e.includes(Cr))return!1;let t=e.indexOf(Ei),n=e.indexOf(Cr)+Cr.length,s=e.substring(0,t)+e.substring(n);return s=s.replace(/\n{3,}/g,`
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
`,"utf-8"),!0}catch(t){return H.error(`JSON write error: ${y(t)}`),!1}}l(dv,"writeJsonFile");function mv(r){return P.getGlobalProjectPath(r)}l(mv,"getProjectDataPath");function cf(r,e){let t=new pv,n=mv(r);return t.get("/state",async s=>{let o=await Ut(rt.join(n,It.state));return o?s.json(o):s.json({currentTask:null,lastUpdated:""})}),t.get("/queue",async s=>{let o=await Ut(rt.join(n,It.queue));return o?s.json(o):s.json({tasks:[],lastUpdated:""})}),t.get("/ideas",async s=>{let o=await Ut(rt.join(n,It.ideas));return o?s.json(o):s.json({ideas:[],lastUpdated:""})}),t.get("/roadmap",async s=>{let o=await Ut(rt.join(n,It.roadmap));return o?s.json(o):s.json({features:[],backlog:[],lastUpdated:""})}),t.get("/shipped",async s=>{let o=await Ut(rt.join(n,It.shipped));return o?s.json(o):s.json({items:[],lastUpdated:""})}),t.get("/dashboard",async s=>{let[o,i,a,c,u]=await Promise.all([Ut(rt.join(n,It.state)),Ut(rt.join(n,It.queue)),Ut(rt.join(n,It.ideas)),Ut(rt.join(n,It.roadmap)),Ut(rt.join(n,It.shipped))]);return s.json({projectId:r,state:o||{currentTask:null,lastUpdated:""},queue:i||{tasks:[],lastUpdated:""},ideas:a||{ideas:[],lastUpdated:""},roadmap:c||{features:[],backlog:[],lastUpdated:""},shipped:u||{items:[],lastUpdated:""},timestamp:new Date().toISOString()})}),t.post("/state",async s=>{try{let o=await s.req.json(),i=rt.join(n,It.state);return await dv(i,o)?s.json({success:!0}):s.json({success:!1,error:"Failed to write"},500)}catch(o){return s.json({success:!1,error:String(o)},400)}}),t.get("/context/:name",async s=>{let o=s.req.param("name");if(!["now","next","ideas","shipped"].includes(o))return s.json({error:"Invalid context file"},400);try{let a=rt.join(n,"context",`${o}.md`),c=await ji.readFile(a,"utf-8");return s.text(c,200,{"Content-Type":"text/markdown"})}catch(a){return S(a)||H.error(`Context read error: ${y(a)}`),s.text("",200,{"Content-Type":"text/markdown"})}}),t}l(cf,"createRoutes");K();M();import Zt from"node:fs/promises";import ce from"node:path";import{Hono as gv}from"hono";import*as lf from"jsonc-parser";var fv=P.getGlobalBasePath(),Gn=ce.join(fv,"projects");async function ye(r){try{let e=await Zt.readFile(r,"utf-8"),t=[],n=lf.parse(e,t);return t.length>0?null:n}catch(e){if(S(e))return null;throw e}}l(ye,"readJsonFile");async function xr(r,e){try{return await Zt.mkdir(ce.dirname(r),{recursive:!0}),await Zt.writeFile(r,`${JSON.stringify(e,null,2)}
|
|
1426
|
-
`,"utf-8"),!0}catch(t){if(S(t))return!1;throw t}}l(xr,"writeJsonFile");function Ht(r){return ce.join(Gn,r)}l(Ht,"getProjectPath");async function Di(r){let e=ce.join(Ht(r),"project.json");return await ye(e)}l(Di,"getProjectConfig");async function Jl(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(Jl,"calculateDuration");function uf(){let r=new gv;return r.get("/projects",async e=>{try{await Zt.mkdir(Gn,{recursive:!0});let n=(await Zt.readdir(Gn,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name),s=await Promise.all(n.map(async o=>{let i=Ht(o),a=await Di(o),c=await ye(ce.join(i,"storage/state.json")),u=await ye(ce.join(i,"storage/queue.json")),p=await ye(ce.join(i,"storage/ideas.json")),m=await ye(ce.join(i,"storage/shipped.json")),d=c?.currentTask,g=await Jl(d?.startedAt);return{id:o,name:a?.name||o.slice(0,8),path:a?.path||null,currentTask:d?{...d,duration:g}:null,pausedTask:c?.previousTask||null,stats:{queueCount:u?.tasks?.filter(f=>!f.completed)?.length||0,ideasCount:p?.ideas?.filter(f=>f.status==="pending")?.length||0,shippedCount:m?.shipped?.length||0}}}));return s.sort((o,i)=>o.currentTask&&!i.currentTask?-1:!o.currentTask&&i.currentTask?1:(o.name||"").localeCompare(i.name||"")),e.json({projects:s})}catch(t){return e.json({projects:[],error:String(t)},500)}}),r.get("/projects/:id/full",async e=>{let t=e.req.param("id"),n=Ht(t);try{let[s,o,i,a,c,u]=await Promise.all([Di(t),ye(ce.join(n,"storage/state.json")),ye(ce.join(n,"storage/queue.json")),ye(ce.join(n,"storage/ideas.json")),ye(ce.join(n,"storage/shipped.json")),ye(ce.join(n,"planning/roadmap.json"))]);o?.currentTask?.startedAt&&(o.currentTask.duration=await Jl(o.currentTask.startedAt));let p=new Date,m=new Date(p.getFullYear(),p.getMonth(),p.getDate()),d=new Date(m);d.setDate(d.getDate()-d.getDay());let g=i?.tasks?.filter(k=>!k.completed||!k.completedAt?!1:new Date(k.completedAt)>=m)?.length||0,f=i?.tasks?.filter(k=>!k.completed||!k.completedAt?!1:new Date(k.completedAt)>=d)?.length||0;return e.json({id:t,name:s?.name||t,path:s?.path,state:o||{currentTask:null,previousTask:null,lastUpdated:""},queue:i||{tasks:[],lastUpdated:""},ideas:a||{ideas:[],lastUpdated:""},shipped:c||{shipped:[],lastUpdated:""},roadmap:u||{features:[],backlog:[],lastUpdated:""},stats:{tasksToday:g,tasksThisWeek:f,queueCount:i?.tasks?.filter(k=>!k.completed)?.length||0,ideasCount:a?.ideas?.filter(k=>k.status==="pending")?.length||0,shippedCount:c?.shipped?.length||0},timestamp:new Date().toISOString()})}catch(s){return e.json({error:String(s)},500)}}),r.post("/projects/:id/task/complete",async e=>{let t=e.req.param("id"),n=Ht(t),s=ce.join(n,"storage/state.json");try{let o=await ye(s);if(!o?.currentTask)return e.json({success:!1,error:"No active task"},400);let i=o.currentTask,a={currentTask:null,previousTask:null,lastUpdated:new Date().toISOString()};return await xr(s,a),e.json({success:!0,completedTask:i,message:`Completed: ${i.description}`})}catch(o){return e.json({success:!1,error:String(o)},500)}}),r.post("/projects/:id/task/pause",async e=>{let t=e.req.param("id"),n=Ht(t),s=ce.join(n,"storage/state.json");try{let i=(await e.req.json().catch(()=>({}))).reason,a=await ye(s);if(!a?.currentTask)return e.json({success:!1,error:"No active task"},400);let c={id:a.currentTask.id,description:a.currentTask.description,status:"paused",startedAt:a.currentTask.startedAt,pausedAt:new Date().toISOString(),pauseReason:i},u={currentTask:null,previousTask:c,lastUpdated:new Date().toISOString()};return await xr(s,u),e.json({success:!0,pausedTask:c,message:`Paused: ${c.description}`})}catch(o){return e.json({success:!1,error:String(o)},500)}}),r.post("/projects/:id/task/resume",async e=>{let t=e.req.param("id"),n=Ht(t),s=ce.join(n,"storage/state.json");try{let o=await ye(s);if(!o?.previousTask)return e.json({success:!1,error:"No paused task"},400);let i={id:o.previousTask.id,description:o.previousTask.description,status:"active",startedAt:new Date().toISOString(),sessionId:`sess_${Date.now().toString(36)}`},a={currentTask:i,previousTask:null,lastUpdated:new Date().toISOString()};return await xr(s,a),e.json({success:!0,resumedTask:i,message:`Resumed: ${i.description}`})}catch(o){return e.json({success:!1,error:String(o)},500)}}),r.post("/projects/:id/queue/start",async e=>{let t=e.req.param("id"),n=Ht(t),s=ce.join(n,"storage/state.json"),o=ce.join(n,"storage/queue.json");try{let i=await e.req.json(),{taskId:a}=i;if(!a)return e.json({success:!1,error:"taskId required"},400);let c=await ye(s),u=await ye(o);if(c?.currentTask)return e.json({success:!1,error:"Complete or pause current task first"},400);let p=u?.tasks?.find(g=>g.id===a);if(!p)return e.json({success:!1,error:"Task not found in queue"},404);let m={id:p.id,description:p.description,status:"active",startedAt:new Date().toISOString(),sessionId:`sess_${Date.now().toString(36)}`,featureId:p.featureId},d={currentTask:m,previousTask:null,lastUpdated:new Date().toISOString()};return await xr(s,d),e.json({success:!0,task:m,message:`Started: ${m.description}`})}catch(i){return e.json({success:!1,error:String(i)},500)}}),r.post("/projects/:id/ideas",async e=>{let t=e.req.param("id"),n=Ht(t),s=ce.join(n,"storage/ideas.json");try{let o=await e.req.json(),{text:i,priority:a="medium",tags:c=[]}=o;if(!i)return e.json({success:!1,error:"text required"},400);let u=await ye(s)||{ideas:[],lastUpdated:""},p={id:`idea_${Date.now().toString(36)}`,text:i,status:"pending",priority:a||"medium",tags:c,addedAt:new Date().toISOString()};return u.ideas.unshift(p),u.lastUpdated=new Date().toISOString(),await xr(s,u),e.json({success:!0,idea:p,message:`Captured: ${i.slice(0,50)}...`})}catch(o){return e.json({success:!1,error:String(o)},500)}}),r.get("/stats/global",async e=>{try{await Zt.mkdir(Gn,{recursive:!0});let n=(await Zt.readdir(Gn,{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=Ht(c),p=await ye(ce.join(u,"storage/state.json")),m=await ye(ce.join(u,"storage/queue.json")),d=await ye(ce.join(u,"storage/ideas.json")),g=await ye(ce.join(u,"storage/shipped.json"));p?.currentTask&&a++,s+=m?.tasks?.filter(f=>!f.completed)?.length||0,o+=d?.ideas?.filter(f=>f.status==="pending")?.length||0,i+=g?.shipped?.length||0}return e.json({totalProjects:n.length,activeProjects:a,totalTasks:s,totalIdeas:o,totalShipped:i,timestamp:new Date().toISOString()})}catch(t){return e.json({error:String(t)},500)}}),r.get("/status-bar/compact",async e=>{try{let t=e.req.query("cwd");await Zt.mkdir(Gn,{recursive:!0});let s=(await Zt.readdir(Gn,{withFileTypes:!0})).filter(p=>p.isDirectory()).map(p=>p.name),o=null;if(t)for(let p of s){let m=await Di(p),d=m?.repoPath||m?.path;if(d&&t.startsWith(d)){o=p;break}}let i=null,a=null,c=null,u=o?[o]:s;for(let p of u){let m=Ht(p),d=await ye(ce.join(m,"storage/state.json")),g=await Di(p);if(d?.currentTask){i={id:p,name:g?.name||p,path:g?.repoPath||g?.path},a={...d.currentTask,duration:await Jl(d.currentTask.startedAt)};break}d?.previousTask&&!c&&(i={id:p,name:g?.name||p,path:g?.repoPath||g?.path},c=d.previousTask)}return e.json({hasActiveTask:!!a,hasPausedTask:!!c,activeProject:i,activeTask:a,pausedTask:c,totalProjects:s.length,filtered:!!o,cwd:t||null,timestamp:new Date().toISOString()})}catch(t){return e.json({error:String(t)},500)}}),r}l(uf,"createExtendedRoutes");Mi();import{streamSSE as hv}from"hono/streaming";var pf=3600*1e3,yv=300*1e3,wv=3e4;function df(){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()>pf&&t(i)},yv),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 hv(o,async i=>{let a=crypto.randomUUID(),c=new Date().toISOString(),u=new AbortController,p={id:a,connectedAt:c,send:l((g,f)=>{i.writeSSE({event:g,data:JSON.stringify(f)})},"send"),close:l(()=>{t(a)},"close")},m=setInterval(async()=>{try{await i.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})})}catch{t(a)}},wv),d=setTimeout(()=>{t(a)},pf);typeof m=="object"&&"unref"in m&&m.unref(),typeof d=="object"&&"unref"in d&&d.unref(),r.set(a,{client:p,heartbeatInterval:m,ttlTimeout:d,abortController:u}),await i.writeSSE({event:"connected",data:JSON.stringify({clientId:a,timestamp:c,message:"Connected to prjct-cli server"})}),i.onAbort(()=>{t(a)}),await new Promise(g=>{u.signal.addEventListener("abort",()=>g(),{once:!0})})})},broadcast(o,i){let a={event:o,data:i,timestamp:new Date().toISOString()};for(let[c,u]of r)try{u.client.send(o,a)}catch{t(c)}},getClientCount(){return r.size},shutdown(){s();for(let o of[...r.keys()])t(o)}}}l(df,"createSSEManager");function mf(r){let e=new Sv,t=df();r.enableCors!==!1&&e.use("*",kv({origin:"*",allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization"]})),r.enableLogging!==!1&&e.use("*",bv()),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=cf(r.projectId,r.projectPath);e.route("/api",n);let s=uf();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(zl())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: ${zl()?"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(mf,"createServer");var gf=3478;var Gt={runDir:l(()=>`${process.env.HOME||$i("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")},ff=1800*1e3;function Wl(r){return Buffer.from(`${JSON.stringify(r)}
|
|
1427
|
-
`)
|
|
1428
|
-
`))!==-1;){let s=e.slice(0,n);if(e=e.slice(n+1),!!s.trim())try{let o=JSON.parse(s),i=await vv(o);r.write(Wl(i))}catch(o){let i={id:"unknown",success:!1,exitCode:1,stderr:`Protocol error: ${o.message}`};r.write(Wl(i))}}}),r.on("error",()=>{})}l(Cv,"handleConnection");async function vv(r){if(!Te||!jt)return{id:r.id,success:!1,exitCode:1,stderr:"Daemon not initialized"};if(yf(),Te.commandsServed++,Te.lastActivity=Date.now(),r.command==="daemon")return Tv(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 xv(r);return{id:r.id,success:o.success,exitCode:o.success?0:1,stdout:e.join(`
|
|
1416
|
+
${i}`);await ne.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 Re.get("Bash")("git add .");let n=`feat: ${e}
|
|
1417
|
+
|
|
1418
|
+
Generated with [p/](https://www.prjct.app/)`;return await Re.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 Re.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)"}}}};it();re();Qr();F();Tn();We();import QP from"node:fs/promises";import ZP from"node:path";import Cs from"chalk";var vs=class extends le{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(Cs.dim(`[dry-run] Would update ${o.length} project(s)
|
|
1419
|
+
`));let i=0,a=0,c=0;for(let d of o){let m=`${d.slice(0,8)}...`;if(n){console.log(` ${Cs.dim("would update")} ${m}`);continue}try{let p=await Bs(d),g=await Xr(d),f=p.migratedFiles.length;if(i+=f,a+=g,f>0||g>0?console.log(` ${Cs.green("\u2713")} ${m}: migrated ${f} files, swept ${g} leftovers`):console.log(` ${Cs.green("\u2713")} ${m}: already up to date`),p.errors.length>0){for(let S of p.errors)console.log(` ${Cs.yellow("\u26A0")} ${S.file}: ${S.error}`);c+=p.errors.length}}catch(p){console.log(` ${Cs.red("\u2717")} ${m}: ${w(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(w(o)),{success:!1,error:w(o)}}}async getCurrentProjectId(e){let t=await R.getProjectId(e);return t?[t]:[]}async getAllProjectIds(){let e=ZP.join(T.getGlobalBasePath(),"projects");try{return(await QP.readdir(e,{withFileTypes:!0})).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name)}catch{return[]}}};pc();Yn();ha();F();An();We();import he from"chalk";var xs=class extends le{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 Xe.getAll(s);if(i.length===0)return console.log(`
|
|
1420
|
+
${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=Fo(i,o);await fa.saveMetrics(s,a),console.log(`
|
|
1422
|
+
${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=ip(d,a.averageVelocity,o),p=m.estimatedDate?new Date(m.estimatedDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"unknown";console.log(`
|
|
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 tt.unlink(r):await tt.writeFile(r,`${s}
|
|
1427
|
+
`,"utf-8"),!0}catch{return!1}}l(SC,"removePrjctSection");async function kC(){let r=gC.homedir(),e=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19),t=Kt.join(r,`.prjct-backup-${e}`);try{await tt.mkdir(t,{recursive:!0});let n=T.getGlobalBasePath();return await $(n)&&await Ug(n,Kt.join(t,".prjct-cli")),t}catch{return null}}l(kC,"createBackup");async function Ug(r,e){await tt.mkdir(e,{recursive:!0});let t=await tt.readdir(r,{withFileTypes:!0});for(let n of t){let s=Kt.join(r,n.name),o=Kt.join(e,n.name);n.isDirectory()?await Ug(s,o):await tt.copyFile(s,o)}}l(Ug,"copyDirectory");async function bC(r,e,t){let n=[],s=[];for(let o of r)if(o.exists)try{o.type==="section"?await SC(o.path)&&n.push(o.path):o.type==="directory"?(await tt.rm(o.path,{recursive:!0,force:!0}),n.push(o.path)):o.type==="file"&&(await tt.unlink(o.path),n.push(o.path))}catch(i){s.push(`${o.path}: ${w(i)}`)}if(!t.keepPackage){if(e.homebrew&&e.homebrewFormula)try{t.dryRun||Si(`brew uninstall ${e.homebrewFormula}`,{stdio:"pipe"}),n.push("Homebrew: prjct-cli")}catch(o){s.push(`Homebrew: ${w(o)}`)}if(e.npm)try{t.dryRun||Si("npm uninstall -g prjct-cli",{stdio:"pipe"}),n.push("npm: prjct-cli")}catch(o){s.push(`npm: ${w(o)}`)}}return{deleted:n,errors:s}}l(bC,"performUninstall");async function PC(r){let e=fC.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.toLowerCase()==="uninstall")})})}l(PC,"promptConfirmation");async function CC(r={},e=process.cwd()){let t=await wC(),n=yC(),s=t.filter(c=>c.exists);if(s.length===0&&!n.homebrew&&!n.npm)return console.log(ue.yellow(`
|
|
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(ue.red.bold(" WARNING: This action is DANGEROUS and IRREVERSIBLE")),console.log(""),console.log(ue.white("The following will be permanently deleted:")),console.log("");for(let c of s){let u=T.getDisplayPath(c.path),d="";c.type==="section"?d=ue.dim("(section only)"):c.size&&(d=ue.dim(`(${Lg(c.size)})`)),console.log(` ${ue.cyan(u.padEnd(35))} ${d}`),console.log(` ${ue.dim(c.description)}`),console.log("")}if(n.homebrew&&(console.log(` ${ue.cyan("Homebrew".padEnd(35))} ${ue.dim("prjct-cli formula")}`),console.log("")),n.npm&&(console.log(` ${ue.cyan("npm global".padEnd(35))} ${ue.dim("prjct-cli package")}`),console.log("")),o>0&&(console.log(ue.dim(` Total size: ${Lg(o)}`)),console.log("")),r.dryRun)return console.log(ue.yellow("Dry run - no changes made")),{success:!0,message:"Dry run complete",itemsFound:s.length};if(r.backup){console.log(ue.blue("Creating backup..."));let c=await kC();c?(console.log(ue.green(`Backup created: ${T.getDisplayPath(c)}`)),console.log("")):console.log(ue.yellow("Failed to create backup, continuing..."))}if(!r.force&&(console.log(ue.yellow('Type "uninstall" to confirm:')),!await PC("> ")))return console.log(ue.yellow(`
|
|
1429
|
+
Uninstall cancelled.`)),{success:!1,message:"Uninstall cancelled by user"};console.log(""),console.log(ue.blue("Removing prjct..."));let{deleted:i,errors:a}=await bC(t,n,r);if(console.log(""),i.length>0&&console.log(ue.green(`Removed ${i.length} items`)),a.length>0){console.log(ue.yellow(`
|
|
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(Dl,"encodeMessage");var Ms=null,Pr=null,ve=null,Ie=null;async function Xg(r){let e=Gt.socket(),t=Gt.pid(),n=Gt.runDir();if(ft.mkdirSync(n,{recursive:!0}),ft.existsSync(t)){let s=parseInt(ft.readFileSync(t,"utf-8").trim(),10);YC(s)&&(console.error(`Daemon already running (PID ${s})`),process.exit(1)),ft.unlinkSync(t)}if(ft.existsSync(e)&&ft.unlinkSync(e),Ie={startedAt:Date.now(),commandsServed:0,lastActivity:Date.now(),idleTimeoutMs:Yg,idleTimer:null},ve=new Nn,Ms=BC(s=>VC(s)),Ms.listen(e,()=>{ft.chmodSync(e,384),ft.writeFileSync(t,String(process.pid)),console.log(`prjct daemon started (PID ${process.pid})`),console.log(` Socket: ${e}`),Qg()}),Ms.on("error",s=>{console.error("Daemon socket error:",s.message),Cr(1)}),!r.noHttp)try{let s=process.cwd(),o=await R.getProjectId(s);if(o){let i=r.port||Kg;Pr=qg({port:i,projectId:o,projectPath:s,enableLogging:!1}),await Pr.start()}}catch{}if(process.on("SIGTERM",()=>Cr(0)),process.on("SIGINT",()=>Cr(0)),process.on("SIGHUP",()=>{ve=new Nn,console.log("Daemon reloaded (SIGHUP)")}),!r.foreground)try{process.stdin?.unref?.()}catch{}}l(Xg,"startDaemon");function VC(r){let e="";r.on("data",async t=>{e+=t.toString();let n;for(;(n=e.indexOf(`
|
|
1432
|
+
`))!==-1;){let s=e.slice(0,n);if(e=e.slice(n+1),!!s.trim())try{let o=JSON.parse(s),i=await JC(o);r.write(Dl(i))}catch(o){let i={id:"unknown",success:!1,exitCode:1,stderr:`Protocol error: ${o.message}`};r.write(Dl(i))}}}),r.on("error",()=>{})}l(VC,"handleConnection");async function JC(r){if(!Ie||!ve)return{id:r.id,success:!1,exitCode:1,stderr:"Daemon not initialized"};if(Qg(),Ie.commandsServed++,Ie.lastActivity=Date.now(),r.command==="daemon")return KC(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 qC(r);return{id:r.id,success:o.success,exitCode:o.success?0:1,stdout:e.join(`
|
|
1429
1433
|
`)||o.message||void 0,stderr:t.join(`
|
|
1430
|
-
`)||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(
|
|
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(JC,"handleRequest");async function qC(r){let e=r.args.join(" ")||null,t=r.options,n=t.md===!0;switch(r.command){case"sync":return ve.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 ve.status(r.cwd,{json:t.json===!0,md:n});case"stats":return ve.stats(r.cwd,{json:t.json===!0,export:t.export===!0});case"seal":return ve.seal(r.cwd,{json:t.json===!0});case"verify":return ve.verify(r.cwd,{json:t.json===!0,semantic:t.semantic===!0});case"task":return ve.task(e,r.cwd,{md:n});case"done":return ve.done(r.cwd,{md:n});case"next":return ve.next(r.cwd,{md:n});case"pause":return ve.pause(e||"",r.cwd,{md:n});case"resume":return ve.resume(e,r.cwd,{md:n});case"bug":return ve.bug(e||"",r.cwd,{md:n});case"idea":return ve.idea(e||"",r.cwd,{md:n});case"ship":return ve.ship(e,r.cwd,{md:n});case"dash":return ve.dash(e||"default",r.cwd,{md:n});case"design":return ve.design(e||"",t);case"analyze":return ve.analyze(t);case"cleanup":return ve.cleanup(t);default:return U.execute(r.command,e,r.cwd)}}l(qC,"executeCommand");function KC(r){let e=r.args[0];if(e==="status")return{id:r.id,success:!0,exitCode:0,result:{running:!0,pid:process.pid,socketPath:Gt.socket(),uptime:Ie?Date.now()-Ie.startedAt:0,commandsServed:Ie?.commandsServed??0,lastActivity:Ie?new Date(Ie.lastActivity).toISOString():null,registeredCommands:U.list().length}};if(e==="stop"){let t={id:r.id,success:!0,exitCode:0,stdout:"Daemon stopping..."};return setTimeout(()=>Cr(0),100),t}return{id:r.id,success:!1,exitCode:1,stderr:`Unknown daemon command: ${e}. Use: status, stop`}}l(KC,"handleDaemonCommand");function Qg(){Ie&&(Ie.idleTimer&&clearTimeout(Ie.idleTimer),Ie.idleTimer=setTimeout(()=>{console.log(`Daemon idle for ${Ie.idleTimeoutMs/1e3/60} minutes, shutting down`),Cr(0)},Ie.idleTimeoutMs),Ie.idleTimer.unref&&Ie.idleTimer.unref())}l(Qg,"resetIdleTimer");function Cr(r){console.log("Daemon shutting down..."),Ie?.idleTimer&&clearTimeout(Ie.idleTimer),Pr&&(Pr.stop(),Pr=null),Ms&&(Ms.close(),Ms=null);let e=Gt.socket(),t=Gt.pid();try{ft.existsSync(e)&&ft.unlinkSync(e)}catch{}try{ft.existsSync(t)&&ft.unlinkSync(t)}catch{}process.exit(r)}l(Cr,"shutdown");function YC(r){try{return process.kill(r,0),!0}catch{return!1}}l(YC,"isProcessRunning");var jl=process.argv.slice(2),XC=parseInt(jl.find(r=>r.startsWith("--port="))?.split("=")[1]||"",10)||void 0,QC=jl.includes("--no-http"),ZC=jl.includes("--foreground");Xg({port:XC,noHttp:QC,foreground:ZC}).catch(r=>{console.error("Failed to start daemon:",r.message),process.exit(1)});
|