prjct-cli 1.38.0 → 1.38.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,12 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.38.2] - 2026-02-14
4
+
5
+ ### Bug Fixes
6
+
7
+ - replace unbounded any types in workflow-rule-storage (PRJ-339) (#188)
8
+
9
+
10
+ ## [1.38.1] - 2026-02-14
11
+
12
+ ### Bug Fixes
13
+
14
+ - auto-repair Codex router metadata during sync (#187)
15
+
16
+
17
+ ## [1.38.1] - 2026-02-14
18
+
19
+ ### Bug Fixes
20
+
21
+ - Auto-repair Codex router metadata during sync and doctor checks (#187)
22
+
3
23
  ## [1.38.0] - 2026-02-14
4
24
 
5
25
  ### Features
6
26
 
7
27
  - hybrid sync pipeline - CLI + LLM analysis (#186)
8
28
 
9
-
10
29
  ## [1.37.1] - 2026-02-14
11
30
 
12
31
  ### Bug Fixes
@@ -1164,7 +1164,7 @@ Domain specialist for ${r} tasks.
1164
1164
  You are the ${r} expert for this project. Apply best practices for the detected stack.
1165
1165
  `}function Ey(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:C(),skills:n.map(o=>({name:o.skill,linkedAgents:[o.agent]})),agentSkillMap:Object.fromEntries(n.map(o=>[o.agent,o.skill]))};return Wt.writeFile(Mt.join(t,"config","skills.json"),JSON.stringify(s,null,2),"utf-8").catch(o=>{G.debug("Failed to write skills.json",{error:se(o)})}),n}async function Ay(r){let e=[];try{let t=Mt.join(__dirname,"..","..","templates","config","skill-mappings.json"),n=await Wt.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=Mt.join(aA.homedir(),".claude","skills");for(let{pkg:c,agent:u}of i){let d=c.split("/").pop()||c,m=Mt.join(a,d,"SKILL.md"),p=Mt.join(a,`${d}.md`),g=!1;try{await Wt.access(m),g=!0}catch{try{await Wt.access(p),g=!0}catch{}}if(g){e.push({name:d,agent:u,status:"skipped"});continue}try{let f=c.split("/"),k;f.length===3?k=`${f[0]}/${f[1]}@${f[2]}`:k=c;let S=await Cy.install(k);S.installed.length>0?(e.push({name:d,agent:u,status:"installed"}),G.info(`Installed skill: ${d} for agent: ${u}`)):S.errors.length>0?(e.push({name:d,agent:u,status:"error"}),G.debug(`Failed to install skill ${d}`,{errors:S.errors})):e.push({name:d,agent:u,status:"skipped"})}catch(f){e.push({name:d,agent:u,status:"error"}),G.debug(`Skill install error for ${d}`,{error:se(f)})}}}catch(t){G.debug("Skill auto-installation failed (non-critical)",{error:se(t)})}return e}var Iy=y(()=>{"use strict";Zt();Pn();le();Gn();vy();l(xy,"generateAgents");l(Py,"loadExistingAgents");l(Ty,"resolveTemplateIncludes");l(cA,"generateWorkflowAgent");l(lA,"generateDomainAgent");l(uA,"injectFeedbackSection");l(dA,"generateMinimalWorkflowAgent");l(pA,"generateMinimalDomainAgent");l(Ey,"configureSkills");l(Ay,"autoInstallSkills")});import jy from"node:fs/promises";import Ry from"node:path";var Fa,Dy=y(()=>{"use strict";Fa=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=Ry.join(this.projectPath,"package.json"),t=await jy.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async fileExists(e){try{return await jy.access(Ry.join(this.projectPath,e)),!0}catch{return!1}}}});import{exec as mA}from"node:child_process";import $y from"node:fs/promises";import wd from"node:path";import{promisify as gA}from"node:util";async function My(r){let e={branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0};try{let{stdout:t}=await Is("git branch --show-current",{cwd:r});e.branch=t.trim()||"main";let{stdout:n}=await Is("git rev-list --count HEAD",{cwd:r});e.commits=parseInt(n.trim(),10)||0;let{stdout:s}=await Is("git shortlog -sn --all | wc -l",{cwd:r});e.contributors=parseInt(s.trim(),10)||0;let{stdout:o}=await Is("git status --porcelain",{cwd:r}),i=o.trim().split(`
1166
1166
  `).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 Is('git log --oneline -20 --pretty=format:"%h|%s|%ad" --date=short',{cwd:r});e.recentCommits=a.split(`
1167
- `).filter(Boolean).map(u=>{let[d,m,p]=u.split("|");return{hash:d,message:m,date:p}});let{stdout:c}=await Is('git log --oneline --since="1 week ago" | wc -l',{cwd:r});e.weeklyCommits=parseInt(c.trim(),10)||0}catch(t){G.debug("Git analysis failed (not a git repo?)",{error:se(t)})}return e}async function kn(r,e){try{return await $y.access(wd.join(r,e)),!0}catch(t){return G.debug("File not found",{filename:e,error:se(t)}),!1}}async function Oy(r){let e={fileCount:0,version:"0.0.0",name:wd.basename(r),ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]};try{let{stdout:t}=await Is('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){G.debug("File count failed",{path:r,error:se(t)}),e.fileCount=0}try{let t=wd.join(r,"package.json"),n=JSON.parse(await $y.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 kn(r,"tsconfig.json")?e.languages.push("TypeScript"):e.languages.push("JavaScript")}catch(t){G.debug("No package.json found",{path:r,error:se(t)})}return await kn(r,"Cargo.toml")&&(e.ecosystem="Rust",e.languages.push("Rust")),await kn(r,"go.mod")&&(e.ecosystem="Go",e.languages.push("Go")),(await kn(r,"requirements.txt")||await kn(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 Fy(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 kn(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 kn(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 kn(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 kn(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 kn(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 Ny(r,e){let t=As(),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 _y(r){return new Fa(r).detect()}var Is,Ly=y(()=>{"use strict";Pn();od();Gn();Dy();Is=gA(mA);l(My,"analyzeGit");l(kn,"fileExists");l(Oy,"gatherStats");l(Fy,"detectCommands");l(Ny,"buildSources");l(_y,"detectStack")});import{exec as fA}from"node:child_process";import kd from"node:fs/promises";import Na from"node:path";import{promisify as hA}from"node:util";var yA,Sd,bd,Hy,Uy=y(()=>{"use strict";nn();N();yA=hA(fA),Sd={async contextFilesExist(r){let e=Date.now(),t=["context/CLAUDE.md"],n=[];for(let s of t){let o=Na.join(r,s);try{await kd.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=Na.basename(r);try{await L.read(n)}catch(s){x(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=Na.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 kd.readdir(t);for(let i of o){if(!i.endsWith(".md"))continue;let a=await kd.readFile(Na.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(!x(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}}},bd=class{static{l(this,"SyncVerifier")}async verify(e,t,n){let s=Date.now(),o=[],i=n?.failFast??!1,a=0,c=[Sd.contextFilesExist(t),Sd.jsonFilesValid(t),Sd.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(k=>k.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 yA(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}}}},Hy=new bd});import _a from"node:fs/promises";import La from"node:path";var Ha,Sn,Ua=y(()=>{"use strict";er();Qu();Oh();_h();Gh();ed();Pn();Ke();Vn();tt();xe();pr();ho();Un();ue();Qr();yo();Zi();Zr();eo();Ks();uy();py();le();Gn();fu();hu();gs();fy();Ul();ql();Iy();Ly();Uy();Ha=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 i=await Oa(e),a=i.filter(u=>mr.includes(u)||u==="codex"),c=i.filter(u=>!mr.includes(u)&&u!=="codex");s=[...a.length>0?a:mr,...c],s=Array.from(new Set(s))}else t.aiTools[0]==="auto"?(s=await Oa(e),s.length===0&&(s=["claude"])):t.aiTools[0]==="all"?s=await sy("all",e):s=t.aiTools;let o={installed:!1,verified:!1,configPath:"",message:""};try{if(this.projectId=await $.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:[],context7:{installed:!1,verified:!1},error:"No prjct project. Run p. init first."};if((await ss()).installed){let _=await dr();if(!_.verified)return{success:!1,projectId:this.projectId,cliVersion:"",git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),agents:[],skills:[],skillsInstalled:[],contextFiles:[],aiTools:[],context7:{installed:!1,verified:!1},error:`Codex p. router is required but not ready: ${_.message||"verification failed"}. Run 'prjct start' or 'prjct setup' to repair.`}}try{o=await tn.ensureReady()}catch(_){return{success:!1,projectId:this.projectId,cliVersion:"",git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),agents:[],skills:[],skillsInstalled:[],contextFiles:[],aiTools:[],context7:{installed:o.installed,verified:!1,message:se(_)},error:`Context7 MCP is required but not ready: ${se(_)}. Run 'prjct start' to repair.`}}this.globalPath=E.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await this.ensureDirectories(),await wo(this.projectId);try{let _=await Qi(this.projectId);_>0&&G.info("Swept legacy JSON files into SQLite",{swept:_})}catch(_){G.debug("Legacy JSON sweep failed (non-critical)",{error:se(_)})}let[c,u,d,m]=await Promise.all([My(this.projectPath),Oy(this.projectPath),Fy(this.projectPath),_y(this.projectPath)]),p=t.full===!0,g,f=!0,k=!0,S=new Set;if(!p&&Nh(this.projectId))try{let{diff:_,currentHashes:bk}=await sd(this.projectPath,this.projectId),yp=_.added.length+_.modified.length+_.deleted.length;if(yp===0&&!t.changedFiles?.length)f=!1,k=!1,g={isIncremental:!0,filesChanged:0,filesUnchanged:_.unchanged.length,indexesRebuilt:!1,agentsRegenerated:!1,affectedDomains:[]};else{let pc=$h(_,this.projectId);S=Mh(pc.allAffected);let Ck=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);f=pc.allAffected.some(es=>{let vk=es.substring(es.lastIndexOf("."));return Ck.has(vk)}),k=pc.directlyChanged.some(es=>es==="package.json"||es==="tsconfig.json"||es.includes("Dockerfile")||es.includes("docker-compose")),g={isIncremental:!0,filesChanged:yp,filesUnchanged:_.unchanged.length,indexesRebuilt:f,agentsRegenerated:k,affectedDomains:Array.from(S)}}nd(this.projectId,bk)}catch(_){G.debug("Incremental detection failed, falling back to full sync",{error:se(_)})}else try{let{currentHashes:_}=await sd(this.projectPath,this.projectId);nd(this.projectId,_)}catch(_){G.debug("Hash computation failed (non-critical)",{error:se(_)})}if(f)try{await Promise.all([Eh(this.projectPath,this.projectId),Dh(this.projectPath,this.projectId),Uh(this.projectPath,this.projectId)])}catch(_){G.debug("File ranking index build failed (non-critical)",{error:se(_)})}let R;if(k)try{let _=await L.getAggregatedFeedback(this.projectId);(_.patternsDiscovered.length>0||_.knownGotchas.length>0||_.agentAccuracy.length>0)&&(R=_)}catch{}let v=k?await xy(this.globalPath,m,u,R):await Py(this.globalPath),M=Ey(v,this.projectId,this.globalPath),F=k?await Ay(v):[],V=Ny(u,d),te=[],b;try{let _=await Ze.getActive(this.projectId);(_?.patterns?.length||_?.antiPatterns?.length)&&(b={patterns:_.patterns??[],antiPatterns:_.antiPatterns??[],packageManager:_.packageManager,sourceDir:_.sourceDir,testDir:_.testDir})}catch{}let D;try{D=await dy(this.projectId)}catch{}let ne={projectId:this.projectId,name:u.name,version:u.version,ecosystem:u.ecosystem,projectType:u.projectType,languages:u.languages,frameworks:u.frameworks,repoPath:this.projectPath,branch:c.branch,fileCount:u.fileCount,commits:c.commits,hasChanges:c.hasChanges,commands:d,agents:{workflow:v.filter(_=>_.type==="workflow").map(_=>_.name),domain:v.filter(_=>_.type==="domain").map(_=>_.name)},sources:V,analysis:b,learnings:D},ut=await cy(ne,this.globalPath,this.projectPath,s);await Promise.all([this.updateProjectJson(c,u),this.updateStateJson(u,m),this.logToMemory(c,u),this.saveDraftAnalysis(c,u,m,o.verified)]);let Be=await Ze.getActive(this.projectId),wt={patterns:Be?.patterns?.length||0,antiPatterns:Be?.antiPatterns?.length||0,criticalAntiPatterns:Be?.antiPatterns?.filter(_=>_.severity==="high").length||0},dc=Date.now()-n,Sk=await this.recordSyncMetrics(u,te,v,dc);await this.archiveStaleData(),await this.autoLearnFromHistory(),await $e.installGlobalConfig(),await $e.syncCommands();let hp;try{let _=await $.readConfig(this.projectPath);hp=await Hy.verify(this.projectPath,this.globalPath,_?.verification)}catch(_){G.debug("Verification failed (non-critical)",{error:se(_)})}return{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:c,stats:u,commands:d,stack:m,agents:v,skills:M,skillsInstalled:F,contextFiles:te,aiTools:ut.map(_=>({toolId:_.toolId,outputFile:_.outputFile,success:_.success})),context7:{installed:o.installed,verified:o.verified,message:o.message},analysisSummary:wt,syncMetrics:Sk,verification:hp,incremental:g}}catch(i){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:[],context7:{installed:o.installed,verified:o.verified,message:o.message},error:se(i)}}}async ensureDirectories(){let e=["storage","context","agents","memory","analysis","config","sync"];await Promise.all(e.map(t=>_a.mkdir(La.join(this.globalPath,t),{recursive:!0})))}async updateProjectJson(e,t){let n=I.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||C(),lastSync:C(),lastSyncCommit:e.recentCommits[0]?.hash||null,lastSyncBranch:e.branch};I.setDoc(this.projectId,"project",s)}async updateStateJson(e,t){let s={...await L.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=C(),s.lastUpdated=C(),s.context={...s.context||{},lastSession:C(),lastAction:"Synced project",nextAction:'Run `p. task "description"` to start working'},await L.write(this.projectId,s);try{await gy.generate(this.projectPath,s)}catch(o){G.debug("Local state generation failed (optional)",{error:se(o)})}}async logToMemory(e,t){I.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=La.join(this.globalPath,m),g=await _a.readFile(p,"utf-8");i+=g.length}catch(p){G.debug("Context file not found for metrics",{file:m,error:se(p)})}for(let m of n)try{let p=La.join(this.globalPath,"agents",`${m.name}.md`),g=await _a.readFile(p,"utf-8");i+=g.length}catch(p){G.debug("Agent file not found for metrics",{agent:m.name,error:se(p)})}let a=Math.floor(i/4),u=e.fileCount*500,d=u>0?Math.max(0,(u-a)/u):0;try{await An.recordSync(this.projectId,{originalSize:u,filteredSize:a,duration:s,isWatch:!1,agents:n.filter(m=>m.type==="domain").map(m=>m.name)})}catch(m){G.debug("Failed to record sync metrics",{error:se(m)})}return{duration:s,originalSize:u,filteredSize:a,compressionRate:d}}async saveDraftAnalysis(e,t,n,s){try{let o=e.recentCommits[0]?.hash||null,i=[],a=[],c;try{c=await L.getAggregatedFeedback(this.projectId),c.patternsDiscovered.length>0&&(i=c.patternsDiscovered.map(d=>({name:d,description:`Discovered during task execution: ${d}`,source:"feedback",confidence:.74}))),c.knownGotchas.length>0&&(a=c.knownGotchas.map(d=>({issue:d,file:"multiple",suggestion:`Recurring issue reported across tasks: ${d}`,source:"feedback",severity:"medium",confidence:.7})))}catch{}let u=await Hg.extract({projectId:this.projectId,projectPath:this.projectPath,languages:t.languages,frameworks:Array.from(new Set([...t.frameworks,...n.frameworks])),feedback:c,context7Verified:s});i=u.patterns,a=u.antiPatterns,await Ze.saveDraft(this.projectId,{projectId:this.projectId,languages:t.languages,frameworks:t.frameworks,configFiles:[],fileCount:t.fileCount,patterns:i,antiPatterns:a,analyzedAt:C(),status:"draft",commitHash:o??void 0})}catch(o){G.debug("Failed to save draft analysis (non-critical)",{error:se(o)})}}async archiveStaleData(){if(this.projectId)try{let[e,t,n,s,o]=await Promise.all([xt.archiveOldShipped(this.projectId).catch(()=>0),rt.markDormantIdeas(this.projectId).catch(()=>0),De.removeStaleCompleted(this.projectId).catch(()=>0),L.archiveStalePausedTasks(this.projectId).catch(()=>[]),Pt.capEntries(this.projectId).catch(()=>0)]),i=e+t+n+s.length+o;if(i>0){G.info("Archived stale data",{shipped:e,dormant:t,staleQueue:n,stalePaused:s.length,memoryCapped:o,total:i});let a=Rt.getStats(this.projectId);G.debug("Archive stats",a)}}catch(e){G.debug("Archival failed (non-critical)",{error:se(e)})}}async autoLearnFromHistory(){if(this.projectId)try{let e=await L.getTaskHistory(this.projectId);if(e.length===0)return;let t=new ds,n=await gu.learnFromTaskHistory(this.projectId,e,t);try{let s=await rf.getFeatureOutcomes(this.projectId);s.length>0&&await gu.learnFromOutcomes(this.projectId,s,t)}catch{}n.memoriesInjected>0&&G.info("Auto-learned from task history",{patternsExtracted:n.patternsExtracted,memoriesInjected:n.memoriesInjected,patternsSkipped:n.patternsSkipped})}catch(e){G.debug("Auto-learning failed (non-critical)",{error:se(e)})}}async getCliVersion(){try{let e=La.join(__dirname,"..","..","package.json");return JSON.parse(await _a.readFile(e,"utf-8")).version||"0.0.0"}catch(e){return G.debug("Failed to read CLI version",{error:se(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:[]}}},Sn=new Ha});import{exec as wA}from"node:child_process";import gr from"node:path";import{promisify as kA}from"node:util";function Wy(r){return/^\d+\.\d+\.\d+/.test(r)}function fr(r){let e=r.match(/^(\d+)\.(\d+)\.(\d+)/);if(!e)return r;let[,t,n,s]=e;return`${t}.${n}.${Number(s)+1}`}function SA(r){let e=r.match(/\[package\]([\s\S]*?)(?=\n\[|\n*$)/);return e?e[1].match(/^\s*version\s*=\s*"([^"]+)"/m)?.[1]??null:null}function bA(r){let e=r.match(/\[project\]([\s\S]*?)(?=\n\[|\n*$)/);if(e){let n=e[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}let t=r.match(/\[tool\.poetry\]([\s\S]*?)(?=\n\[|\n*$)/);if(t){let n=t[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}return null}function CA(r){return r.match(/<Version>([^<]+)<\/Version>/)?.[1]?.trim()??null}var Gy,Lo,zy=y(()=>{"use strict";Ee();Gy=kA(wA),Lo=class{static{l(this,"VersionService")}projectPath;constructor(e){this.projectPath=e}async detect(){let e=[()=>this.fromPackageJson(),()=>this.fromCargoToml(),()=>this.fromPyprojectToml(),()=>this.fromCsproj(),()=>this.fromVersionFile("VERSION"),()=>this.fromVersionFile("version.txt"),()=>this.fromGitTag()];for(let t of e){let n=await t();if(n)return n}return this.createFallbackVersion()}async bump(){let e=await this.detect();return await this.writeVersion(e),e.next}async fromPackageJson(){let e=gr.join(this.projectPath,"package.json"),t=await un(e,null);return t?.version?{current:t.version,next:fr(t.version),file:e,format:"json"}:null}async fromCargoToml(){let e=gr.join(this.projectPath,"Cargo.toml"),t=await dt(e,"");if(!t)return null;let n=SA(t);return n?{current:n,next:fr(n),file:e,format:"toml"}:null}async fromPyprojectToml(){let e=gr.join(this.projectPath,"pyproject.toml"),t=await dt(e,"");if(!t)return null;let n=bA(t);return n?{current:n,next:fr(n),file:e,format:"toml"}:null}async fromCsproj(){let e=await vn(this.projectPath,{extension:".csproj"});if(e.length===0)return null;let t=gr.join(this.projectPath,e[0]),n=await dt(t,"");if(!n)return null;let s=CA(n);return s?{current:s,next:fr(s),file:t,format:"xml"}:null}async fromVersionFile(e){let t=gr.join(this.projectPath,e),n=await dt(t,"");if(!n)return null;let s=n.trim();return Wy(s)?{current:s,next:fr(s),file:t,format:"plaintext"}:null}async fromGitTag(){try{let{stdout:e}=await Gy("git tag --sort=-v:refname",{cwd:this.projectPath}),t=e.trim().split(`
1167
+ `).filter(Boolean).map(u=>{let[d,m,p]=u.split("|");return{hash:d,message:m,date:p}});let{stdout:c}=await Is('git log --oneline --since="1 week ago" | wc -l',{cwd:r});e.weeklyCommits=parseInt(c.trim(),10)||0}catch(t){G.debug("Git analysis failed (not a git repo?)",{error:se(t)})}return e}async function kn(r,e){try{return await $y.access(wd.join(r,e)),!0}catch(t){return G.debug("File not found",{filename:e,error:se(t)}),!1}}async function Oy(r){let e={fileCount:0,version:"0.0.0",name:wd.basename(r),ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]};try{let{stdout:t}=await Is('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){G.debug("File count failed",{path:r,error:se(t)}),e.fileCount=0}try{let t=wd.join(r,"package.json"),n=JSON.parse(await $y.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 kn(r,"tsconfig.json")?e.languages.push("TypeScript"):e.languages.push("JavaScript")}catch(t){G.debug("No package.json found",{path:r,error:se(t)})}return await kn(r,"Cargo.toml")&&(e.ecosystem="Rust",e.languages.push("Rust")),await kn(r,"go.mod")&&(e.ecosystem="Go",e.languages.push("Go")),(await kn(r,"requirements.txt")||await kn(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 Fy(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 kn(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 kn(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 kn(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 kn(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 kn(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 Ny(r,e){let t=As(),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 _y(r){return new Fa(r).detect()}var Is,Ly=y(()=>{"use strict";Pn();od();Gn();Dy();Is=gA(mA);l(My,"analyzeGit");l(kn,"fileExists");l(Oy,"gatherStats");l(Fy,"detectCommands");l(Ny,"buildSources");l(_y,"detectStack")});import{exec as fA}from"node:child_process";import kd from"node:fs/promises";import Na from"node:path";import{promisify as hA}from"node:util";var yA,Sd,bd,Hy,Uy=y(()=>{"use strict";nn();N();yA=hA(fA),Sd={async contextFilesExist(r){let e=Date.now(),t=["context/CLAUDE.md"],n=[];for(let s of t){let o=Na.join(r,s);try{await kd.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=Na.basename(r);try{await L.read(n)}catch(s){x(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=Na.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 kd.readdir(t);for(let i of o){if(!i.endsWith(".md"))continue;let a=await kd.readFile(Na.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(!x(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}}},bd=class{static{l(this,"SyncVerifier")}async verify(e,t,n){let s=Date.now(),o=[],i=n?.failFast??!1,a=0,c=[Sd.contextFilesExist(t),Sd.jsonFilesValid(t),Sd.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(k=>k.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 yA(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}}}},Hy=new bd});import _a from"node:fs/promises";import La from"node:path";var Ha,Sn,Ua=y(()=>{"use strict";er();Qu();Oh();_h();Gh();ed();Pn();Ke();Vn();tt();xe();pr();ho();Un();ue();Qr();yo();Zi();Zr();eo();Ks();uy();py();le();Gn();fu();hu();gs();fy();Ul();ql();Iy();Ly();Uy();Ha=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 i=await Oa(e),a=i.filter(u=>mr.includes(u)||u==="codex"),c=i.filter(u=>!mr.includes(u)&&u!=="codex");s=[...a.length>0?a:mr,...c],s=Array.from(new Set(s))}else t.aiTools[0]==="auto"?(s=await Oa(e),s.length===0&&(s=["claude"])):t.aiTools[0]==="all"?s=await sy("all",e):s=t.aiTools;let o={installed:!1,verified:!1,configPath:"",message:""};try{if(this.projectId=await $.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:[],context7:{installed:!1,verified:!1},error:"No prjct project. Run p. init first."};if((await ss()).installed){let _=await dr({autoRepair:!0});if(!_.verified)return{success:!1,projectId:this.projectId,cliVersion:"",git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),agents:[],skills:[],skillsInstalled:[],contextFiles:[],aiTools:[],context7:{installed:!1,verified:!1},error:`Codex p. router is required but not ready: ${_.message||"verification failed"}. Run 'prjct start' or 'prjct setup' to repair.`}}try{o=await tn.ensureReady()}catch(_){return{success:!1,projectId:this.projectId,cliVersion:"",git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),agents:[],skills:[],skillsInstalled:[],contextFiles:[],aiTools:[],context7:{installed:o.installed,verified:!1,message:se(_)},error:`Context7 MCP is required but not ready: ${se(_)}. Run 'prjct start' to repair.`}}this.globalPath=E.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await this.ensureDirectories(),await wo(this.projectId);try{let _=await Qi(this.projectId);_>0&&G.info("Swept legacy JSON files into SQLite",{swept:_})}catch(_){G.debug("Legacy JSON sweep failed (non-critical)",{error:se(_)})}let[c,u,d,m]=await Promise.all([My(this.projectPath),Oy(this.projectPath),Fy(this.projectPath),_y(this.projectPath)]),p=t.full===!0,g,f=!0,k=!0,S=new Set;if(!p&&Nh(this.projectId))try{let{diff:_,currentHashes:bk}=await sd(this.projectPath,this.projectId),yp=_.added.length+_.modified.length+_.deleted.length;if(yp===0&&!t.changedFiles?.length)f=!1,k=!1,g={isIncremental:!0,filesChanged:0,filesUnchanged:_.unchanged.length,indexesRebuilt:!1,agentsRegenerated:!1,affectedDomains:[]};else{let pc=$h(_,this.projectId);S=Mh(pc.allAffected);let Ck=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);f=pc.allAffected.some(es=>{let vk=es.substring(es.lastIndexOf("."));return Ck.has(vk)}),k=pc.directlyChanged.some(es=>es==="package.json"||es==="tsconfig.json"||es.includes("Dockerfile")||es.includes("docker-compose")),g={isIncremental:!0,filesChanged:yp,filesUnchanged:_.unchanged.length,indexesRebuilt:f,agentsRegenerated:k,affectedDomains:Array.from(S)}}nd(this.projectId,bk)}catch(_){G.debug("Incremental detection failed, falling back to full sync",{error:se(_)})}else try{let{currentHashes:_}=await sd(this.projectPath,this.projectId);nd(this.projectId,_)}catch(_){G.debug("Hash computation failed (non-critical)",{error:se(_)})}if(f)try{await Promise.all([Eh(this.projectPath,this.projectId),Dh(this.projectPath,this.projectId),Uh(this.projectPath,this.projectId)])}catch(_){G.debug("File ranking index build failed (non-critical)",{error:se(_)})}let R;if(k)try{let _=await L.getAggregatedFeedback(this.projectId);(_.patternsDiscovered.length>0||_.knownGotchas.length>0||_.agentAccuracy.length>0)&&(R=_)}catch{}let v=k?await xy(this.globalPath,m,u,R):await Py(this.globalPath),M=Ey(v,this.projectId,this.globalPath),F=k?await Ay(v):[],V=Ny(u,d),te=[],b;try{let _=await Ze.getActive(this.projectId);(_?.patterns?.length||_?.antiPatterns?.length)&&(b={patterns:_.patterns??[],antiPatterns:_.antiPatterns??[],packageManager:_.packageManager,sourceDir:_.sourceDir,testDir:_.testDir})}catch{}let D;try{D=await dy(this.projectId)}catch{}let ne={projectId:this.projectId,name:u.name,version:u.version,ecosystem:u.ecosystem,projectType:u.projectType,languages:u.languages,frameworks:u.frameworks,repoPath:this.projectPath,branch:c.branch,fileCount:u.fileCount,commits:c.commits,hasChanges:c.hasChanges,commands:d,agents:{workflow:v.filter(_=>_.type==="workflow").map(_=>_.name),domain:v.filter(_=>_.type==="domain").map(_=>_.name)},sources:V,analysis:b,learnings:D},ut=await cy(ne,this.globalPath,this.projectPath,s);await Promise.all([this.updateProjectJson(c,u),this.updateStateJson(u,m),this.logToMemory(c,u),this.saveDraftAnalysis(c,u,m,o.verified)]);let Be=await Ze.getActive(this.projectId),wt={patterns:Be?.patterns?.length||0,antiPatterns:Be?.antiPatterns?.length||0,criticalAntiPatterns:Be?.antiPatterns?.filter(_=>_.severity==="high").length||0},dc=Date.now()-n,Sk=await this.recordSyncMetrics(u,te,v,dc);await this.archiveStaleData(),await this.autoLearnFromHistory(),await $e.installGlobalConfig(),await $e.syncCommands();let hp;try{let _=await $.readConfig(this.projectPath);hp=await Hy.verify(this.projectPath,this.globalPath,_?.verification)}catch(_){G.debug("Verification failed (non-critical)",{error:se(_)})}return{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:c,stats:u,commands:d,stack:m,agents:v,skills:M,skillsInstalled:F,contextFiles:te,aiTools:ut.map(_=>({toolId:_.toolId,outputFile:_.outputFile,success:_.success})),context7:{installed:o.installed,verified:o.verified,message:o.message},analysisSummary:wt,syncMetrics:Sk,verification:hp,incremental:g}}catch(i){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:[],context7:{installed:o.installed,verified:o.verified,message:o.message},error:se(i)}}}async ensureDirectories(){let e=["storage","context","agents","memory","analysis","config","sync"];await Promise.all(e.map(t=>_a.mkdir(La.join(this.globalPath,t),{recursive:!0})))}async updateProjectJson(e,t){let n=I.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||C(),lastSync:C(),lastSyncCommit:e.recentCommits[0]?.hash||null,lastSyncBranch:e.branch};I.setDoc(this.projectId,"project",s)}async updateStateJson(e,t){let s={...await L.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=C(),s.lastUpdated=C(),s.context={...s.context||{},lastSession:C(),lastAction:"Synced project",nextAction:'Run `p. task "description"` to start working'},await L.write(this.projectId,s);try{await gy.generate(this.projectPath,s)}catch(o){G.debug("Local state generation failed (optional)",{error:se(o)})}}async logToMemory(e,t){I.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=La.join(this.globalPath,m),g=await _a.readFile(p,"utf-8");i+=g.length}catch(p){G.debug("Context file not found for metrics",{file:m,error:se(p)})}for(let m of n)try{let p=La.join(this.globalPath,"agents",`${m.name}.md`),g=await _a.readFile(p,"utf-8");i+=g.length}catch(p){G.debug("Agent file not found for metrics",{agent:m.name,error:se(p)})}let a=Math.floor(i/4),u=e.fileCount*500,d=u>0?Math.max(0,(u-a)/u):0;try{await An.recordSync(this.projectId,{originalSize:u,filteredSize:a,duration:s,isWatch:!1,agents:n.filter(m=>m.type==="domain").map(m=>m.name)})}catch(m){G.debug("Failed to record sync metrics",{error:se(m)})}return{duration:s,originalSize:u,filteredSize:a,compressionRate:d}}async saveDraftAnalysis(e,t,n,s){try{let o=e.recentCommits[0]?.hash||null,i=[],a=[],c;try{c=await L.getAggregatedFeedback(this.projectId),c.patternsDiscovered.length>0&&(i=c.patternsDiscovered.map(d=>({name:d,description:`Discovered during task execution: ${d}`,source:"feedback",confidence:.74}))),c.knownGotchas.length>0&&(a=c.knownGotchas.map(d=>({issue:d,file:"multiple",suggestion:`Recurring issue reported across tasks: ${d}`,source:"feedback",severity:"medium",confidence:.7})))}catch{}let u=await Hg.extract({projectId:this.projectId,projectPath:this.projectPath,languages:t.languages,frameworks:Array.from(new Set([...t.frameworks,...n.frameworks])),feedback:c,context7Verified:s});i=u.patterns,a=u.antiPatterns,await Ze.saveDraft(this.projectId,{projectId:this.projectId,languages:t.languages,frameworks:t.frameworks,configFiles:[],fileCount:t.fileCount,patterns:i,antiPatterns:a,analyzedAt:C(),status:"draft",commitHash:o??void 0})}catch(o){G.debug("Failed to save draft analysis (non-critical)",{error:se(o)})}}async archiveStaleData(){if(this.projectId)try{let[e,t,n,s,o]=await Promise.all([xt.archiveOldShipped(this.projectId).catch(()=>0),rt.markDormantIdeas(this.projectId).catch(()=>0),De.removeStaleCompleted(this.projectId).catch(()=>0),L.archiveStalePausedTasks(this.projectId).catch(()=>[]),Pt.capEntries(this.projectId).catch(()=>0)]),i=e+t+n+s.length+o;if(i>0){G.info("Archived stale data",{shipped:e,dormant:t,staleQueue:n,stalePaused:s.length,memoryCapped:o,total:i});let a=Rt.getStats(this.projectId);G.debug("Archive stats",a)}}catch(e){G.debug("Archival failed (non-critical)",{error:se(e)})}}async autoLearnFromHistory(){if(this.projectId)try{let e=await L.getTaskHistory(this.projectId);if(e.length===0)return;let t=new ds,n=await gu.learnFromTaskHistory(this.projectId,e,t);try{let s=await rf.getFeatureOutcomes(this.projectId);s.length>0&&await gu.learnFromOutcomes(this.projectId,s,t)}catch{}n.memoriesInjected>0&&G.info("Auto-learned from task history",{patternsExtracted:n.patternsExtracted,memoriesInjected:n.memoriesInjected,patternsSkipped:n.patternsSkipped})}catch(e){G.debug("Auto-learning failed (non-critical)",{error:se(e)})}}async getCliVersion(){try{let e=La.join(__dirname,"..","..","package.json");return JSON.parse(await _a.readFile(e,"utf-8")).version||"0.0.0"}catch(e){return G.debug("Failed to read CLI version",{error:se(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:[]}}},Sn=new Ha});import{exec as wA}from"node:child_process";import gr from"node:path";import{promisify as kA}from"node:util";function Wy(r){return/^\d+\.\d+\.\d+/.test(r)}function fr(r){let e=r.match(/^(\d+)\.(\d+)\.(\d+)/);if(!e)return r;let[,t,n,s]=e;return`${t}.${n}.${Number(s)+1}`}function SA(r){let e=r.match(/\[package\]([\s\S]*?)(?=\n\[|\n*$)/);return e?e[1].match(/^\s*version\s*=\s*"([^"]+)"/m)?.[1]??null:null}function bA(r){let e=r.match(/\[project\]([\s\S]*?)(?=\n\[|\n*$)/);if(e){let n=e[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}let t=r.match(/\[tool\.poetry\]([\s\S]*?)(?=\n\[|\n*$)/);if(t){let n=t[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}return null}function CA(r){return r.match(/<Version>([^<]+)<\/Version>/)?.[1]?.trim()??null}var Gy,Lo,zy=y(()=>{"use strict";Ee();Gy=kA(wA),Lo=class{static{l(this,"VersionService")}projectPath;constructor(e){this.projectPath=e}async detect(){let e=[()=>this.fromPackageJson(),()=>this.fromCargoToml(),()=>this.fromPyprojectToml(),()=>this.fromCsproj(),()=>this.fromVersionFile("VERSION"),()=>this.fromVersionFile("version.txt"),()=>this.fromGitTag()];for(let t of e){let n=await t();if(n)return n}return this.createFallbackVersion()}async bump(){let e=await this.detect();return await this.writeVersion(e),e.next}async fromPackageJson(){let e=gr.join(this.projectPath,"package.json"),t=await un(e,null);return t?.version?{current:t.version,next:fr(t.version),file:e,format:"json"}:null}async fromCargoToml(){let e=gr.join(this.projectPath,"Cargo.toml"),t=await dt(e,"");if(!t)return null;let n=SA(t);return n?{current:n,next:fr(n),file:e,format:"toml"}:null}async fromPyprojectToml(){let e=gr.join(this.projectPath,"pyproject.toml"),t=await dt(e,"");if(!t)return null;let n=bA(t);return n?{current:n,next:fr(n),file:e,format:"toml"}:null}async fromCsproj(){let e=await vn(this.projectPath,{extension:".csproj"});if(e.length===0)return null;let t=gr.join(this.projectPath,e[0]),n=await dt(t,"");if(!n)return null;let s=CA(n);return s?{current:s,next:fr(s),file:t,format:"xml"}:null}async fromVersionFile(e){let t=gr.join(this.projectPath,e),n=await dt(t,"");if(!n)return null;let s=n.trim();return Wy(s)?{current:s,next:fr(s),file:t,format:"plaintext"}:null}async fromGitTag(){try{let{stdout:e}=await Gy("git tag --sort=-v:refname",{cwd:this.projectPath}),t=e.trim().split(`
1168
1168
  `);for(let n of t){let s=n.trim().replace(/^v/,"");if(Wy(s))return{current:s,next:fr(s),file:null,format:"git-tag"}}}catch{}return null}async createFallbackVersion(){let e=gr.join(this.projectPath,"VERSION");return await dn(e,`0.1.0
1169
1169
  `),{current:"0.1.0",next:"0.1.1",file:e,format:"plaintext"}}async writeVersion(e){if(!e.file){e.format==="git-tag"&&await Gy(`git tag v${e.next}`,{cwd:this.projectPath});return}switch(e.format){case"json":await this.writeJsonVersion(e.file,e.next);break;case"toml":await this.writeTomlVersion(e.file,e.next);break;case"xml":await this.writeXmlVersion(e.file,e.next);break;case"plaintext":await dn(e.file,`${e.next}
1170
1170
  `);break}}async writeJsonVersion(e,t){let n=await un(e,{});n&&(n.version=t,await ns(e,n))}async writeTomlVersion(e,t){let n=await dt(e,"");if(!n)return;let s=n.replace(/^(\s*version\s*=\s*")([^"]+)(")/m,`$1${t}$3`);await dn(e,s)}async writeXmlVersion(e,t){let n=await dt(e,"");if(!n)return;let s=n.replace(/(<Version>)([^<]+)(<\/Version>)/,`$1${t}$3`);await dn(e,s)}};l(Wy,"isSemver");l(fr,"bumpPatch");l(SA,"parseTomlVersion");l(bA,"parsePyprojectVersion");l(CA,"parseCsprojVersion")});var jn=y(()=>{"use strict";dg();kg();Sg();Cg();Tg();gs();$g();_l();Og();Ul();Fg();Vl();ql();Ug();kh();Sh();Ua();zy()});var Cd,vA,hr,vd=y(()=>{"use strict";le();ue();Cd=class{static{l(this,"LLMAnalysisStorage")}save(e,t){let n=I.getDb(e),s=C();n.transaction(()=>{n.prepare("UPDATE llm_analysis SET status = 'superseded', superseded_at = ? WHERE status = 'active'").run(s),n.prepare("INSERT INTO llm_analysis (commit_hash, status, analysis, analyzed_at) VALUES (?, ?, ?, ?)").run(t.commitHash??null,"active",JSON.stringify(t),t.analyzedAt)})()}getActive(e){let t=I.get(e,"SELECT analysis FROM llm_analysis WHERE status = 'active' LIMIT 1");return t?JSON.parse(t.analysis):null}getActiveSummary(e){let t=this.getActive(e);return t?{commitHash:t.commitHash,architectureStyle:t.architecture.style,patternCount:t.patterns.length,antiPatternCount:t.antiPatterns.length,analyzedAt:t.analyzedAt}:null}isCurrent(e,t){return t?I.get(e,"SELECT commit_hash FROM llm_analysis WHERE status = 'active' LIMIT 1")?.commit_hash===t:!1}getHistory(e,t=10){return I.query(e,"SELECT id, commit_hash, status, analyzed_at, analysis FROM llm_analysis ORDER BY id DESC LIMIT ?",t).map(s=>{let o=JSON.parse(s.analysis);return{id:s.id,commitHash:s.commit_hash,status:s.status,analyzedAt:s.analyzed_at,patternCount:o.patterns.length}})}},vA=new Cd,hr=vA});import Vy from"node:fs/promises";import By from"node:path";async function Jy(r,e,t,n){let[s,o,i,a]=await Promise.all([TA(r,e,n),EA(r),AA(r),IA(r)]);return{project:{name:n.name,ecosystem:n.ecosystem,languages:n.languages,frameworks:n.frameworks,fileCount:n.fileCount,projectType:n.projectType},git:{branch:t.branch,recentCommits:t.recentCommits.slice(0,xA).map(c=>({message:c.message,date:c.date})),hasChanges:t.hasChanges,weeklyCommits:t.weeklyCommits},codeSamples:s,existingPatterns:o,taskHistory:i,previousAnalysis:a??void 0}}async function TA(r,e,t){let n=[],s=[...t.frameworks.map(a=>a.toLowerCase()),"config","router","middleware","service","model","schema","database","api","auth"].join(" "),o=Ah(r,s,xd*2);for(let a of o){if(n.length>=xd)break;try{let c=By.join(e,a.path),u=await Vy.readFile(c,"utf-8");u.length>Ga*3?n.push({path:a.path,content:`${u.slice(0,Ga)}
@@ -1646,7 +1646,7 @@ ${o.split(`
1646
1646
  `);o.trim()==="#!/bin/sh"||o.trim()==="#!/usr/bin/env sh"?await Ve.unlink(n):await Ve.writeFile(n,o,{mode:493})}return!0}async function xj(r){let e=_e.join(r,".git","hooks");for(let t of["post-commit","post-checkout"]){let n=_e.join(e,t);if(!await P(n))continue;let s=await Ve.readFile(n,"utf-8");if(s.includes("prjct sync"))if(s.includes("Installed by: prjct hooks install"))await Ve.unlink(n);else{let o=s.split(`
1647
1647
  `).filter(i=>!i.includes("prjct sync")&&!i.includes("prjct auto-sync")).join(`
1648
1648
  `);await Ve.writeFile(n,o,{mode:493})}}return!0}var mp,Pj,nk=y(()=>{"use strict";tt();ue();N();Ee();Yt();l(Zw,"getPostCommitScript");l(ek,"getPostCheckoutScript");l(pp,"detectHookManagers");l(Qw,"selectStrategy");l(kj,"installLefthook");l(Sj,"installHusky");l(bj,"installDirect");l(Cj,"uninstallLefthook");l(vj,"uninstallHusky");l(xj,"uninstallDirect");mp=class{static{l(this,"HooksService")}async install(e,t={}){let n=t.hooks||["post-commit","post-checkout"],s=await pp(e);if(s.length===0)return{success:!1,strategy:"direct",hooksInstalled:[],error:'Not a git repository. Run "git init" first.'};let o=t.strategy||Qw(s);try{let i=!1;switch(o){case"lefthook":i=await kj(e,n);break;case"husky":i=await Sj(e,n);break;case"direct":i=await bj(e,n);break}return i&&await this.saveHookConfig(e,{enabled:!0,strategy:o,hooks:n,installedAt:new Date().toISOString()}),{success:i,strategy:o,hooksInstalled:i?n:[]}}catch(i){return{success:!1,strategy:o,hooksInstalled:[],error:w(i)}}}async uninstall(e){try{let n=(await this.getHookConfig(e))?.strategy||"direct",s=!1;switch(n){case"lefthook":s=await Cj(e);break;case"husky":s=await vj(e);break;case"direct":s=await xj(e);break}return s&&await this.saveHookConfig(e,{enabled:!1,strategy:n,hooks:[]}),{success:s}}catch(t){return{success:!1,error:w(t)}}}async status(e){let t=await pp(e),n=await this.getHookConfig(e),s=["post-commit","post-checkout"],o=await Promise.all(s.map(async i=>({name:i,installed:await this.isHookInstalled(e,i,n?.strategy||null),path:await this.getHookPath(e,i,n?.strategy||null)})));return{installed:o.some(i=>i.installed),strategy:n?.strategy||null,hooks:o,detectedManagers:t}}async run(e,t){if(!await $.getProjectId(e))return console.error('No prjct project found. Run "prjct init" first.'),1;switch(t){case"install":return this.runInstall(e);case"uninstall":return this.runUninstall(e);case"status":return this.runStatus(e);default:return this.runStatus(e)}}async runInstall(e){h.start(),h.section("Git Hooks Installation");let t=await pp(e),n=Qw(t);console.log(` Strategy: ${Ot.cyan(n)}`),console.log(` Hooks: ${Ot.dim("post-commit, post-checkout")}`),console.log("");let s=await this.install(e,{strategy:n});if(s.success){h.done(`Hooks installed via ${s.strategy}`),console.log("");for(let o of s.hooksInstalled)console.log(` ${Ot.green("\u2713")} ${o}`);console.log(""),console.log(Ot.dim(" Context will auto-sync on commit and branch switch.")),console.log(Ot.dim(" Remove with: prjct hooks uninstall"))}else h.fail(s.error||"Failed to install hooks");return console.log(""),h.end(),s.success?0:1}async runUninstall(e){h.start(),h.section("Git Hooks Removal");let t=await this.uninstall(e);return t.success?h.done("Hooks removed"):h.fail(t.error||"Failed to remove hooks"),console.log(""),h.end(),t.success?0:1}async runStatus(e){h.start(),h.section("Git Hooks Status");let t=await this.status(e);t.installed?(console.log(` Status: ${Ot.green("Active")}`),console.log(` Strategy: ${Ot.cyan(t.strategy)}`)):console.log(` Status: ${Ot.dim("Not installed")}`),console.log("");for(let n of t.hooks){let s=n.installed?Ot.green("\u2713"):Ot.dim("\u25CB"),o=n.installed?n.name:Ot.dim(n.name);console.log(` ${s} ${o}`)}return t.detectedManagers.length>0&&(console.log(""),console.log(` ${Ot.dim("Available managers:")} ${t.detectedManagers.join(", ")}`)),t.installed||(console.log(""),console.log(Ot.dim(" Install with: prjct hooks install"))),console.log(""),h.end(),0}async isHookInstalled(e,t,n){if(n==="lefthook"){let o=await P(_e.join(e,"lefthook.yml"))?"lefthook.yml":"lefthook.yaml",i=_e.join(e,o);return await P(i)?(await Ve.readFile(i,"utf-8")).includes(`prjct-sync-${t}`):!1}if(n==="husky"){let o=_e.join(e,".husky",t);return await P(o)?(await Ve.readFile(o,"utf-8")).includes("prjct sync"):!1}let s=_e.join(e,".git","hooks",t);return await P(s)?(await Ve.readFile(s,"utf-8")).includes("prjct sync"):!1}async getHookPath(e,t,n){return n==="lefthook"?await P(_e.join(e,"lefthook.yml"))?"lefthook.yml":"lefthook.yaml":n==="husky"?`.husky/${t}`:`.git/hooks/${t}`}async getHookConfig(e){let t=await $.getProjectId(e);if(!t)return null;try{let n=I.getDoc(t,"project");return n&&n.hooks||null}catch{return null}}async saveHookConfig(e,t){let n=await $.getProjectId(e);if(n)try{let s=I.getDoc(n,"project")||{};s.hooks=t,I.setDoc(n,"project",s)}catch{}}},Pj=new mp});var ok={};Ce(ok,{DoctorService:()=>cc,doctorService:()=>Tj});import{execSync as gp}from"node:child_process";import sk from"node:fs/promises";import rk from"node:path";import Zn from"chalk";var cc,Tj,ik=y(()=>{"use strict";tt();xe();pr();nn();Yt();pt();gs();cc=class{static{l(this,"DoctorService")}projectPath="";projectId=null;globalPath="";async check(e=process.cwd()){this.projectPath=e,this.projectId=await $.getProjectId(e),this.projectId&&(this.globalPath=E.getGlobalProjectPath(this.projectId));let t=await this.checkTools(),n=await this.checkProject(),s=this.generateRecommendations(t,n),o=[...t,...n].some(a=>a.status==="error"&&!a.optional),i=[...t,...n].some(a=>a.status==="warn"||a.status==="error"&&a.optional);return{success:!o,tools:t,project:n,recommendations:s,hasErrors:o,hasWarnings:i}}async run(e=process.cwd()){let t=await this.check(e);return this.printHeader(),this.printSection("System Tools",t.tools),this.printSection("Project Status",t.project),t.recommendations.length>0&&this.printRecommendations(t.recommendations),this.printSummary(t),t.hasErrors?1:0}async checkTools(){let e=[];return e.push(this.checkCommand("git","git --version",/git version ([\d.]+)/,!1)),e.push(this.checkCommand("node","node --version",/v([\d.]+)/,!1)),e.push(this.checkCommand("bun","bun --version",/([\d.]+)/,!0)),e.push(this.checkCommand("gh","gh --version",/gh version ([\d.]+)/,!0,"needed for PR commands")),e.push(this.checkCommand("claude","claude --version",/claude ([\d.]+)/,!0,"Anthropic Claude Code CLI")),e.push(this.checkCommand("gemini","gemini --version",/gemini ([\d.]+)/,!0,"Google Gemini CLI")),e}checkCommand(e,t,n,s,o){try{let a=gp(t,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).match(n),c=a?a[1]:"unknown";return{name:e,status:"ok",version:c,optional:s}}catch{return{name:e,status:"error",message:o?`not found (${o})`:"not found",optional:s}}}async checkProject(){let e=[];return e.push(await this.checkPrjctConfig()),e.push(await this.checkClaudeMd()),e.push(await this.checkGitRepo()),e.push(await this.checkStateFile()),e.push(await this.checkContext7()),e.push(await this.checkCodexPRouter()),e}async checkPrjctConfig(){let e=rk.join(this.projectPath,".prjct","prjct.config.json");try{return await sk.access(e),{name:"prjct config",status:"ok",message:"initialized"}}catch{return{name:"prjct config",status:"error",message:'not initialized - run "prjct init"'}}}async checkClaudeMd(){if(!this.globalPath)return{name:"CLAUDE.md",status:"warn",message:"project not initialized"};let e=rk.join(this.globalPath,"context","CLAUDE.md");try{let t=await sk.stat(e),n=Date.now()-t.mtimeMs,s=Math.floor(n/(1e3*60*60)),o=Math.floor(s/24),i;return o>0?i=`${o} day${o>1?"s":""} ago`:s>0?i=`${s} hour${s>1?"s":""} ago`:i="recently",s>24?{name:"CLAUDE.md",status:"warn",message:`stale (last sync: ${i})`}:{name:"CLAUDE.md",status:"ok",message:`synced ${i}`}}catch{return{name:"CLAUDE.md",status:"error",message:'not found - run "prjct sync"'}}}async checkGitRepo(){try{gp("git rev-parse --git-dir",{cwd:this.projectPath,stdio:["pipe","pipe","pipe"]});let e=gp("git status --porcelain",{cwd:this.projectPath,encoding:"utf-8"});if(e.trim().length>0){let n=e.trim().split(`
1649
- `).filter(Boolean);return{name:"git repo",status:"ok",message:`${n.length} uncommitted change${n.length>1?"s":""}`}}return{name:"git repo",status:"ok",message:"clean"}}catch{return{name:"git repo",status:"warn",message:"not a git repository"}}}async checkStateFile(){if(!this.globalPath||!this.projectId)return{name:"task state",status:"warn",message:"project not initialized"};try{let e=await L.read(this.projectId);return e.currentTask?{name:"task state",status:"ok",message:`active: ${e.currentTask.description?.slice(0,30)}...`}:{name:"task state",status:"ok",message:"no active task"}}catch{return{name:"task state",status:"ok",message:"no state data (normal for new projects)",optional:!0}}}async checkContext7(){try{let e=await tn.verify();return e.installed?e.verified?{name:"context7 mcp",status:"ok",message:"ready"}:{name:"context7 mcp",status:"error",message:e.message||"configured but verification failed"}:{name:"context7 mcp",status:"error",message:'not configured - run "prjct start"'}}catch(e){return{name:"context7 mcp",status:"error",message:`check failed: ${e instanceof Error?e.message:"unknown error"}`}}}async checkCodexPRouter(){try{let e=await dr();return e.installed?e.verified?{name:"codex p-router",status:"ok",message:`ready (${e.templateSource||"local-dev"})`}:{name:"codex p-router",status:"error",message:e.message||"router verification failed"}:{name:"codex p-router",status:"ok",message:"codex not detected (check skipped)",optional:!0}}catch(e){return{name:"codex p-router",status:"error",message:`check failed: ${e instanceof Error?e.message:"unknown error"}`}}}generateRecommendations(e,t){let n=[];e.find(d=>d.name==="gh"&&d.status==="error")&&n.push("Install GitHub CLI (gh) for PR commands: https://cli.github.com");let o=t.find(d=>d.name==="CLAUDE.md");o?.status==="warn"&&o.message?.includes("stale")&&n.push('Run "prjct sync" to update context');let i=t.find(d=>d.name==="prjct config");i?.status==="error"&&n.push('Run "prjct init" to initialize this project'),t.find(d=>d.name==="CLAUDE.md"&&d.status==="error")&&!i?.status?.includes("error")&&n.push('Run "prjct sync" to generate context files');let c=t.find(d=>d.name==="context7 mcp");c&&c.status!=="ok"&&n.push('Run "prjct start" to install/repair Context7 MCP');let u=t.find(d=>d.name==="codex p-router");return u&&u.status==="error"&&n.push('Run "prjct start" or "prjct setup" to repair Codex p. router'),n}printHeader(){h.section(`prjct doctor v${Se}`)}printSection(e,t){h.section(e);let n=t.map(s=>{let o=this.getStatusIcon(s.status,s.optional),i=s.name.padEnd(14),a=s.version||s.message||"",c=s.optional&&s.status==="error"?Zn.dim(" (optional)"):"";return`${o} ${i} ${Zn.dim(a)}${c}`});for(let s of n)console.log(` ${s}`)}printRecommendations(e){h.section("Recommendations"),h.list(e,{bullet:Zn.yellow("\u2022")})}printSummary(e){console.log(""),console.log(Zn.dim("\u2500".repeat(40))),e.hasErrors?h.fail("Some required checks failed"):e.hasWarnings?h.warn("All required checks passed (some warnings)"):h.done("All checks passed"),console.log("")}getStatusIcon(e,t){switch(e){case"ok":return Zn.green("\u2713");case"warn":return Zn.yellow("\u26A0");case"error":return t?Zn.dim("\u25CB"):Zn.red("\u2717")}}},Tj=new cc});var ak={};Ce(ak,{WatchService:()=>lc,watchService:()=>Rj});import Ej from"node:path";import lt from"chalk";import Aj from"chokidar";var Ij,jj,lc,Rj,ck=y(()=>{"use strict";tt();N();le();Ua();Ij=["package.json","package-lock.json","bun.lockb","pnpm-lock.yaml","yarn.lock","tsconfig.json","tsconfig.*.json",".env",".env.*","Cargo.toml","go.mod","pyproject.toml","requirements.txt","src/**/*.ts","src/**/*.tsx","src/**/*.js","src/**/*.jsx","lib/**/*.ts","core/**/*.ts","app/**/*.ts","app/**/*.tsx","pages/**/*.ts","pages/**/*.tsx"],jj=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/coverage/**","**/*.log","**/*.tmp","**/CLAUDE.md","**/.cursorrules","**/.windsurfrules","**/.prjct/**","**/.prjct-cli/**"],lc=class{static{l(this,"WatchService")}watcher=null;projectPath="";projectId=null;debounceTimer=null;lastSyncTime=0;pendingChanges=new Set;options={debounceMs:2e3,minIntervalMs:3e4,verbose:!1,quiet:!1};isRunning=!1;syncCount=0;sigintHandler=null;sigtermHandler=null;async start(e=process.cwd(),t={}){return this.projectPath=e,this.options={...this.options,...t},this.projectId=await $.getProjectId(e),this.projectId?this.isRunning?{success:!1,error:"Watch mode is already running"}:(this.isRunning=!0,this.options.quiet||this.printStartup(),this.watcher=Aj.watch(Ij,{cwd:this.projectPath,ignored:jj,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}}),this.watcher.on("add",n=>this.handleChange("add",n)).on("change",n=>this.handleChange("change",n)).on("unlink",n=>this.handleChange("unlink",n)).on("error",n=>this.handleError(n)),this.sigintHandler&&process.off("SIGINT",this.sigintHandler),this.sigtermHandler&&process.off("SIGTERM",this.sigtermHandler),this.sigintHandler=()=>this.stop(),this.sigtermHandler=()=>this.stop(),process.on("SIGINT",this.sigintHandler),process.on("SIGTERM",this.sigtermHandler),{success:!0}):{success:!1,error:'No prjct project. Run "prjct init" first.'}}async stop(){this.options.quiet||(console.log(""),console.log(lt.dim(`
1649
+ `).filter(Boolean);return{name:"git repo",status:"ok",message:`${n.length} uncommitted change${n.length>1?"s":""}`}}return{name:"git repo",status:"ok",message:"clean"}}catch{return{name:"git repo",status:"warn",message:"not a git repository"}}}async checkStateFile(){if(!this.globalPath||!this.projectId)return{name:"task state",status:"warn",message:"project not initialized"};try{let e=await L.read(this.projectId);return e.currentTask?{name:"task state",status:"ok",message:`active: ${e.currentTask.description?.slice(0,30)}...`}:{name:"task state",status:"ok",message:"no active task"}}catch{return{name:"task state",status:"ok",message:"no state data (normal for new projects)",optional:!0}}}async checkContext7(){try{let e=await tn.verify();return e.installed?e.verified?{name:"context7 mcp",status:"ok",message:"ready"}:{name:"context7 mcp",status:"error",message:e.message||"configured but verification failed"}:{name:"context7 mcp",status:"error",message:'not configured - run "prjct start"'}}catch(e){return{name:"context7 mcp",status:"error",message:`check failed: ${e instanceof Error?e.message:"unknown error"}`}}}async checkCodexPRouter(){try{let e=await dr({autoRepair:!0});return e.installed?e.verified?{name:"codex p-router",status:"ok",message:`ready (${e.templateSource||"local-dev"})`}:{name:"codex p-router",status:"error",message:e.message||"router verification failed"}:{name:"codex p-router",status:"ok",message:"codex not detected (check skipped)",optional:!0}}catch(e){return{name:"codex p-router",status:"error",message:`check failed: ${e instanceof Error?e.message:"unknown error"}`}}}generateRecommendations(e,t){let n=[];e.find(d=>d.name==="gh"&&d.status==="error")&&n.push("Install GitHub CLI (gh) for PR commands: https://cli.github.com");let o=t.find(d=>d.name==="CLAUDE.md");o?.status==="warn"&&o.message?.includes("stale")&&n.push('Run "prjct sync" to update context');let i=t.find(d=>d.name==="prjct config");i?.status==="error"&&n.push('Run "prjct init" to initialize this project'),t.find(d=>d.name==="CLAUDE.md"&&d.status==="error")&&!i?.status?.includes("error")&&n.push('Run "prjct sync" to generate context files');let c=t.find(d=>d.name==="context7 mcp");c&&c.status!=="ok"&&n.push('Run "prjct start" to install/repair Context7 MCP');let u=t.find(d=>d.name==="codex p-router");return u&&u.status==="error"&&n.push('Run "prjct start" or "prjct setup" to repair Codex p. router'),n}printHeader(){h.section(`prjct doctor v${Se}`)}printSection(e,t){h.section(e);let n=t.map(s=>{let o=this.getStatusIcon(s.status,s.optional),i=s.name.padEnd(14),a=s.version||s.message||"",c=s.optional&&s.status==="error"?Zn.dim(" (optional)"):"";return`${o} ${i} ${Zn.dim(a)}${c}`});for(let s of n)console.log(` ${s}`)}printRecommendations(e){h.section("Recommendations"),h.list(e,{bullet:Zn.yellow("\u2022")})}printSummary(e){console.log(""),console.log(Zn.dim("\u2500".repeat(40))),e.hasErrors?h.fail("Some required checks failed"):e.hasWarnings?h.warn("All required checks passed (some warnings)"):h.done("All checks passed"),console.log("")}getStatusIcon(e,t){switch(e){case"ok":return Zn.green("\u2713");case"warn":return Zn.yellow("\u26A0");case"error":return t?Zn.dim("\u25CB"):Zn.red("\u2717")}}},Tj=new cc});var ak={};Ce(ak,{WatchService:()=>lc,watchService:()=>Rj});import Ej from"node:path";import lt from"chalk";import Aj from"chokidar";var Ij,jj,lc,Rj,ck=y(()=>{"use strict";tt();N();le();Ua();Ij=["package.json","package-lock.json","bun.lockb","pnpm-lock.yaml","yarn.lock","tsconfig.json","tsconfig.*.json",".env",".env.*","Cargo.toml","go.mod","pyproject.toml","requirements.txt","src/**/*.ts","src/**/*.tsx","src/**/*.js","src/**/*.jsx","lib/**/*.ts","core/**/*.ts","app/**/*.ts","app/**/*.tsx","pages/**/*.ts","pages/**/*.tsx"],jj=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/coverage/**","**/*.log","**/*.tmp","**/CLAUDE.md","**/.cursorrules","**/.windsurfrules","**/.prjct/**","**/.prjct-cli/**"],lc=class{static{l(this,"WatchService")}watcher=null;projectPath="";projectId=null;debounceTimer=null;lastSyncTime=0;pendingChanges=new Set;options={debounceMs:2e3,minIntervalMs:3e4,verbose:!1,quiet:!1};isRunning=!1;syncCount=0;sigintHandler=null;sigtermHandler=null;async start(e=process.cwd(),t={}){return this.projectPath=e,this.options={...this.options,...t},this.projectId=await $.getProjectId(e),this.projectId?this.isRunning?{success:!1,error:"Watch mode is already running"}:(this.isRunning=!0,this.options.quiet||this.printStartup(),this.watcher=Aj.watch(Ij,{cwd:this.projectPath,ignored:jj,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}}),this.watcher.on("add",n=>this.handleChange("add",n)).on("change",n=>this.handleChange("change",n)).on("unlink",n=>this.handleChange("unlink",n)).on("error",n=>this.handleError(n)),this.sigintHandler&&process.off("SIGINT",this.sigintHandler),this.sigtermHandler&&process.off("SIGTERM",this.sigtermHandler),this.sigintHandler=()=>this.stop(),this.sigtermHandler=()=>this.stop(),process.on("SIGINT",this.sigintHandler),process.on("SIGTERM",this.sigtermHandler),{success:!0}):{success:!1,error:'No prjct project. Run "prjct init" first.'}}async stop(){this.options.quiet||(console.log(""),console.log(lt.dim(`
1650
1650
  \u{1F44B} Stopped watching (${this.syncCount} syncs performed)`))),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.watcher&&(await this.watcher.close(),this.watcher=null),this.sigintHandler&&(process.off("SIGINT",this.sigintHandler),this.sigintHandler=null),this.sigtermHandler&&(process.off("SIGTERM",this.sigtermHandler),this.sigtermHandler=null),this.pendingChanges.clear(),this.isRunning=!1,process.exit(0)}handleChange(e,t){if(this.pendingChanges.add(t),this.options.verbose&&!this.options.quiet){let n=e==="add"?"\u2795":e==="unlink"?"\u2796":"\u{1F4DD}";console.log(lt.dim(` ${n} ${t}`))}this.scheduleSyncIfNeeded()}scheduleSyncIfNeeded(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(async()=>{let t=Date.now()-this.lastSyncTime;if(t<this.options.minIntervalMs&&this.lastSyncTime>0){let n=this.options.minIntervalMs-t;this.options.verbose&&!this.options.quiet&&console.log(lt.dim(` \u23F3 Rate limited, waiting ${Math.round(n/1e3)}s...`)),this.debounceTimer=setTimeout(()=>this.performSync(),n);return}await this.performSync()},this.options.debounceMs)}async performSync(){let e=Array.from(this.pendingChanges);if(this.pendingChanges.clear(),e.length===0)return;let t=C().split("T")[1].split(".")[0];if(!this.options.quiet){let n=e.length===1?e[0]:`${e.length} files`;console.log(`
1651
1651
  ${lt.dim(`[${t}]`)} ${lt.cyan("\u27F3")} ${n} changed \u2192 syncing...`)}try{let n=await Sn.sync(this.projectPath,{changedFiles:e});if(this.lastSyncTime=Date.now(),this.syncCount++,n.success){if(!this.options.quiet){let s=n.agents.filter(i=>i.type==="domain").map(i=>i.name),o=s.length>0?` [${s.join(", ")}]`:"";console.log(`${lt.dim(`[${t}]`)} ${lt.green("\u2713")} Synced${o}`)}}else console.error(`${lt.dim(`[${t}]`)} ${lt.red("\u2717")} Sync failed: ${n.error}`)}catch(n){console.error(`${lt.dim(`[${t}]`)} ${lt.red("\u2717")} Error: ${w(n)}`)}}handleError(e){console.error(lt.red(`Watch error: ${e.message}`))}printStartup(){console.log(""),console.log(lt.cyan("\u{1F441}\uFE0F Watching for changes...")),console.log(lt.dim(` Project: ${Ej.basename(this.projectPath)}`)),console.log(lt.dim(` Debounce: ${this.options.debounceMs}ms`)),console.log(lt.dim(` Min interval: ${this.options.minIntervalMs/1e3}s`)),console.log(""),console.log(lt.dim(" Press Ctrl+C to stop")),console.log("")}},Rj=new lc});var fk={};Ce(fk,{formatAgentCommandHelp:()=>pk,formatCommandHelp:()=>mk,formatCommandList:()=>gk,formatMainHelp:()=>uk,formatTerminalCommandHelp:()=>dk,getHelp:()=>$j});import X from"chalk";function uk(){let r=[];r.push(""),r.push(`${X.cyan.bold("prjct")} v${Se} - Context layer for AI coding agents`),r.push(X.dim("Works with Claude Code, Gemini CLI, Cursor, Windsurf, and more.")),r.push(""),r.push(X.bold("QUICK START")),r.push(X.dim("\u2500".repeat(60))),r.push(` ${X.green("1.")} prjct start ${X.dim("# Configure AI providers")}`),r.push(` ${X.green("2.")} cd my-project && prjct init`),r.push(` ${X.green("3.")} Open in Claude Code / Gemini CLI / Cursor`),r.push(` ${X.green("4.")} p. sync ${X.dim("# Analyze project")}`),r.push(""),r.push(X.bold("TERMINAL COMMANDS")),r.push(X.dim("\u2500".repeat(60)));for(let t of lk){let n=`prjct ${t.name}`.padEnd(22);r.push(` ${n} ${t.description}`)}r.push(""),r.push(`${X.bold("AI AGENT COMMANDS")} ${X.dim("(inside Claude/Gemini/Cursor)")}`),r.push(X.dim("\u2500".repeat(60))),r.push(` ${"Command".padEnd(22)} Description`),r.push(` ${X.dim("\u2500".repeat(56))}`);let e=Rr.filter(t=>t.group==="core"&&t.usage?.claude);for(let t of e.slice(0,10)){let n=`p. ${t.name}`.padEnd(22);r.push(` ${n} ${t.description}`)}r.push(` ${X.dim(`... and ${e.length-10} more (run 'prjct help commands')`)}`),r.push(""),r.push(X.bold("FLAGS")),r.push(X.dim("\u2500".repeat(60)));for(let t of Dj)r.push(` ${t.flag.padEnd(22)} ${t.description}`);return r.push(""),r.push(X.bold("MORE INFO")),r.push(X.dim("\u2500".repeat(60))),r.push(` Documentation: ${X.cyan("https://prjct.app")}`),r.push(` GitHub: ${X.cyan("https://github.com/jlopezlira/prjct-cli")}`),r.push(" Per-command: prjct help <command>"),r.push(""),r.join(`
1652
1652
  `)}function dk(r){let e=lk.find(n=>n.name===r);if(!e)return null;let t=[];if(t.push(""),t.push(`${X.cyan.bold(`prjct ${e.name}`)} - ${e.description}`),t.push(""),t.push(X.bold("USAGE")),t.push(` ${e.example}`),t.push(""),e.options){t.push(X.bold("OPTIONS"));for(let n of e.options)t.push(` ${n}`);t.push("")}if(e.subcommands){t.push(X.bold("SUBCOMMANDS"));for(let n of e.subcommands)t.push(` ${n}`);t.push("")}return t.join(`
@@ -1656,7 +1656,7 @@ ${X.yellow(`Command '${r}' not found.`)}
1656
1656
 
1657
1657
  Run 'prjct help' to see all available commands.
1658
1658
  `}function gk(){let r=[];r.push(""),r.push(X.cyan.bold("All Commands")),r.push("");let e=Object.entries(Uo).sort((t,n)=>t[1].order-n[1].order);for(let[t,n]of e){let s=Rr.filter(o=>o.group===t);if(s.length!==0){r.push(`${X.bold(n.title)} ${X.dim(`(${s.length} commands)`)}`),r.push(X.dim(n.description)),r.push("");for(let o of s){let i=`p. ${o.name}`.padEnd(18),a=o.description.length>45?`${o.description.slice(0,42)}...`:o.description;r.push(` ${i} ${a}`)}r.push("")}}return r.push(X.dim("Run 'prjct help <command>' for detailed help on a specific command.")),r.push(""),r.join(`
1659
- `)}function $j(r){return r?r==="commands"||r==="all"?gk():mk(r):uk()}var lk,Dj,hk=y(()=>{"use strict";ip();pt();lk=[{name:"start",description:"First-time setup wizard",example:"prjct start"},{name:"init",description:"Initialize project in current directory",example:"prjct init"},{name:"sync",description:"Sync project state and update context files",example:"prjct sync"},{name:"watch",description:"Auto-sync on file changes",example:"prjct watch",options:["--verbose","--debounce=<ms>","--interval=<sec>"]},{name:"hooks",description:"Manage git hooks for auto-sync",example:"prjct hooks install",subcommands:["install","uninstall","status"]},{name:"doctor",description:"Check system health and dependencies",example:"prjct doctor"},{name:"serve",description:"Start web dashboard server",example:"prjct serve [port]"},{name:"context",description:"Smart context filtering tools for AI",example:'prjct context files "add auth"',subcommands:["files","signatures","imports","recent","summary"]},{name:"linear",description:"Linear issue tracker CLI",example:"prjct linear list",subcommands:["list","get","create","update"]},{name:"uninstall",description:"Complete system removal of prjct",example:"prjct uninstall --backup",options:["--force","--backup","--dry-run","--keep-package"]}],Dj=[{flag:"-q, --quiet",description:"Suppress all output (errors to stderr only)"},{flag:"-v, --version",description:"Show version and provider status"},{flag:"-h, --help",description:"Show this help message"}];l(uk,"formatMainHelp");l(dk,"formatTerminalCommandHelp");l(pk,"formatAgentCommandHelp");l(mk,"formatCommandHelp");l(gk,"formatCommandList");l($j,"getHelp")});var yk=Ik((b3,Mj)=>{Mj.exports={name:"prjct-cli",version:"1.38.0",description:"Context layer for AI agents. Project context for Claude Code, Gemini CLI, and more.",main:"dist/bin/prjct.mjs",bin:{prjct:"bin/prjct"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"},scripts:{build:"node scripts/build.js","build:node":"node scripts/build.js",release:"node scripts/release.js","release:patch":"node scripts/release.js patch","release:minor":"node scripts/release.js minor","release:major":"node scripts/release.js major",postinstall:"node scripts/postinstall.js",prepare:"lefthook install","update-commands":`bun -e "const installer = require('./core/infrastructure/command-installer'); installer.syncCommands().then(r => console.log('Commands updated:', r)).catch(e => console.error('Error:', e.message))"`,"install-global":"./scripts/install.sh",update:"./scripts/update.sh",test:"bun test","test:watch":"bun test --watch","test:coverage":"bun test --coverage",typecheck:"tsc --noEmit -p core/tsconfig.json","typecheck:watch":"tsc --noEmit -p core/tsconfig.json --watch",validate:"bun scripts/validate-commands.js",lint:"biome lint .","lint:fix":"biome lint --write .","lint:meta":"bun core/cli/lint-meta-commentary.ts",format:"biome format --write .","format:check":"biome format .",check:"biome check .","check:fix":"biome check --write ."},keywords:["claude-code","gemini-cli","ai-agents","context-layer","developer-tools","ai-assistant","productivity","mcp","llm","coding-agents"],author:"prjct.app",license:"MIT",dependencies:{"@clack/prompts":"^1.0.0","@hono/node-server":"^1.13.7","@linear/sdk":"^29.0.0","better-sqlite3":"^12.6.2",chalk:"^4.1.2",chokidar:"^5.0.0","date-fns":"^4.1.0",glob:"^13.0.1",hono:"^4.11.3","jsonc-parser":"^3.3.1",zod:"^3.24.1"},devDependencies:{"@biomejs/biome":"^2.3.13","@types/better-sqlite3":"^7.6.13","@types/bun":"latest","@types/chokidar":"^2.1.7",esbuild:"^0.25.0",lefthook:"^2.1.0",typescript:"^5.9.3"},repository:{type:"git",url:"git+https://github.com/jlopezlira/prjct-cli.git"},bugs:{url:"https://github.com/jlopezlira/prjct-cli/issues"},homepage:"https://prjct.app",packageManager:"bun@1.2.23",engines:{node:">=18.0.0",bun:">=1.0.0"},files:["assets/","bin/prjct","dist/","scripts/postinstall.js","scripts/install.sh","LICENSE","README.md","CHANGELOG.md"],prepublishOnly:"node scripts/build.js",trustedDependencies:["chalk"]}});var Gj={};import wk from"node:os";import uc from"node:path";import Le from"chalk";async function Oj(){let[r,...e]=process.argv.slice(2);if(["-v","--version","version"].includes(r)){let t=await Promise.resolve().then(()=>jk(yk()));await Hj(t.version),process.exit(0)}["-h","--help",void 0].includes(r)&&(Uj(),process.exit(0)),h.start();try{let t=W.getByName(r);if(!t){let d=Nj(r),m=d?`Did you mean 'prjct ${d}'? Run 'prjct --help' for all commands`:"Run 'prjct --help' to see available commands";h.failWithHint(cs("UNKNOWN_COMMAND",{message:`Unknown command: ${r}`,hint:m})),h.end(),process.exit(1)}if(t.deprecated){let d=t.replacedBy?`Use 'prjct ${t.replacedBy}' instead`:"Run 'prjct --help' to see available commands";h.failWithHint({message:`Command '${r}' is deprecated`,hint:d}),h.end(),process.exit(1)}t.implemented||(h.failWithHint({message:`Command '${r}' is not yet implemented`,hint:"Run 'prjct --help' to see available commands",docs:"https://github.com/jlopezlira/prjct-cli"}),h.end(),process.exit(1));let{parsedArgs:n,options:s}=Lj(t,e),o=Fj(t,n);o&&(h.failWithHint(o),h.end(),process.exit(1));let i=null,a=Date.now();try{i=await $.getProjectId(process.cwd()),i&&(await zn.expireIfStale(i),await zn.touch(i))}catch{}let c=new Mn,u;if(r==="design"){let d=n.join(" ");u=await c.design(d,s)}else if(r==="analyze")u=await c.analyze(s);else if(r==="cleanup")u=await c.cleanup(s);else if(r==="setup")u=await c.setup(s);else if(r==="update")u=await c.update(s);else{let d=n.join(" ")||null,m=s.md===!0,g={task:l(f=>c.task(f,process.cwd(),{md:m}),"task"),done:l(()=>c.done(process.cwd(),{md:m}),"done"),next:l(()=>c.next(process.cwd(),{md:m}),"next"),pause:l(f=>c.pause(f||"",process.cwd(),{md:m}),"pause"),resume:l(f=>c.resume(f,process.cwd(),{md:m}),"resume"),init:l(f=>c.init(f),"init"),bug:l(f=>c.bug(f||"",process.cwd(),{md:m}),"bug"),idea:l(f=>c.idea(f||"",process.cwd(),{md:m}),"idea"),spec:l(f=>c.spec(f),"spec"),ship:l(f=>c.ship(f,process.cwd(),{md:m}),"ship"),workflow:l(f=>c.workflowPrefs(f,process.cwd(),{md:m}),"workflow"),sessions:l(()=>c.sessions(process.cwd(),{md:m,cleanup:s.cleanup===!0}),"sessions"),dash:l(f=>c.dash(f||"default",process.cwd(),{md:m}),"dash"),stats:l(()=>c.stats(process.cwd(),{json:s.json===!0,export:s.export===!0}),"stats"),status:l(()=>c.status(process.cwd(),{json:s.json===!0,md:m}),"status"),help:l(f=>c.help(f||""),"help"),perf:l(f=>c.perf(f||"7"),"perf"),velocity:l(f=>c.velocity(f||"0"),"velocity"),recover:l(()=>c.recover(),"recover"),undo:l(()=>c.undo(),"undo"),redo:l(()=>c.redo(),"redo"),history:l(()=>c.history(),"history"),sync:l(()=>c.sync(process.cwd(),{aiTools:s.agents?String(s.agents).split(","):void 0,preview:s.preview===!0||s["dry-run"]===!0,yes:s.yes===!0,json:s.json===!0,md:m,package:s.package?String(s.package):void 0,full:s.full===!0}),"sync"),diff:l(()=>c.diff(process.cwd(),{json:s.json===!0,md:m}),"diff"),seal:l(()=>c.seal(process.cwd(),{json:s.json===!0}),"seal"),rollback:l(()=>c.rollback(process.cwd(),{json:s.json===!0,md:m}),"rollback"),verify:l(()=>c.verify(process.cwd(),{json:s.json===!0,semantic:s.semantic===!0}),"verify"),"analysis-payload":l(()=>c.analysisPayload(process.cwd(),{json:s.json===!0,md:m}),"analysis-payload"),"analysis-save-llm":l(f=>c.saveLlmAnalysis(f||"",process.cwd(),{md:m}),"analysis-save-llm"),"analysis-llm":l(()=>c.getLlmAnalysis(process.cwd(),{json:s.json===!0,md:m}),"analysis-llm"),start:l(()=>c.start(),"start"),context:l(f=>c.context(f),"context")}[r];if(g)u=await g(d);else throw new Error(`Command '${r}' has no handler`)}if(i){let d=Date.now()-a;try{await zn.trackCommand(i,r,d)}catch{}try{await ls.recordTiming(i,"command_duration",d,{command:r});let m=globalThis.__perfStartNs;if(m){let p=Number(process.hrtime.bigint()-m)/1e6;await ls.recordTiming(i,"startup_time",p)}await ls.recordMemory(i,{command:r})}catch{}}u?.message&&console.log(u.message),h.end(),process.exit(u?.success?0:1)}catch(t){console.error("Error:",w(t)),process.env.DEBUG&&console.error(Jo(t)),h.end(),process.exit(1)}}function Fj(r,e){if(!r.params)return null;let t=r.params.match(/<[^>]+>/g);if(!t||t.length===0)return null;if(e.length<t.length){let n=t.map(o=>o.slice(1,-1)).join(", "),s=r.usage.terminal||`prjct ${r.name} ${r.params}`;return cs("MISSING_PARAM",{message:`Missing required parameter: ${n}`,hint:`Usage: ${s}`})}return null}function Nj(r){let e=W.getAll().map(s=>s.name),t=null,n=1/0;for(let s of e){let o=_j(r.toLowerCase(),s.toLowerCase());o<n&&(n=o,t=s)}return n<=2?t:null}function _j(r,e){let t=r.length,n=e.length,s=Array.from({length:t+1},()=>Array(n+1).fill(0));for(let o=0;o<=t;o++)s[o][0]=o;for(let o=0;o<=n;o++)s[0][o]=o;for(let o=1;o<=t;o++)for(let i=1;i<=n;i++)s[o][i]=r[o-1]===e[i-1]?s[o-1][i-1]:1+Math.min(s[o-1][i],s[o][i-1],s[o-1][i-1]);return s[t][n]}function Lj(r,e){let t=[],n={};for(let s=0;s<e.length;s++){let o=e[s];if(o.startsWith("--")){let i=o.slice(2);s+1<e.length&&!e[s+1].startsWith("--")?n[i]=e[++s]:n[i]=!0}else t.push(o)}return{parsedArgs:t,options:n}}async function Hj(r){let e=await xn(),t=uc.join(wk.homedir(),".claude","commands","p.md"),n=uc.join(wk.homedir(),".gemini","commands","p.toml"),[s,o,i,a]=await Promise.all([P(t),P(n),P(uc.join(process.cwd(),".cursor","commands","sync.md")),P(uc.join(process.cwd(),".cursor"))]),c=await _s();if(console.log(`
1659
+ `)}function $j(r){return r?r==="commands"||r==="all"?gk():mk(r):uk()}var lk,Dj,hk=y(()=>{"use strict";ip();pt();lk=[{name:"start",description:"First-time setup wizard",example:"prjct start"},{name:"init",description:"Initialize project in current directory",example:"prjct init"},{name:"sync",description:"Sync project state and update context files",example:"prjct sync"},{name:"watch",description:"Auto-sync on file changes",example:"prjct watch",options:["--verbose","--debounce=<ms>","--interval=<sec>"]},{name:"hooks",description:"Manage git hooks for auto-sync",example:"prjct hooks install",subcommands:["install","uninstall","status"]},{name:"doctor",description:"Check system health and dependencies",example:"prjct doctor"},{name:"serve",description:"Start web dashboard server",example:"prjct serve [port]"},{name:"context",description:"Smart context filtering tools for AI",example:'prjct context files "add auth"',subcommands:["files","signatures","imports","recent","summary"]},{name:"linear",description:"Linear issue tracker CLI",example:"prjct linear list",subcommands:["list","get","create","update"]},{name:"uninstall",description:"Complete system removal of prjct",example:"prjct uninstall --backup",options:["--force","--backup","--dry-run","--keep-package"]}],Dj=[{flag:"-q, --quiet",description:"Suppress all output (errors to stderr only)"},{flag:"-v, --version",description:"Show version and provider status"},{flag:"-h, --help",description:"Show this help message"}];l(uk,"formatMainHelp");l(dk,"formatTerminalCommandHelp");l(pk,"formatAgentCommandHelp");l(mk,"formatCommandHelp");l(gk,"formatCommandList");l($j,"getHelp")});var yk=Ik((b3,Mj)=>{Mj.exports={name:"prjct-cli",version:"1.38.2",description:"Context layer for AI agents. Project context for Claude Code, Gemini CLI, and more.",main:"dist/bin/prjct.mjs",bin:{prjct:"bin/prjct"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"},scripts:{build:"node scripts/build.js","build:node":"node scripts/build.js",release:"node scripts/release.js","release:patch":"node scripts/release.js patch","release:minor":"node scripts/release.js minor","release:major":"node scripts/release.js major",postinstall:"node scripts/postinstall.js",prepare:"lefthook install","update-commands":`bun -e "const installer = require('./core/infrastructure/command-installer'); installer.syncCommands().then(r => console.log('Commands updated:', r)).catch(e => console.error('Error:', e.message))"`,"install-global":"./scripts/install.sh",update:"./scripts/update.sh",test:"bun test","test:watch":"bun test --watch","test:coverage":"bun test --coverage",typecheck:"tsc --noEmit -p core/tsconfig.json","typecheck:watch":"tsc --noEmit -p core/tsconfig.json --watch",validate:"bun scripts/validate-commands.js",lint:"biome lint .","lint:fix":"biome lint --write .","lint:meta":"bun core/cli/lint-meta-commentary.ts",format:"biome format --write .","format:check":"biome format .",check:"biome check .","check:fix":"biome check --write ."},keywords:["claude-code","gemini-cli","ai-agents","context-layer","developer-tools","ai-assistant","productivity","mcp","llm","coding-agents"],author:"prjct.app",license:"MIT",dependencies:{"@clack/prompts":"^1.0.0","@hono/node-server":"^1.13.7","@linear/sdk":"^29.0.0","better-sqlite3":"^12.6.2",chalk:"^4.1.2",chokidar:"^5.0.0","date-fns":"^4.1.0",glob:"^13.0.1",hono:"^4.11.3","jsonc-parser":"^3.3.1",zod:"^3.24.1"},devDependencies:{"@biomejs/biome":"^2.3.13","@types/better-sqlite3":"^7.6.13","@types/bun":"latest","@types/chokidar":"^2.1.7",esbuild:"^0.25.0",lefthook:"^2.1.0",typescript:"^5.9.3"},repository:{type:"git",url:"git+https://github.com/jlopezlira/prjct-cli.git"},bugs:{url:"https://github.com/jlopezlira/prjct-cli/issues"},homepage:"https://prjct.app",packageManager:"bun@1.2.23",engines:{node:">=18.0.0",bun:">=1.0.0"},files:["assets/","bin/prjct","dist/","scripts/postinstall.js","scripts/install.sh","LICENSE","README.md","CHANGELOG.md"],prepublishOnly:"node scripts/build.js",trustedDependencies:["chalk"]}});var Gj={};import wk from"node:os";import uc from"node:path";import Le from"chalk";async function Oj(){let[r,...e]=process.argv.slice(2);if(["-v","--version","version"].includes(r)){let t=await Promise.resolve().then(()=>jk(yk()));await Hj(t.version),process.exit(0)}["-h","--help",void 0].includes(r)&&(Uj(),process.exit(0)),h.start();try{let t=W.getByName(r);if(!t){let d=Nj(r),m=d?`Did you mean 'prjct ${d}'? Run 'prjct --help' for all commands`:"Run 'prjct --help' to see available commands";h.failWithHint(cs("UNKNOWN_COMMAND",{message:`Unknown command: ${r}`,hint:m})),h.end(),process.exit(1)}if(t.deprecated){let d=t.replacedBy?`Use 'prjct ${t.replacedBy}' instead`:"Run 'prjct --help' to see available commands";h.failWithHint({message:`Command '${r}' is deprecated`,hint:d}),h.end(),process.exit(1)}t.implemented||(h.failWithHint({message:`Command '${r}' is not yet implemented`,hint:"Run 'prjct --help' to see available commands",docs:"https://github.com/jlopezlira/prjct-cli"}),h.end(),process.exit(1));let{parsedArgs:n,options:s}=Lj(t,e),o=Fj(t,n);o&&(h.failWithHint(o),h.end(),process.exit(1));let i=null,a=Date.now();try{i=await $.getProjectId(process.cwd()),i&&(await zn.expireIfStale(i),await zn.touch(i))}catch{}let c=new Mn,u;if(r==="design"){let d=n.join(" ");u=await c.design(d,s)}else if(r==="analyze")u=await c.analyze(s);else if(r==="cleanup")u=await c.cleanup(s);else if(r==="setup")u=await c.setup(s);else if(r==="update")u=await c.update(s);else{let d=n.join(" ")||null,m=s.md===!0,g={task:l(f=>c.task(f,process.cwd(),{md:m}),"task"),done:l(()=>c.done(process.cwd(),{md:m}),"done"),next:l(()=>c.next(process.cwd(),{md:m}),"next"),pause:l(f=>c.pause(f||"",process.cwd(),{md:m}),"pause"),resume:l(f=>c.resume(f,process.cwd(),{md:m}),"resume"),init:l(f=>c.init(f),"init"),bug:l(f=>c.bug(f||"",process.cwd(),{md:m}),"bug"),idea:l(f=>c.idea(f||"",process.cwd(),{md:m}),"idea"),spec:l(f=>c.spec(f),"spec"),ship:l(f=>c.ship(f,process.cwd(),{md:m}),"ship"),workflow:l(f=>c.workflowPrefs(f,process.cwd(),{md:m}),"workflow"),sessions:l(()=>c.sessions(process.cwd(),{md:m,cleanup:s.cleanup===!0}),"sessions"),dash:l(f=>c.dash(f||"default",process.cwd(),{md:m}),"dash"),stats:l(()=>c.stats(process.cwd(),{json:s.json===!0,export:s.export===!0}),"stats"),status:l(()=>c.status(process.cwd(),{json:s.json===!0,md:m}),"status"),help:l(f=>c.help(f||""),"help"),perf:l(f=>c.perf(f||"7"),"perf"),velocity:l(f=>c.velocity(f||"0"),"velocity"),recover:l(()=>c.recover(),"recover"),undo:l(()=>c.undo(),"undo"),redo:l(()=>c.redo(),"redo"),history:l(()=>c.history(),"history"),sync:l(()=>c.sync(process.cwd(),{aiTools:s.agents?String(s.agents).split(","):void 0,preview:s.preview===!0||s["dry-run"]===!0,yes:s.yes===!0,json:s.json===!0,md:m,package:s.package?String(s.package):void 0,full:s.full===!0}),"sync"),diff:l(()=>c.diff(process.cwd(),{json:s.json===!0,md:m}),"diff"),seal:l(()=>c.seal(process.cwd(),{json:s.json===!0}),"seal"),rollback:l(()=>c.rollback(process.cwd(),{json:s.json===!0,md:m}),"rollback"),verify:l(()=>c.verify(process.cwd(),{json:s.json===!0,semantic:s.semantic===!0}),"verify"),"analysis-payload":l(()=>c.analysisPayload(process.cwd(),{json:s.json===!0,md:m}),"analysis-payload"),"analysis-save-llm":l(f=>c.saveLlmAnalysis(f||"",process.cwd(),{md:m}),"analysis-save-llm"),"analysis-llm":l(()=>c.getLlmAnalysis(process.cwd(),{json:s.json===!0,md:m}),"analysis-llm"),start:l(()=>c.start(),"start"),context:l(f=>c.context(f),"context")}[r];if(g)u=await g(d);else throw new Error(`Command '${r}' has no handler`)}if(i){let d=Date.now()-a;try{await zn.trackCommand(i,r,d)}catch{}try{await ls.recordTiming(i,"command_duration",d,{command:r});let m=globalThis.__perfStartNs;if(m){let p=Number(process.hrtime.bigint()-m)/1e6;await ls.recordTiming(i,"startup_time",p)}await ls.recordMemory(i,{command:r})}catch{}}u?.message&&console.log(u.message),h.end(),process.exit(u?.success?0:1)}catch(t){console.error("Error:",w(t)),process.env.DEBUG&&console.error(Jo(t)),h.end(),process.exit(1)}}function Fj(r,e){if(!r.params)return null;let t=r.params.match(/<[^>]+>/g);if(!t||t.length===0)return null;if(e.length<t.length){let n=t.map(o=>o.slice(1,-1)).join(", "),s=r.usage.terminal||`prjct ${r.name} ${r.params}`;return cs("MISSING_PARAM",{message:`Missing required parameter: ${n}`,hint:`Usage: ${s}`})}return null}function Nj(r){let e=W.getAll().map(s=>s.name),t=null,n=1/0;for(let s of e){let o=_j(r.toLowerCase(),s.toLowerCase());o<n&&(n=o,t=s)}return n<=2?t:null}function _j(r,e){let t=r.length,n=e.length,s=Array.from({length:t+1},()=>Array(n+1).fill(0));for(let o=0;o<=t;o++)s[o][0]=o;for(let o=0;o<=n;o++)s[0][o]=o;for(let o=1;o<=t;o++)for(let i=1;i<=n;i++)s[o][i]=r[o-1]===e[i-1]?s[o-1][i-1]:1+Math.min(s[o-1][i],s[o][i-1],s[o-1][i-1]);return s[t][n]}function Lj(r,e){let t=[],n={};for(let s=0;s<e.length;s++){let o=e[s];if(o.startsWith("--")){let i=o.slice(2);s+1<e.length&&!e[s+1].startsWith("--")?n[i]=e[++s]:n[i]=!0}else t.push(o)}return{parsedArgs:t,options:n}}async function Hj(r){let e=await xn(),t=uc.join(wk.homedir(),".claude","commands","p.md"),n=uc.join(wk.homedir(),".gemini","commands","p.toml"),[s,o,i,a]=await Promise.all([P(t),P(n),P(uc.join(process.cwd(),".cursor","commands","sync.md")),P(uc.join(process.cwd(),".cursor"))]),c=await _s();if(console.log(`
1660
1660
  ${Le.cyan("p/")} prjct v${r}
1661
1661
  ${Le.dim("Context layer for AI coding agents")}
1662
1662
 
@@ -1157,7 +1157,7 @@ Domain specialist for ${r} tasks.
1157
1157
  You are the ${r} expert for this project. Apply best practices for the detected stack.
1158
1158
  `}function Nf(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 Et.writeFile(Ct.join(t,"config","skills.json"),JSON.stringify(s,null,2),"utf-8").catch(o=>{U.debug("Failed to write skills.json",{error:Y(o)})}),n}async function Lf(r){let e=[];try{let t=Ct.join(__dirname,"..","..","templates","config","skill-mappings.json"),n=await Et.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=Ct.join(ux.homedir(),".claude","skills");for(let{pkg:c,agent:u}of i){let d=c.split("/").pop()||c,m=Ct.join(a,d,"SKILL.md"),p=Ct.join(a,`${d}.md`),g=!1;try{await Et.access(m),g=!0}catch{try{await Et.access(p),g=!0}catch{}}if(g){e.push({name:d,agent:u,status:"skipped"});continue}try{let f=c.split("/"),k;f.length===3?k=`${f[0]}/${f[1]}@${f[2]}`:k=c;let S=await $f.install(k);S.installed.length>0?(e.push({name:d,agent:u,status:"installed"}),U.info(`Installed skill: ${d} for agent: ${u}`)):S.errors.length>0?(e.push({name:d,agent:u,status:"error"}),U.debug(`Failed to install skill ${d}`,{errors:S.errors})):e.push({name:d,agent:u,status:"skipped"})}catch(f){e.push({name:d,agent:u,status:"error"}),U.debug(`Skill install error for ${d}`,{error:Y(f)})}}}catch(t){U.debug("Skill auto-installation failed (non-critical)",{error:Y(t)})}return e}var Uf=w(()=>{"use strict";Jt();rn();oe();vn();Mf();l(Of,"generateAgents");l(Ff,"loadExistingAgents");l(_f,"resolveTemplateIncludes");l(dx,"generateWorkflowAgent");l(px,"generateDomainAgent");l(mx,"injectFeedbackSection");l(gx,"generateMinimalWorkflowAgent");l(fx,"generateMinimalDomainAgent");l(Nf,"configureSkills");l(Lf,"autoInstallSkills")});import Hf from"node:fs/promises";import Gf from"node:path";var Mi,zf=w(()=>{"use strict";Mi=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=Gf.join(this.projectPath,"package.json"),t=await Hf.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async fileExists(e){try{return await Hf.access(Gf.join(this.projectPath,e)),!0}catch{return!1}}}});import{exec as hx}from"node:child_process";import Wf from"node:fs/promises";import su from"node:path";import{promisify as yx}from"node:util";async function Vf(r){let e={branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0};try{let{stdout:t}=await ss("git branch --show-current",{cwd:r});e.branch=t.trim()||"main";let{stdout:n}=await ss("git rev-list --count HEAD",{cwd:r});e.commits=parseInt(n.trim(),10)||0;let{stdout:s}=await ss("git shortlog -sn --all | wc -l",{cwd:r});e.contributors=parseInt(s.trim(),10)||0;let{stdout:o}=await ss("git status --porcelain",{cwd:r}),i=o.trim().split(`
1159
1159
  `).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 ss('git log --oneline -20 --pretty=format:"%h|%s|%ad" --date=short',{cwd:r});e.recentCommits=a.split(`
1160
- `).filter(Boolean).map(u=>{let[d,m,p]=u.split("|");return{hash:d,message:m,date:p}});let{stdout:c}=await ss('git log --oneline --since="1 week ago" | wc -l',{cwd:r});e.weeklyCommits=parseInt(c.trim(),10)||0}catch(t){U.debug("Git analysis failed (not a git repo?)",{error:Y(t)})}return e}async function en(r,e){try{return await Wf.access(su.join(r,e)),!0}catch(t){return U.debug("File not found",{filename:e,error:Y(t)}),!1}}async function Bf(r){let e={fileCount:0,version:"0.0.0",name:su.basename(r),ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]};try{let{stdout:t}=await ss('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){U.debug("File count failed",{path:r,error:Y(t)}),e.fileCount=0}try{let t=su.join(r,"package.json"),n=JSON.parse(await Wf.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 en(r,"tsconfig.json")?e.languages.push("TypeScript"):e.languages.push("JavaScript")}catch(t){U.debug("No package.json found",{path:r,error:Y(t)})}return await en(r,"Cargo.toml")&&(e.ecosystem="Rust",e.languages.push("Rust")),await en(r,"go.mod")&&(e.ecosystem="Go",e.languages.push("Go")),(await en(r,"requirements.txt")||await en(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 Jf(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 en(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 en(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 en(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 en(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 en(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 qf(r,e){let t=ns(),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 Kf(r){return new Mi(r).detect()}var ss,Xf=w(()=>{"use strict";rn();Wl();vn();zf();ss=yx(hx);l(Vf,"analyzeGit");l(en,"fileExists");l(Bf,"gatherStats");l(Jf,"detectCommands");l(qf,"buildSources");l(Kf,"detectStack")});import{exec as wx}from"node:child_process";import ru from"node:fs/promises";import Oi from"node:path";import{promisify as kx}from"node:util";var Sx,ou,iu,Yf,Qf=w(()=>{"use strict";Xt();F();Sx=kx(wx),ou={async contextFilesExist(r){let e=Date.now(),t=["context/CLAUDE.md"],n=[];for(let s of t){let o=Oi.join(r,s);try{await ru.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=Oi.basename(r);try{await _.read(n)}catch(s){P(s)||t.push(`state: ${y(s)}`)}return{name:"State data valid",passed:t.length===0,output:t.length===0?"1 store validated":void 0,error:t.length>0?t.join("; "):void 0,durationMs:Date.now()-e}},async noSensitiveData(r){let e=Date.now(),t=Oi.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 ru.readdir(t);for(let i of o){if(!i.endsWith(".md"))continue;let a=await ru.readFile(Oi.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(!P(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}}},iu=class{static{l(this,"SyncVerifier")}async verify(e,t,n){let s=Date.now(),o=[],i=n?.failFast??!1,a=0,c=[ou.contextFilesExist(t),ou.jsonFilesValid(t),ou.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(k=>k.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 Sx(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}}}},Yf=new iu});import Fi from"node:fs/promises";import _i from"node:path";var Ni,En,au=w(()=>{"use strict";ms();Ol();Gg();Vg();Kg();_l();rn();Ze();Sn();wt();we();Ri();Pr();Cn();ne();vr();Yo();Zo();Tr();Er();xs();bf();Pf();oe();vn();Yc();Qc();Ss();Tf();gc();bc();Uf();Xf();Qf();Ni=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 i=await $i(e),a=i.filter(u=>$s.includes(u)||u==="codex"),c=i.filter(u=>!$s.includes(u)&&u!=="codex");s=[...a.length>0?a:$s,...c],s=Array.from(new Set(s))}else t.aiTools[0]==="auto"?(s=await $i(e),s.length===0&&(s=["claude"])):t.aiTools[0]==="all"?s=await gf("all",e):s=t.aiTools;let o={installed:!1,verified:!1,configPath:"",message:""};try{if(this.projectId=await $.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:[],context7:{installed:!1,verified:!1},error:"No prjct project. Run p. init first."};if((await Mn()).installed){let O=await Ii();if(!O.verified)return{success:!1,projectId:this.projectId,cliVersion:"",git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),agents:[],skills:[],skillsInstalled:[],contextFiles:[],aiTools:[],context7:{installed:!1,verified:!1},error:`Codex p. router is required but not ready: ${O.message||"verification failed"}. Run 'prjct start' or 'prjct setup' to repair.`}}try{o=await on.ensureReady()}catch(O){return{success:!1,projectId:this.projectId,cliVersion:"",git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),agents:[],skills:[],skillsInstalled:[],contextFiles:[],aiTools:[],context7:{installed:o.installed,verified:!1,message:Y(O)},error:`Context7 MCP is required but not ready: ${Y(O)}. Run 'prjct start' to repair.`}}this.globalPath=x.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await this.ensureDirectories(),await xr(this.projectId);try{let O=await Qo(this.projectId);O>0&&U.info("Swept legacy JSON files into SQLite",{swept:O})}catch(O){U.debug("Legacy JSON sweep failed (non-critical)",{error:Y(O)})}let[c,u,d,m]=await Promise.all([Vf(this.projectPath),Bf(this.projectPath),Jf(this.projectPath),Kf(this.projectPath)]),p=t.full===!0,g,f=!0,k=!0,S=new Set;if(!p&&Wg(this.projectId))try{let{diff:O,currentHashes:Yh}=await Ul(this.projectPath,this.projectId),Ou=O.added.length+O.modified.length+O.deleted.length;if(Ou===0&&!t.changedFiles?.length)f=!1,k=!1,g={isIncremental:!0,filesChanged:0,filesUnchanged:O.unchanged.length,indexesRebuilt:!1,agentsRegenerated:!1,affectedDomains:[]};else{let oa=Ug(O,this.projectId);S=Hg(oa.allAffected);let Qh=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);f=oa.allAffected.some(Rn=>{let Zh=Rn.substring(Rn.lastIndexOf("."));return Qh.has(Zh)}),k=oa.directlyChanged.some(Rn=>Rn==="package.json"||Rn==="tsconfig.json"||Rn.includes("Dockerfile")||Rn.includes("docker-compose")),g={isIncremental:!0,filesChanged:Ou,filesUnchanged:O.unchanged.length,indexesRebuilt:f,agentsRegenerated:k,affectedDomains:Array.from(S)}}Ll(this.projectId,Yh)}catch(O){U.debug("Incremental detection failed, falling back to full sync",{error:Y(O)})}else try{let{currentHashes:O}=await Ul(this.projectPath,this.projectId);Ll(this.projectId,O)}catch(O){U.debug("Hash computation failed (non-critical)",{error:Y(O)})}if(f)try{await Promise.all([Mg(this.projectPath,this.projectId),Lg(this.projectPath,this.projectId),qg(this.projectPath,this.projectId)])}catch(O){U.debug("File ranking index build failed (non-critical)",{error:Y(O)})}let I;if(k)try{let O=await _.getAggregatedFeedback(this.projectId);(O.patternsDiscovered.length>0||O.knownGotchas.length>0||O.agentAccuracy.length>0)&&(I=O)}catch{}let D=k?await Of(this.globalPath,m,u,I):await Ff(this.globalPath),B=Nf(D,this.projectId,this.globalPath),Pe=k?await Lf(D):[],$e=qf(u,d),Be=[],C;try{let O=await He.getActive(this.projectId);(O?.patterns?.length||O?.antiPatterns?.length)&&(C={patterns:O.patterns??[],antiPatterns:O.antiPatterns??[],packageManager:O.packageManager,sourceDir:O.sourceDir,testDir:O.testDir})}catch{}let j;try{j=await Cf(this.projectId)}catch{}let Re={projectId:this.projectId,name:u.name,version:u.version,ecosystem:u.ecosystem,projectType:u.projectType,languages:u.languages,frameworks:u.frameworks,repoPath:this.projectPath,branch:c.branch,fileCount:u.fileCount,commits:c.commits,hasChanges:c.hasChanges,commands:d,agents:{workflow:D.filter(O=>O.type==="workflow").map(O=>O.name),domain:D.filter(O=>O.type==="domain").map(O=>O.name)},sources:$e,analysis:C,learnings:j},tr=await kf(Re,this.globalPath,this.projectPath,s);await Promise.all([this.updateProjectJson(c,u),this.updateStateJson(u,m),this.logToMemory(c,u),this.saveDraftAnalysis(c,u,m,o.verified)]);let nr=await He.getActive(this.projectId),Ht={patterns:nr?.patterns?.length||0,antiPatterns:nr?.antiPatterns?.length||0,criticalAntiPatterns:nr?.antiPatterns?.filter(O=>O.severity==="high").length||0},Kh=Date.now()-n,Xh=await this.recordSyncMetrics(u,Be,D,Kh);await this.archiveStaleData(),await this.autoLearnFromHistory(),await ve.installGlobalConfig(),await ve.syncCommands();let Mu;try{let O=await $.readConfig(this.projectPath);Mu=await Yf.verify(this.projectPath,this.globalPath,O?.verification)}catch(O){U.debug("Verification failed (non-critical)",{error:Y(O)})}return{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:c,stats:u,commands:d,stack:m,agents:D,skills:B,skillsInstalled:Pe,contextFiles:Be,aiTools:tr.map(O=>({toolId:O.toolId,outputFile:O.outputFile,success:O.success})),context7:{installed:o.installed,verified:o.verified,message:o.message},analysisSummary:Ht,syncMetrics:Xh,verification:Mu,incremental:g}}catch(i){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:[],context7:{installed:o.installed,verified:o.verified,message:o.message},error:Y(i)}}}async ensureDirectories(){let e=["storage","context","agents","memory","analysis","config","sync"];await Promise.all(e.map(t=>Fi.mkdir(_i.join(this.globalPath,t),{recursive:!0})))}async updateProjectJson(e,t){let n=A.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};A.setDoc(this.projectId,"project",s)}async updateStateJson(e,t){let s={...await _.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 _.write(this.projectId,s);try{await xf.generate(this.projectPath,s)}catch(o){U.debug("Local state generation failed (optional)",{error:Y(o)})}}async logToMemory(e,t){A.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=_i.join(this.globalPath,m),g=await Fi.readFile(p,"utf-8");i+=g.length}catch(p){U.debug("Context file not found for metrics",{file:m,error:Y(p)})}for(let m of n)try{let p=_i.join(this.globalPath,"agents",`${m.name}.md`),g=await Fi.readFile(p,"utf-8");i+=g.length}catch(p){U.debug("Agent file not found for metrics",{agent:m.name,error:Y(p)})}let a=Math.floor(i/4),u=e.fileCount*500,d=u>0?Math.max(0,(u-a)/u):0;try{await Wn.recordSync(this.projectId,{originalSize:u,filteredSize:a,duration:s,isWatch:!1,agents:n.filter(m=>m.type==="domain").map(m=>m.name)})}catch(m){U.debug("Failed to record sync metrics",{error:Y(m)})}return{duration:s,originalSize:u,filteredSize:a,compressionRate:d}}async saveDraftAnalysis(e,t,n,s){try{let o=e.recentCommits[0]?.hash||null,i=[],a=[],c;try{c=await _.getAggregatedFeedback(this.projectId),c.patternsDiscovered.length>0&&(i=c.patternsDiscovered.map(d=>({name:d,description:`Discovered during task execution: ${d}`,source:"feedback",confidence:.74}))),c.knownGotchas.length>0&&(a=c.knownGotchas.map(d=>({issue:d,file:"multiple",suggestion:`Recurring issue reported across tasks: ${d}`,source:"feedback",severity:"medium",confidence:.7})))}catch{}let u=await Mp.extract({projectId:this.projectId,projectPath:this.projectPath,languages:t.languages,frameworks:Array.from(new Set([...t.frameworks,...n.frameworks])),feedback:c,context7Verified:s});i=u.patterns,a=u.antiPatterns,await He.saveDraft(this.projectId,{projectId:this.projectId,languages:t.languages,frameworks:t.frameworks,configFiles:[],fileCount:t.fileCount,patterns:i,antiPatterns:a,analyzedAt:b(),status:"draft",commitHash:o??void 0})}catch(o){U.debug("Failed to save draft analysis (non-critical)",{error:Y(o)})}}async archiveStaleData(){if(this.projectId)try{let[e,t,n,s,o]=await Promise.all([ut.archiveOldShipped(this.projectId).catch(()=>0),qe.markDormantIdeas(this.projectId).catch(()=>0),xe.removeStaleCompleted(this.projectId).catch(()=>0),_.archiveStalePausedTasks(this.projectId).catch(()=>[]),lt.capEntries(this.projectId).catch(()=>0)]),i=e+t+n+s.length+o;if(i>0){U.info("Archived stale data",{shipped:e,dormant:t,staleQueue:n,stalePaused:s.length,memoryCapped:o,total:i});let a=kt.getStats(this.projectId);U.debug("Archive stats",a)}}catch(e){U.debug("Archival failed (non-critical)",{error:Y(e)})}}async autoLearnFromHistory(){if(this.projectId)try{let e=await _.getTaskHistory(this.projectId);if(e.length===0)return;let t=new Fn,n=await Xc.learnFromTaskHistory(this.projectId,e,t);try{let s=await sm.getFeatureOutcomes(this.projectId);s.length>0&&await Xc.learnFromOutcomes(this.projectId,s,t)}catch{}n.memoriesInjected>0&&U.info("Auto-learned from task history",{patternsExtracted:n.patternsExtracted,memoriesInjected:n.memoriesInjected,patternsSkipped:n.patternsSkipped})}catch(e){U.debug("Auto-learning failed (non-critical)",{error:Y(e)})}}async getCliVersion(){try{let e=_i.join(__dirname,"..","..","package.json");return JSON.parse(await Fi.readFile(e,"utf-8")).version||"0.0.0"}catch(e){return U.debug("Failed to read CLI version",{error:Y(e)}),"0.0.0"}}emptyGitData(){return{branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0}}emptyStats(){return{fileCount:0,version:"0.0.0",name:"unknown",ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]}}emptyCommands(){return{install:"npm install",run:"npm run",test:"npm test",build:"npm run build",dev:"npm run dev",lint:"npm run lint",format:"npm run format"}}emptyStack(){return{hasFrontend:!1,hasBackend:!1,hasDatabase:!1,hasDocker:!1,hasTesting:!1,frontendType:null,frameworks:[]}}},En=new Ni});import{exec as bx}from"node:child_process";import Ms from"node:path";import{promisify as Cx}from"node:util";function eh(r){return/^\d+\.\d+\.\d+/.test(r)}function Os(r){let e=r.match(/^(\d+)\.(\d+)\.(\d+)/);if(!e)return r;let[,t,n,s]=e;return`${t}.${n}.${Number(s)+1}`}function Px(r){let e=r.match(/\[package\]([\s\S]*?)(?=\n\[|\n*$)/);return e?e[1].match(/^\s*version\s*=\s*"([^"]+)"/m)?.[1]??null:null}function vx(r){let e=r.match(/\[project\]([\s\S]*?)(?=\n\[|\n*$)/);if(e){let n=e[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}let t=r.match(/\[tool\.poetry\]([\s\S]*?)(?=\n\[|\n*$)/);if(t){let n=t[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}return null}function xx(r){return r.match(/<Version>([^<]+)<\/Version>/)?.[1]?.trim()??null}var Zf,Br,th=w(()=>{"use strict";Me();Zf=Cx(bx),Br=class{static{l(this,"VersionService")}projectPath;constructor(e){this.projectPath=e}async detect(){let e=[()=>this.fromPackageJson(),()=>this.fromCargoToml(),()=>this.fromPyprojectToml(),()=>this.fromCsproj(),()=>this.fromVersionFile("VERSION"),()=>this.fromVersionFile("version.txt"),()=>this.fromGitTag()];for(let t of e){let n=await t();if(n)return n}return this.createFallbackVersion()}async bump(){let e=await this.detect();return await this.writeVersion(e),e.next}async fromPackageJson(){let e=Ms.join(this.projectPath,"package.json"),t=await Gt(e,null);return t?.version?{current:t.version,next:Os(t.version),file:e,format:"json"}:null}async fromCargoToml(){let e=Ms.join(this.projectPath,"Cargo.toml"),t=await Qe(e,"");if(!t)return null;let n=Px(t);return n?{current:n,next:Os(n),file:e,format:"toml"}:null}async fromPyprojectToml(){let e=Ms.join(this.projectPath,"pyproject.toml"),t=await Qe(e,"");if(!t)return null;let n=vx(t);return n?{current:n,next:Os(n),file:e,format:"toml"}:null}async fromCsproj(){let e=await sn(this.projectPath,{extension:".csproj"});if(e.length===0)return null;let t=Ms.join(this.projectPath,e[0]),n=await Qe(t,"");if(!n)return null;let s=xx(n);return s?{current:s,next:Os(s),file:t,format:"xml"}:null}async fromVersionFile(e){let t=Ms.join(this.projectPath,e),n=await Qe(t,"");if(!n)return null;let s=n.trim();return eh(s)?{current:s,next:Os(s),file:t,format:"plaintext"}:null}async fromGitTag(){try{let{stdout:e}=await Zf("git tag --sort=-v:refname",{cwd:this.projectPath}),t=e.trim().split(`
1160
+ `).filter(Boolean).map(u=>{let[d,m,p]=u.split("|");return{hash:d,message:m,date:p}});let{stdout:c}=await ss('git log --oneline --since="1 week ago" | wc -l',{cwd:r});e.weeklyCommits=parseInt(c.trim(),10)||0}catch(t){U.debug("Git analysis failed (not a git repo?)",{error:Y(t)})}return e}async function en(r,e){try{return await Wf.access(su.join(r,e)),!0}catch(t){return U.debug("File not found",{filename:e,error:Y(t)}),!1}}async function Bf(r){let e={fileCount:0,version:"0.0.0",name:su.basename(r),ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]};try{let{stdout:t}=await ss('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){U.debug("File count failed",{path:r,error:Y(t)}),e.fileCount=0}try{let t=su.join(r,"package.json"),n=JSON.parse(await Wf.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 en(r,"tsconfig.json")?e.languages.push("TypeScript"):e.languages.push("JavaScript")}catch(t){U.debug("No package.json found",{path:r,error:Y(t)})}return await en(r,"Cargo.toml")&&(e.ecosystem="Rust",e.languages.push("Rust")),await en(r,"go.mod")&&(e.ecosystem="Go",e.languages.push("Go")),(await en(r,"requirements.txt")||await en(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 Jf(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 en(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 en(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 en(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 en(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 en(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 qf(r,e){let t=ns(),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 Kf(r){return new Mi(r).detect()}var ss,Xf=w(()=>{"use strict";rn();Wl();vn();zf();ss=yx(hx);l(Vf,"analyzeGit");l(en,"fileExists");l(Bf,"gatherStats");l(Jf,"detectCommands");l(qf,"buildSources");l(Kf,"detectStack")});import{exec as wx}from"node:child_process";import ru from"node:fs/promises";import Oi from"node:path";import{promisify as kx}from"node:util";var Sx,ou,iu,Yf,Qf=w(()=>{"use strict";Xt();F();Sx=kx(wx),ou={async contextFilesExist(r){let e=Date.now(),t=["context/CLAUDE.md"],n=[];for(let s of t){let o=Oi.join(r,s);try{await ru.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=Oi.basename(r);try{await _.read(n)}catch(s){P(s)||t.push(`state: ${y(s)}`)}return{name:"State data valid",passed:t.length===0,output:t.length===0?"1 store validated":void 0,error:t.length>0?t.join("; "):void 0,durationMs:Date.now()-e}},async noSensitiveData(r){let e=Date.now(),t=Oi.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 ru.readdir(t);for(let i of o){if(!i.endsWith(".md"))continue;let a=await ru.readFile(Oi.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(!P(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}}},iu=class{static{l(this,"SyncVerifier")}async verify(e,t,n){let s=Date.now(),o=[],i=n?.failFast??!1,a=0,c=[ou.contextFilesExist(t),ou.jsonFilesValid(t),ou.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(k=>k.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 Sx(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}}}},Yf=new iu});import Fi from"node:fs/promises";import _i from"node:path";var Ni,En,au=w(()=>{"use strict";ms();Ol();Gg();Vg();Kg();_l();rn();Ze();Sn();wt();we();Ri();Pr();Cn();ne();vr();Yo();Zo();Tr();Er();xs();bf();Pf();oe();vn();Yc();Qc();Ss();Tf();gc();bc();Uf();Xf();Qf();Ni=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 i=await $i(e),a=i.filter(u=>$s.includes(u)||u==="codex"),c=i.filter(u=>!$s.includes(u)&&u!=="codex");s=[...a.length>0?a:$s,...c],s=Array.from(new Set(s))}else t.aiTools[0]==="auto"?(s=await $i(e),s.length===0&&(s=["claude"])):t.aiTools[0]==="all"?s=await gf("all",e):s=t.aiTools;let o={installed:!1,verified:!1,configPath:"",message:""};try{if(this.projectId=await $.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:[],context7:{installed:!1,verified:!1},error:"No prjct project. Run p. init first."};if((await Mn()).installed){let O=await Ii({autoRepair:!0});if(!O.verified)return{success:!1,projectId:this.projectId,cliVersion:"",git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),agents:[],skills:[],skillsInstalled:[],contextFiles:[],aiTools:[],context7:{installed:!1,verified:!1},error:`Codex p. router is required but not ready: ${O.message||"verification failed"}. Run 'prjct start' or 'prjct setup' to repair.`}}try{o=await on.ensureReady()}catch(O){return{success:!1,projectId:this.projectId,cliVersion:"",git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),agents:[],skills:[],skillsInstalled:[],contextFiles:[],aiTools:[],context7:{installed:o.installed,verified:!1,message:Y(O)},error:`Context7 MCP is required but not ready: ${Y(O)}. Run 'prjct start' to repair.`}}this.globalPath=x.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await this.ensureDirectories(),await xr(this.projectId);try{let O=await Qo(this.projectId);O>0&&U.info("Swept legacy JSON files into SQLite",{swept:O})}catch(O){U.debug("Legacy JSON sweep failed (non-critical)",{error:Y(O)})}let[c,u,d,m]=await Promise.all([Vf(this.projectPath),Bf(this.projectPath),Jf(this.projectPath),Kf(this.projectPath)]),p=t.full===!0,g,f=!0,k=!0,S=new Set;if(!p&&Wg(this.projectId))try{let{diff:O,currentHashes:Yh}=await Ul(this.projectPath,this.projectId),Ou=O.added.length+O.modified.length+O.deleted.length;if(Ou===0&&!t.changedFiles?.length)f=!1,k=!1,g={isIncremental:!0,filesChanged:0,filesUnchanged:O.unchanged.length,indexesRebuilt:!1,agentsRegenerated:!1,affectedDomains:[]};else{let oa=Ug(O,this.projectId);S=Hg(oa.allAffected);let Qh=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);f=oa.allAffected.some(Rn=>{let Zh=Rn.substring(Rn.lastIndexOf("."));return Qh.has(Zh)}),k=oa.directlyChanged.some(Rn=>Rn==="package.json"||Rn==="tsconfig.json"||Rn.includes("Dockerfile")||Rn.includes("docker-compose")),g={isIncremental:!0,filesChanged:Ou,filesUnchanged:O.unchanged.length,indexesRebuilt:f,agentsRegenerated:k,affectedDomains:Array.from(S)}}Ll(this.projectId,Yh)}catch(O){U.debug("Incremental detection failed, falling back to full sync",{error:Y(O)})}else try{let{currentHashes:O}=await Ul(this.projectPath,this.projectId);Ll(this.projectId,O)}catch(O){U.debug("Hash computation failed (non-critical)",{error:Y(O)})}if(f)try{await Promise.all([Mg(this.projectPath,this.projectId),Lg(this.projectPath,this.projectId),qg(this.projectPath,this.projectId)])}catch(O){U.debug("File ranking index build failed (non-critical)",{error:Y(O)})}let I;if(k)try{let O=await _.getAggregatedFeedback(this.projectId);(O.patternsDiscovered.length>0||O.knownGotchas.length>0||O.agentAccuracy.length>0)&&(I=O)}catch{}let D=k?await Of(this.globalPath,m,u,I):await Ff(this.globalPath),B=Nf(D,this.projectId,this.globalPath),Pe=k?await Lf(D):[],$e=qf(u,d),Be=[],C;try{let O=await He.getActive(this.projectId);(O?.patterns?.length||O?.antiPatterns?.length)&&(C={patterns:O.patterns??[],antiPatterns:O.antiPatterns??[],packageManager:O.packageManager,sourceDir:O.sourceDir,testDir:O.testDir})}catch{}let j;try{j=await Cf(this.projectId)}catch{}let Re={projectId:this.projectId,name:u.name,version:u.version,ecosystem:u.ecosystem,projectType:u.projectType,languages:u.languages,frameworks:u.frameworks,repoPath:this.projectPath,branch:c.branch,fileCount:u.fileCount,commits:c.commits,hasChanges:c.hasChanges,commands:d,agents:{workflow:D.filter(O=>O.type==="workflow").map(O=>O.name),domain:D.filter(O=>O.type==="domain").map(O=>O.name)},sources:$e,analysis:C,learnings:j},tr=await kf(Re,this.globalPath,this.projectPath,s);await Promise.all([this.updateProjectJson(c,u),this.updateStateJson(u,m),this.logToMemory(c,u),this.saveDraftAnalysis(c,u,m,o.verified)]);let nr=await He.getActive(this.projectId),Ht={patterns:nr?.patterns?.length||0,antiPatterns:nr?.antiPatterns?.length||0,criticalAntiPatterns:nr?.antiPatterns?.filter(O=>O.severity==="high").length||0},Kh=Date.now()-n,Xh=await this.recordSyncMetrics(u,Be,D,Kh);await this.archiveStaleData(),await this.autoLearnFromHistory(),await ve.installGlobalConfig(),await ve.syncCommands();let Mu;try{let O=await $.readConfig(this.projectPath);Mu=await Yf.verify(this.projectPath,this.globalPath,O?.verification)}catch(O){U.debug("Verification failed (non-critical)",{error:Y(O)})}return{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:c,stats:u,commands:d,stack:m,agents:D,skills:B,skillsInstalled:Pe,contextFiles:Be,aiTools:tr.map(O=>({toolId:O.toolId,outputFile:O.outputFile,success:O.success})),context7:{installed:o.installed,verified:o.verified,message:o.message},analysisSummary:Ht,syncMetrics:Xh,verification:Mu,incremental:g}}catch(i){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:[],context7:{installed:o.installed,verified:o.verified,message:o.message},error:Y(i)}}}async ensureDirectories(){let e=["storage","context","agents","memory","analysis","config","sync"];await Promise.all(e.map(t=>Fi.mkdir(_i.join(this.globalPath,t),{recursive:!0})))}async updateProjectJson(e,t){let n=A.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};A.setDoc(this.projectId,"project",s)}async updateStateJson(e,t){let s={...await _.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 _.write(this.projectId,s);try{await xf.generate(this.projectPath,s)}catch(o){U.debug("Local state generation failed (optional)",{error:Y(o)})}}async logToMemory(e,t){A.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=_i.join(this.globalPath,m),g=await Fi.readFile(p,"utf-8");i+=g.length}catch(p){U.debug("Context file not found for metrics",{file:m,error:Y(p)})}for(let m of n)try{let p=_i.join(this.globalPath,"agents",`${m.name}.md`),g=await Fi.readFile(p,"utf-8");i+=g.length}catch(p){U.debug("Agent file not found for metrics",{agent:m.name,error:Y(p)})}let a=Math.floor(i/4),u=e.fileCount*500,d=u>0?Math.max(0,(u-a)/u):0;try{await Wn.recordSync(this.projectId,{originalSize:u,filteredSize:a,duration:s,isWatch:!1,agents:n.filter(m=>m.type==="domain").map(m=>m.name)})}catch(m){U.debug("Failed to record sync metrics",{error:Y(m)})}return{duration:s,originalSize:u,filteredSize:a,compressionRate:d}}async saveDraftAnalysis(e,t,n,s){try{let o=e.recentCommits[0]?.hash||null,i=[],a=[],c;try{c=await _.getAggregatedFeedback(this.projectId),c.patternsDiscovered.length>0&&(i=c.patternsDiscovered.map(d=>({name:d,description:`Discovered during task execution: ${d}`,source:"feedback",confidence:.74}))),c.knownGotchas.length>0&&(a=c.knownGotchas.map(d=>({issue:d,file:"multiple",suggestion:`Recurring issue reported across tasks: ${d}`,source:"feedback",severity:"medium",confidence:.7})))}catch{}let u=await Mp.extract({projectId:this.projectId,projectPath:this.projectPath,languages:t.languages,frameworks:Array.from(new Set([...t.frameworks,...n.frameworks])),feedback:c,context7Verified:s});i=u.patterns,a=u.antiPatterns,await He.saveDraft(this.projectId,{projectId:this.projectId,languages:t.languages,frameworks:t.frameworks,configFiles:[],fileCount:t.fileCount,patterns:i,antiPatterns:a,analyzedAt:b(),status:"draft",commitHash:o??void 0})}catch(o){U.debug("Failed to save draft analysis (non-critical)",{error:Y(o)})}}async archiveStaleData(){if(this.projectId)try{let[e,t,n,s,o]=await Promise.all([ut.archiveOldShipped(this.projectId).catch(()=>0),qe.markDormantIdeas(this.projectId).catch(()=>0),xe.removeStaleCompleted(this.projectId).catch(()=>0),_.archiveStalePausedTasks(this.projectId).catch(()=>[]),lt.capEntries(this.projectId).catch(()=>0)]),i=e+t+n+s.length+o;if(i>0){U.info("Archived stale data",{shipped:e,dormant:t,staleQueue:n,stalePaused:s.length,memoryCapped:o,total:i});let a=kt.getStats(this.projectId);U.debug("Archive stats",a)}}catch(e){U.debug("Archival failed (non-critical)",{error:Y(e)})}}async autoLearnFromHistory(){if(this.projectId)try{let e=await _.getTaskHistory(this.projectId);if(e.length===0)return;let t=new Fn,n=await Xc.learnFromTaskHistory(this.projectId,e,t);try{let s=await sm.getFeatureOutcomes(this.projectId);s.length>0&&await Xc.learnFromOutcomes(this.projectId,s,t)}catch{}n.memoriesInjected>0&&U.info("Auto-learned from task history",{patternsExtracted:n.patternsExtracted,memoriesInjected:n.memoriesInjected,patternsSkipped:n.patternsSkipped})}catch(e){U.debug("Auto-learning failed (non-critical)",{error:Y(e)})}}async getCliVersion(){try{let e=_i.join(__dirname,"..","..","package.json");return JSON.parse(await Fi.readFile(e,"utf-8")).version||"0.0.0"}catch(e){return U.debug("Failed to read CLI version",{error:Y(e)}),"0.0.0"}}emptyGitData(){return{branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0}}emptyStats(){return{fileCount:0,version:"0.0.0",name:"unknown",ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]}}emptyCommands(){return{install:"npm install",run:"npm run",test:"npm test",build:"npm run build",dev:"npm run dev",lint:"npm run lint",format:"npm run format"}}emptyStack(){return{hasFrontend:!1,hasBackend:!1,hasDatabase:!1,hasDocker:!1,hasTesting:!1,frontendType:null,frameworks:[]}}},En=new Ni});import{exec as bx}from"node:child_process";import Ms from"node:path";import{promisify as Cx}from"node:util";function eh(r){return/^\d+\.\d+\.\d+/.test(r)}function Os(r){let e=r.match(/^(\d+)\.(\d+)\.(\d+)/);if(!e)return r;let[,t,n,s]=e;return`${t}.${n}.${Number(s)+1}`}function Px(r){let e=r.match(/\[package\]([\s\S]*?)(?=\n\[|\n*$)/);return e?e[1].match(/^\s*version\s*=\s*"([^"]+)"/m)?.[1]??null:null}function vx(r){let e=r.match(/\[project\]([\s\S]*?)(?=\n\[|\n*$)/);if(e){let n=e[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}let t=r.match(/\[tool\.poetry\]([\s\S]*?)(?=\n\[|\n*$)/);if(t){let n=t[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}return null}function xx(r){return r.match(/<Version>([^<]+)<\/Version>/)?.[1]?.trim()??null}var Zf,Br,th=w(()=>{"use strict";Me();Zf=Cx(bx),Br=class{static{l(this,"VersionService")}projectPath;constructor(e){this.projectPath=e}async detect(){let e=[()=>this.fromPackageJson(),()=>this.fromCargoToml(),()=>this.fromPyprojectToml(),()=>this.fromCsproj(),()=>this.fromVersionFile("VERSION"),()=>this.fromVersionFile("version.txt"),()=>this.fromGitTag()];for(let t of e){let n=await t();if(n)return n}return this.createFallbackVersion()}async bump(){let e=await this.detect();return await this.writeVersion(e),e.next}async fromPackageJson(){let e=Ms.join(this.projectPath,"package.json"),t=await Gt(e,null);return t?.version?{current:t.version,next:Os(t.version),file:e,format:"json"}:null}async fromCargoToml(){let e=Ms.join(this.projectPath,"Cargo.toml"),t=await Qe(e,"");if(!t)return null;let n=Px(t);return n?{current:n,next:Os(n),file:e,format:"toml"}:null}async fromPyprojectToml(){let e=Ms.join(this.projectPath,"pyproject.toml"),t=await Qe(e,"");if(!t)return null;let n=vx(t);return n?{current:n,next:Os(n),file:e,format:"toml"}:null}async fromCsproj(){let e=await sn(this.projectPath,{extension:".csproj"});if(e.length===0)return null;let t=Ms.join(this.projectPath,e[0]),n=await Qe(t,"");if(!n)return null;let s=xx(n);return s?{current:s,next:Os(s),file:t,format:"xml"}:null}async fromVersionFile(e){let t=Ms.join(this.projectPath,e),n=await Qe(t,"");if(!n)return null;let s=n.trim();return eh(s)?{current:s,next:Os(s),file:t,format:"plaintext"}:null}async fromGitTag(){try{let{stdout:e}=await Zf("git tag --sort=-v:refname",{cwd:this.projectPath}),t=e.trim().split(`
1161
1161
  `);for(let n of t){let s=n.trim().replace(/^v/,"");if(eh(s))return{current:s,next:Os(s),file:null,format:"git-tag"}}}catch{}return null}async createFallbackVersion(){let e=Ms.join(this.projectPath,"VERSION");return await zt(e,`0.1.0
1162
1162
  `),{current:"0.1.0",next:"0.1.1",file:e,format:"plaintext"}}async writeVersion(e){if(!e.file){e.format==="git-tag"&&await Zf(`git tag v${e.next}`,{cwd:this.projectPath});return}switch(e.format){case"json":await this.writeJsonVersion(e.file,e.next);break;case"toml":await this.writeTomlVersion(e.file,e.next);break;case"xml":await this.writeXmlVersion(e.file,e.next);break;case"plaintext":await zt(e.file,`${e.next}
1163
1163
  `);break}}async writeJsonVersion(e,t){let n=await Gt(e,{});n&&(n.version=t,await $n(e,n))}async writeTomlVersion(e,t){let n=await Qe(e,"");if(!n)return;let s=n.replace(/^(\s*version\s*=\s*")([^"]+)(")/m,`$1${t}$3`);await zt(e,s)}async writeXmlVersion(e,t){let n=await Qe(e,"");if(!n)return;let s=n.replace(/(<Version>)([^<]+)(<\/Version>)/,`$1${t}$3`);await zt(e,s)}};l(eh,"isSemver");l(Os,"bumpPatch");l(Px,"parseTomlVersion");l(vx,"parsePyprojectVersion");l(xx,"parseCsprojVersion")});var ln=w(()=>{"use strict";sp();pp();mp();fp();kp();Ss();Tp();ac();Ip();gc();Rp();wc();bc();Op();Cg();Eg();au();th()});var cu,Tx,Fs,lu=w(()=>{"use strict";oe();ne();cu=class{static{l(this,"LLMAnalysisStorage")}save(e,t){let n=A.getDb(e),s=b();n.transaction(()=>{n.prepare("UPDATE llm_analysis SET status = 'superseded', superseded_at = ? WHERE status = 'active'").run(s),n.prepare("INSERT INTO llm_analysis (commit_hash, status, analysis, analyzed_at) VALUES (?, ?, ?, ?)").run(t.commitHash??null,"active",JSON.stringify(t),t.analyzedAt)})()}getActive(e){let t=A.get(e,"SELECT analysis FROM llm_analysis WHERE status = 'active' LIMIT 1");return t?JSON.parse(t.analysis):null}getActiveSummary(e){let t=this.getActive(e);return t?{commitHash:t.commitHash,architectureStyle:t.architecture.style,patternCount:t.patterns.length,antiPatternCount:t.antiPatterns.length,analyzedAt:t.analyzedAt}:null}isCurrent(e,t){return t?A.get(e,"SELECT commit_hash FROM llm_analysis WHERE status = 'active' LIMIT 1")?.commit_hash===t:!1}getHistory(e,t=10){return A.query(e,"SELECT id, commit_hash, status, analyzed_at, analysis FROM llm_analysis ORDER BY id DESC LIMIT ?",t).map(s=>{let o=JSON.parse(s.analysis);return{id:s.id,commitHash:s.commit_hash,status:s.status,analyzedAt:s.analyzed_at,patternCount:o.patterns.length}})}},Tx=new cu,Fs=Tx});import nh from"node:fs/promises";import sh from"node:path";async function rh(r,e,t,n){let[s,o,i,a]=await Promise.all([Ix(r,e,n),Rx(r),Dx(r),jx(r)]);return{project:{name:n.name,ecosystem:n.ecosystem,languages:n.languages,frameworks:n.frameworks,fileCount:n.fileCount,projectType:n.projectType},git:{branch:t.branch,recentCommits:t.recentCommits.slice(0,Ex).map(c=>({message:c.message,date:c.date})),hasChanges:t.hasChanges,weeklyCommits:t.weeklyCommits},codeSamples:s,existingPatterns:o,taskHistory:i,previousAnalysis:a??void 0}}async function Ix(r,e,t){let n=[],s=[...t.frameworks.map(a=>a.toLowerCase()),"config","router","middleware","service","model","schema","database","api","auth"].join(" "),o=Og(r,s,uu*2);for(let a of o){if(n.length>=uu)break;try{let c=sh.join(e,a.path),u=await nh.readFile(c,"utf-8");u.length>Li*3?n.push({path:a.path,content:`${u.slice(0,Li)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prjct-cli",
3
- "version": "1.38.0",
3
+ "version": "1.38.2",
4
4
  "description": "Context layer for AI agents. Project context for Claude Code, Gemini CLI, and more.",
5
5
  "main": "dist/bin/prjct.mjs",
6
6
  "bin": {