prjct-cli 2.4.7 → 2.4.11

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.
@@ -628,14 +628,14 @@ ${e.join(`
628
628
  ## User Patterns
629
629
  ${n.userPatterns.slice(0,8).map(t=>`- ${t}`).join(`
630
630
  `)}
631
- `}function Gf(n){return[Nf(n),Mf(n),Of(n),Lf(n),Ff(n),Uf(n.commands),Hf(n),Wf(n)].filter(Boolean).join("")}function Vf(n){return["# prjct","","## Use when","","You want to:","- recall prior project decisions, learnings, or shipped features","- capture a thought, todo, or insight without a commitment","- run a workflow the project already registered","- understand your role and the MCPs available in this project","","## What's here","",_f(n),"",Gf(n),"","### Primitives","",'- `prjct capture "<anything>"` \u2014 inbox dump (zero ceremony)','- `prjct remember <type> "<content>" [--tags]` \u2014 typed memory entry',"- `prjct context memory [topic]` \u2014 recall with optional keyword filter","- `prjct workflow list` / `prjct workflow run <name>` \u2014 registered workflows","- `prjct seed list` \u2014 active packs (memory types + workflow slots)","","Base memory types: `fact \xB7 decision \xB7 learning \xB7 gotcha \xB7 pattern \xB7 anti-pattern \xB7 shipped \xB7 inbox \xB7 todo \xB7 idea \xB7 insight \xB7 question \xB7 source \xB7 person`. Any lowercase string works (e.g. `recipe`, `okr`, `stakeholder`).","","### Data paths","","- `.prjct/wiki/_generated/` \u2014 agent-crawlable markdown (regenerated on ship/remember)","- `.prjct/wiki/captured/` \u2014 drop notes with frontmatter, run `prjct context wiki sync` to ingest","- `.prjct/prjct.config.json` \u2014 persona + active packs","","## Gotchas","",'- Memory recall is best-effort \u2014 an empty result means no match, not "nothing exists".',"- Tags are freeform strings \u2014 reuse existing vocabulary before inventing new keys.","- Secret-like content is refused by `remember` and `capture` unless `--force`.",'- Bare `prjct "<text>"` routes to `capture` (inbox), not `task`. Use `prjct task` explicitly for work that needs a branch/worktree.',"- Hooks in `~/.claude/settings.json` already inject persona + topical memory on SessionStart / UserPromptSubmit \u2014 you rarely need to call prjct by hand at session start.",""].join(`
631
+ `}function Gf(n){return[Nf(n),Mf(n),Of(n),Lf(n),Ff(n),Uf(n.commands),Hf(n),Wf(n)].filter(Boolean).join("")}function Vf(n){return["# prjct","","## Use when","","You want to:","- recall prior project decisions, learnings, or shipped features","- capture a thought, todo, or insight without a commitment","- run a workflow the project already registered","- understand your role and the MCPs available in this project","","## What's here","",_f(n),"",Gf(n),"","### Primitives","",'- `prjct capture "<anything>"` \u2014 inbox dump (zero ceremony)','- `prjct remember <type> "<content>" [--tags]` \u2014 typed memory entry',"- `prjct context memory [topic]` \u2014 recall with optional keyword filter","- `prjct workflow list` / `prjct workflow run <name>` \u2014 registered workflows","- `prjct seed list` \u2014 active packs (memory types + workflow slots)","","Base memory types: `fact \xB7 decision \xB7 learning \xB7 gotcha \xB7 pattern \xB7 anti-pattern \xB7 shipped \xB7 inbox \xB7 todo \xB7 idea \xB7 insight \xB7 question \xB7 source \xB7 person`. Any lowercase string works (e.g. `recipe`, `okr`, `stakeholder`).","","### Data paths","","- `.prjct/wiki/_generated/` \u2014 agent-crawlable markdown (regenerated on ship/remember)","- `.prjct/wiki/captured/` \u2014 drop notes with frontmatter, run `prjct context wiki sync` to ingest","- `.prjct/prjct.config.json` \u2014 persona + active packs","","## Quality workflows","","Five named workflows for shipping quality. Each has an explicit methodology, modes, and stop conditions. Each persists findings via `prjct remember` so the vault accumulates project-specific knowledge across sessions.","","### `review` \u2014 Production Bug Hunt + Completeness Gate","",'Use when: user asks to review code, a PR, a recent diff, or "is this ready to ship".',"","Modes (pick one based on context):",'- `expansion` \u2014 adversarial scope ("what could break", "what is missing")',"- `polish` \u2014 final pass on already-correct code (naming, ergonomics, comments)","- `triage` \u2014 fast pass that flags everything but only auto-fixes the obvious","","Methodology:","1. Read git diff + relevant memory (decisions, gotchas) for affected files.","2. Find bugs that pass CI but blow up in production: race conditions, off-by-one, error swallow, leaked resources, partial writes, retry storms.","3. Auto-fix only the OBVIOUS (typos, wrong var names, missing await on a promise that is then discarded). Anything ambiguous \u2192 flag, do not touch.","4. Stop conditions: max 3 auto-fixes per file (more = the file needs a human); never refactor outside the diff scope.",'5. Persist: `prjct remember gotcha "<bug + how to avoid>"` for each finding; `prjct remember decision "<auto-fix applied>"` for each fix.',"","### `qa` \u2014 Real Browser, Atomic Fixes, Regression Tests","","Use when: user asks to test the app, validate a UI change, find UI bugs, or check accessibility.","","Methodology:","1. Use a real browser (Playwright MCP if available; otherwise document the manual steps).","2. Walk the golden path + 2-3 edge cases for the affected feature.","3. For each bug: atomic commit with `fix:` prefix + a regression test that fails without the fix.","4. Stop conditions: max 3 failed fixes per bug \u2014 escalate to a human with details (what was tried, why it failed).",'5. Persist: `prjct remember gotcha "<UI bug + reproducer>"`; `prjct remember decision "<fix + regression test path>"`.',"","### `security` \u2014 OWASP Top 10 + STRIDE Threat Model","",'Use when: user asks for a security review, a CSO check, a vulnerability scan, or "is this safe to ship".',"","Methodology:","1. Walk OWASP Top 10 against the diff: injection, broken auth, sensitive data exposure, XXE, broken access control, security misconfig, XSS, insecure deserialization, vulnerable deps, insufficient logging.","2. Run STRIDE on each new endpoint / data flow: Spoofing, Tampering, Repudiation, Info disclosure, DoS, Elevation of privilege.","3. Confidence gate: only report findings rated 8/10+ on exploit feasibility AND impact. Below = note in appendix only.","4. False-positive exclusions: skip CSRF on idempotent GET, skip SQL injection on parameterized queries, skip XSS on already-escaped templates, skip leaks on logged-error-codes-without-PII. (List grows with project context \u2014 capture exclusions as `prjct remember decision`).",'5. Each finding includes a CONCRETE exploit scenario (curl + payload, or click sequence). Abstract "could be exploited" is not actionable.','6. Persist: `prjct remember gotcha "<finding + exploit + fix>"` for every 8/10+ finding.',"","### `investigate` \u2014 Iron Law: no fix without investigation","",'Use when: user reports a bug, behavior is unexpected, tests fail intermittently, "why does X happen".',"","Methodology:","1. Iron Law: NO code fix until you can state the root cause in one sentence.","2. Trace the data flow from user input to symptom. Include logs, network, state.","3. Form a hypothesis. Design a test that proves or disproves it.","4. Stop condition: max 3 failed hypotheses per bug \u2014 escalate with what was tried.","5. Auto-freeze: limit edits to the module under investigation (mention this constraint to the user).",'6. Persist: `prjct remember learning "<root cause discovered>"`; `prjct remember decision "<fix + why it works>"`; `prjct remember gotcha "<related bug surfaced during investigation>"`.',"","### `ship` (endurecido) \u2014 Coverage Gate + Auto-Document","","Use when: user asks to ship, deploy, merge, or finalize work.","","Methodology (additions to the existing `prjct ship`):","1. Bootstrap a test framework if the project has none (bun test / vitest / jest based on stack).","2. Coverage gate: BLOCK ship if coverage drops more than 2% from the previous version.","3. Auto-document: scan the diff against README / ARCHITECTURE / CHANGELOG / CLAUDE.md \u2192 propose updates for any drift.","4. PR description: include {Summary, Tests added (delta), Coverage delta, Risk areas touched (cross-reference `_generated/analysis/risk-areas/`), Reviews already run on this branch}.",'5. Persist: `prjct remember decision "<release notes + coverage delta>"` so the next sprint sees the trend.',"","### Outputs convention","","Every workflow above persists findings VIA `prjct remember <type>` \u2014 never to ad-hoc files. The wiki regen exposes them in `_generated/memory/<type>.md` and `_generated/analysis/`. Tag with `--tags workflow:<name>,task:<id>` so the user can query a sprint cleanly with `prjct context --tags task=<id>`.","","## Gotchas","",'- Memory recall is best-effort \u2014 an empty result means no match, not "nothing exists".',"- Tags are freeform strings \u2014 reuse existing vocabulary before inventing new keys.","- Secret-like content is refused by `remember` and `capture` unless `--force`.",'- Bare `prjct "<text>"` routes to `capture` (inbox), not `task`. Use `prjct task` explicitly for work that needs a branch/worktree.',"- Hooks in `~/.claude/settings.json` already inject persona + topical memory on SessionStart / UserPromptSubmit \u2014 you rarely need to call prjct by hand at session start.",""].join(`
632
632
  `)}function Bf(n,e){let t=n.userInvocable!==!1;return`---
633
633
  description: "${n.description}"
634
634
  allowed-tools: [${n.allowedTools.map(s=>`"${s}"`).join(", ")}]
635
635
  user-invocable: ${t}
636
636
  ---`}function Jf(n,e){return`${Bf(n,e)}
637
637
 
638
- ${n.body(e)}`}var Bi,Ji,bu,Su=v(()=>{"use strict";It();xs();c(_f,"formatProjectHeader");c(Nf,"formatPatterns");c(Mf,"formatAntiPatterns");c(Of,"formatGotchas");c(Lf,"formatRecentShipped");c(Ff,"formatVelocity");c(Uf,"formatCommands");c(Hf,"formatState");c(Wf,"formatUserPatterns");c(Gf,"formatRichContext");Bi=[{name:"prjct",description:"Persona-aware project memory + workflows. Use when you need prior decisions, learnings, or to run a registered workflow.",allowedTools:["Bash","Read","Write","Edit","Glob","Grep","Task"],condition:c(()=>!0,"condition"),body:c(n=>Vf(n),"body")}];c(Vf,"buildPrjctSkillBody");c(Bf,"buildFrontmatter");c(Jf,"buildSkillContent");Ji=class{static{c(this,"SkillGenerator")}async generateAndInstall(e,t={backlogCount:0,completedTaskCount:0,pausedTaskCount:0,hasActiveTask:!1},s){let r={generated:[],skipped:[]},o={projectName:e.stats.name,stack:[...e.stats.languages,...e.stats.frameworks].filter(Boolean).join("/")||e.stats.ecosystem,branch:e.git.branch,commands:e.commands,projectId:e.projectId,version:s?.version??e.stats.version??"0.0.0",fileCount:s?.fileCount??e.stats.fileCount??0,patterns:s?.patterns??[],antiPatterns:s?.antiPatterns??[],recentShipped:s?.recentShipped??[],velocity:s?.velocity??null,backlogCount:s?.backlogCount??t.backlogCount,completedTaskCount:s?.completedTaskCount??t.completedTaskCount,pausedTaskCount:s?.pausedTaskCount??t.pausedTaskCount,knownGotchas:s?.knownGotchas??[],hasActiveTask:s?.hasActiveTask??t.hasActiveTask,activeTaskDescription:s?.activeTaskDescription??"",pausedTasks:s?.pausedTasks??[],topBacklog:s?.topBacklog??[],ideasCount:s?.ideasCount??0,shippedCount:s?.shippedCount??0,userPatterns:s?.userPatterns??[]},i=Pn.join(If.homedir(),".claude","skills");for(let l of Bi){if(!l.condition(t)){r.skipped.push({name:l.name,reason:"condition not met"}),await Cn.rm(Pn.join(i,l.name),{recursive:!0,force:!0}).catch(()=>{});continue}try{let u=Jf(l,o),d=Pn.join(i,l.name),p=Pn.join(d,"SKILL.md");await Cn.mkdir(d,{recursive:!0}),await Cn.writeFile(p,u,"utf-8"),r.generated.push({name:l.name,path:p})}catch(u){U.debug(`Failed to generate skill ${l.name}`,{error:ie(u)}),r.skipped.push({name:l.name,reason:ie(u)})}}let a=new Set(Bi.map(l=>l.name));try{let l=await Cn.readdir(i,{withFileTypes:!0}).catch(()=>[]);for(let u of l)u.isDirectory()&&u.name.startsWith("prjct-")&&!a.has(u.name)&&await Cn.rm(Pn.join(i,u.name),{recursive:!0,force:!0}).catch(()=>{})}catch{}return r.generated.length>0&&U.info("Generated native workflow skills",{count:r.generated.length,skills:r.generated.map(l=>l.name)}),r}getDefinitions(){return Bi}},bu=new Ji});var Tu=v(()=>{"use strict"});import zf from"node:fs/promises";import Eu from"node:path";var Ur,Cu=v(()=>{"use strict";K();Ur=class{static{c(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 s={...t.dependencies,...t.devDependencies};this.detectFrontend(s,e),this.detectBackend(s,e),this.detectDatabase(s,e),this.detectTesting(s,t,e),this.collectFrameworks(s,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(r=>e[r])&&(t.hasBackend=!0)}detectDatabase(e,t){["prisma","@prisma/client","mongoose","pg","mysql2","sequelize","typeorm","drizzle-orm","knex","better-sqlite3","mongodb","redis","ioredis"].some(r=>e[r])&&(t.hasDatabase=!0)}detectTesting(e,t,s){["jest","vitest","mocha","@testing-library/react","@testing-library/vue","cypress","playwright","@playwright/test","ava","tap","bun-types"].some(o=>e[o]||t.devDependencies?.[o])&&(s.hasTesting=!0)}async detectDocker(){let e=["Dockerfile","docker-compose.yml","docker-compose.yaml",".dockerignore"];for(let t of e)if(await this.fileExistsInProject(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=Eu.join(this.projectPath,"package.json"),t=await zf.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async fileExistsInProject(e){return S(Eu.join(this.projectPath,e))}}});import zi from"node:path";async function Pu(n){let e={branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0};try{let{stdout:t}=await _("git branch --show-current",{cwd:n});e.branch=t.trim()||"main";let{stdout:s}=await _("git rev-list --count HEAD",{cwd:n});e.commits=parseInt(s.trim(),10)||0;let{stdout:r}=await _("git shortlog -sn --all | wc -l",{cwd:n});e.contributors=parseInt(r.trim(),10)||0;let{stdout:o}=await _("git status --porcelain",{cwd:n}),i=o.trim().split(`
638
+ ${n.body(e)}`}var Bi,Ji,bu,Su=v(()=>{"use strict";It();xs();c(_f,"formatProjectHeader");c(Nf,"formatPatterns");c(Mf,"formatAntiPatterns");c(Of,"formatGotchas");c(Lf,"formatRecentShipped");c(Ff,"formatVelocity");c(Uf,"formatCommands");c(Hf,"formatState");c(Wf,"formatUserPatterns");c(Gf,"formatRichContext");Bi=[{name:"prjct",description:"Project memory + quality workflows. Use to recall prior decisions/learnings/gotchas, run quality reviews (review, qa, security, investigate), ship safely, or capture insights. Lookup-first: check the vault before re-reading source.",allowedTools:["Bash","Read","Write","Edit","Glob","Grep","Task"],condition:c(()=>!0,"condition"),body:c(n=>Vf(n),"body")}];c(Vf,"buildPrjctSkillBody");c(Bf,"buildFrontmatter");c(Jf,"buildSkillContent");Ji=class{static{c(this,"SkillGenerator")}async generateAndInstall(e,t={backlogCount:0,completedTaskCount:0,pausedTaskCount:0,hasActiveTask:!1},s){let r={generated:[],skipped:[]},o={projectName:e.stats.name,stack:[...e.stats.languages,...e.stats.frameworks].filter(Boolean).join("/")||e.stats.ecosystem,branch:e.git.branch,commands:e.commands,projectId:e.projectId,version:s?.version??e.stats.version??"0.0.0",fileCount:s?.fileCount??e.stats.fileCount??0,patterns:s?.patterns??[],antiPatterns:s?.antiPatterns??[],recentShipped:s?.recentShipped??[],velocity:s?.velocity??null,backlogCount:s?.backlogCount??t.backlogCount,completedTaskCount:s?.completedTaskCount??t.completedTaskCount,pausedTaskCount:s?.pausedTaskCount??t.pausedTaskCount,knownGotchas:s?.knownGotchas??[],hasActiveTask:s?.hasActiveTask??t.hasActiveTask,activeTaskDescription:s?.activeTaskDescription??"",pausedTasks:s?.pausedTasks??[],topBacklog:s?.topBacklog??[],ideasCount:s?.ideasCount??0,shippedCount:s?.shippedCount??0,userPatterns:s?.userPatterns??[]},i=Pn.join(If.homedir(),".claude","skills");for(let l of Bi){if(!l.condition(t)){r.skipped.push({name:l.name,reason:"condition not met"}),await Cn.rm(Pn.join(i,l.name),{recursive:!0,force:!0}).catch(()=>{});continue}try{let u=Jf(l,o),d=Pn.join(i,l.name),p=Pn.join(d,"SKILL.md");await Cn.mkdir(d,{recursive:!0}),await Cn.writeFile(p,u,"utf-8"),r.generated.push({name:l.name,path:p})}catch(u){U.debug(`Failed to generate skill ${l.name}`,{error:ie(u)}),r.skipped.push({name:l.name,reason:ie(u)})}}let a=new Set(Bi.map(l=>l.name));try{let l=await Cn.readdir(i,{withFileTypes:!0}).catch(()=>[]);for(let u of l)u.isDirectory()&&u.name.startsWith("prjct-")&&!a.has(u.name)&&await Cn.rm(Pn.join(i,u.name),{recursive:!0,force:!0}).catch(()=>{})}catch{}return r.generated.length>0&&U.info("Generated native workflow skills",{count:r.generated.length,skills:r.generated.map(l=>l.name)}),r}getDefinitions(){return Bi}},bu=new Ji});var Tu=v(()=>{"use strict"});import zf from"node:fs/promises";import Eu from"node:path";var Ur,Cu=v(()=>{"use strict";K();Ur=class{static{c(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 s={...t.dependencies,...t.devDependencies};this.detectFrontend(s,e),this.detectBackend(s,e),this.detectDatabase(s,e),this.detectTesting(s,t,e),this.collectFrameworks(s,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(r=>e[r])&&(t.hasBackend=!0)}detectDatabase(e,t){["prisma","@prisma/client","mongoose","pg","mysql2","sequelize","typeorm","drizzle-orm","knex","better-sqlite3","mongodb","redis","ioredis"].some(r=>e[r])&&(t.hasDatabase=!0)}detectTesting(e,t,s){["jest","vitest","mocha","@testing-library/react","@testing-library/vue","cypress","playwright","@playwright/test","ava","tap","bun-types"].some(o=>e[o]||t.devDependencies?.[o])&&(s.hasTesting=!0)}async detectDocker(){let e=["Dockerfile","docker-compose.yml","docker-compose.yaml",".dockerignore"];for(let t of e)if(await this.fileExistsInProject(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=Eu.join(this.projectPath,"package.json"),t=await zf.readFile(e,"utf-8");return JSON.parse(t)}catch{return null}}async fileExistsInProject(e){return S(Eu.join(this.projectPath,e))}}});import zi from"node:path";async function Pu(n){let e={branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0};try{let{stdout:t}=await _("git branch --show-current",{cwd:n});e.branch=t.trim()||"main";let{stdout:s}=await _("git rev-list --count HEAD",{cwd:n});e.commits=parseInt(s.trim(),10)||0;let{stdout:r}=await _("git shortlog -sn --all | wc -l",{cwd:n});e.contributors=parseInt(r.trim(),10)||0;let{stdout:o}=await _("git status --porcelain",{cwd:n}),i=o.trim().split(`
639
639
  `).filter(Boolean);e.hasChanges=i.length>0;for(let u of i){let d=u.substring(0,2),p=u.substring(3);d.startsWith("A")||d.startsWith("M ")?e.stagedFiles.push(p):d.includes("M")?e.modifiedFiles.push(p):d.startsWith("??")&&e.untrackedFiles.push(p)}let{stdout:a}=await _('git log --oneline -20 --pretty=format:"%h|%s|%ad" --date=short',{cwd:n});e.recentCommits=a.split(`
640
640
  `).filter(Boolean).map(u=>{let[d,p,m]=u.split("|");return{hash:d,message:p,date:m}});let{stdout:l}=await _('git log --oneline --since="1 week ago" | wc -l',{cwd:n});e.weeklyCommits=parseInt(l.trim(),10)||0}catch(t){U.debug("Git analysis failed (not a git repo?)",{error:ie(t)})}return e}async function ct(n,e){let t=await S(zi.join(n,e));return t||U.debug("File not found",{filename:e}),t}async function Ru(n){let e={fileCount:0,version:"0.0.0",name:zi.basename(n),ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]};try{let{stdout:t}=await _('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:n});e.fileCount=parseInt(t.trim(),10)||0}catch(t){U.debug("File count failed",{path:n,error:ie(t)}),e.fileCount=0}try{let t=zi.join(n,"package.json"),s=await me(t);if(!s)throw new Error("No package.json found");e.version=s.version||"0.0.0",e.name=s.name||e.name,e.ecosystem="JavaScript",s.devDependencies?.typescript||await ct(n,"tsconfig.json")?e.languages.push("TypeScript"):e.languages.push("JavaScript")}catch(t){U.debug("No package.json found",{path:n,error:ie(t)})}return await ct(n,"Cargo.toml")?(e.ecosystem="Rust",e.languages.push("Rust")):await ct(n,"go.mod")?(e.ecosystem="Go",e.languages.push("Go")):(await ct(n,"requirements.txt")||await ct(n,"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 Au(n){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 ct(n,"bun.lockb")||await ct(n,"bun.lock")?(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 ct(n,"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 ct(n,"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 ct(n,"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 ct(n,"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}async function ju(n){return new Ur(n).detect()}var xu=v(()=>{"use strict";It();Tu();Ne();K();xs();Cu();c(Pu,"analyzeGit");c(ct,"fileExistsInProject");c(Ru,"gatherStats");c(Au,"detectCommands");c(ju,"detectStack")});import $u from"node:fs/promises";import Xi from"node:path";var Du,qi,Iu,_u=v(()=>{"use strict";ot();z();Ne();Du={async jsonFilesValid(n){let e=Date.now(),t=[],s=Xi.basename(n);try{await L.read(s)}catch(r){x(r)||t.push(`state: ${h(r)}`)}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(n){let e=Date.now(),t=Xi.join(n,"context"),s=[/(?:api[_-]?key|apikey)\s*[:=]\s*['"][^'"]{10,}/i,/(?:password|passwd|pwd)\s*[:=]\s*['"][^'"]{4,}/i,/(?:secret|token)\s*[:=]\s*['"][^'"]{10,}/i],r=[];try{let o=await $u.readdir(t);for(let i of o){if(!i.endsWith(".md"))continue;let a=await $u.readFile(Xi.join(t,i),"utf-8");for(let l of s)if(l.test(a)){r.push(`${i}: potential sensitive data detected`);break}}}catch(o){if(!x(o))return{name:"No sensitive data",passed:!1,error:`Could not scan: ${h(o)}`,durationMs:Date.now()-e}}return{name:"No sensitive data",passed:r.length===0,output:r.length===0?"No sensitive patterns found":void 0,error:r.length>0?r.join("; "):void 0,durationMs:Date.now()-e}}},qi=class{static{c(this,"SyncVerifier")}async verify(e,t,s){let r=Date.now(),o=[],i=s?.failFast??!1,a=0,l=[Du.jsonFilesValid(t),Du.noSensitiveData(t)];for(let m of l){let g=await m;if(o.push(g),!g.passed&&i){a=s?.checks?.filter(y=>y.enabled!==!1).length??0;break}}if((!i||o.every(m=>m.passed))&&s?.checks)for(let m of s.checks){if(m.enabled===!1){a++;continue}let g=await this.runCustomCheck(m,e);if(o.push(g),!g.passed&&i){let y=s.checks.slice(s.checks.indexOf(m)+1);a+=y.filter(C=>C.enabled!==!1).length;break}}let d=o.filter(m=>!m.passed).length,p=o.filter(m=>m.passed).length;return{passed:d===0,checks:o,totalMs:Date.now()-r,failedCount:d,passedCount:p,skippedCount:a}}async runCustomCheck(e,t){let s=Date.now(),r=e.command||(e.script?`sh ${e.script}`:null);if(!r)return{name:e.name,passed:!1,error:"No command or script specified",durationMs:Date.now()-s};try{let{stdout:o,stderr:i}=await _(r,{cwd:t,timeout:3e4});return{name:e.name,passed:!0,output:(o.trim()||i.trim()).slice(0,200)||void 0,durationMs:Date.now()-s}}catch(o){let i=o;return{name:e.name,passed:!1,error:(i.stderr?.trim()||i.message).slice(0,200),durationMs:Date.now()-s}}}},Iu=new qi});import Nu from"node:fs/promises";import Ki from"node:path";var Yi,Os,Qi=v(()=>{"use strict";Ko();Pl();jl();_l();pi();It();Ue();bt();Ce();Ae();Mr();vn();ss();ye();Ri();bn();ji();Ii();Oi();Tn();ot();hu();be();K();xs();Ar();wu();os();vu();Su();xu();_u();Yi=class{static{c(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 s=Date.now(),r={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(),context7:{installed:!1,verified:!1},error:"No prjct project. Run p. init first."};if(this.globalPath=j.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await Nu.rm(Ki.join(this.globalPath,"agents"),{recursive:!0,force:!0}).catch(()=>{}),(await Qt()).installed){let P=await Nr({autoRepair:!0});P.verified||U.warn(`Codex p. router not ready: ${P.message||"verification failed"}`)}try{r=await ns.ensureReady()}catch(P){return{success:!1,projectId:this.projectId,cliVersion:this.cliVersion,git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),context7:{installed:r.installed,verified:!1,message:ie(P)},error:`Context7 MCP is required but not ready: ${ie(P)}. Run 'prjct start' to repair.`}}await this.ensureDirectories(),await Or(this.projectId);try{let P=await Lr(this.projectId);P>0&&U.info("Swept legacy JSON files into SQLite",{swept:P})}catch(P){U.debug("Legacy JSON sweep failed (non-critical)",{error:ie(P)})}let[a,l,u,d]=await Promise.all([Pu(this.projectPath),Ru(this.projectPath),Au(this.projectPath),ju(this.projectPath)]),p=t.full===!0,m,g=!0,y=new Set;if(!p&&Al(this.projectId))try{let{diff:P,currentHashes:ge}=await gi(this.projectPath,this.projectId),Xe=P.added.length+P.modified.length+P.deleted.length;if(Xe===0&&!t.changedFiles?.length)g=!1,m={isIncremental:!0,filesChanged:0,filesUnchanged:P.unchanged.length,indexesRebuilt:!1,affectedDomains:[]};else{let mt=El(P,this.projectId);y=Cl(mt.allAffected);let gt=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);g=mt.allAffected.some(Et=>{let Dt=Et.substring(Et.lastIndexOf("."));return gt.has(Dt)}),m={isIncremental:!0,filesChanged:Xe,filesUnchanged:P.unchanged.length,indexesRebuilt:g,affectedDomains:Array.from(y)}}mi(this.projectId,ge)}catch(P){U.debug("Incremental detection failed, falling back to full sync",{error:ie(P)})}else try{let{currentHashes:P}=await gi(this.projectPath,this.projectId);mi(this.projectId,P)}catch(P){U.debug("Hash computation failed (non-critical)",{error:ie(P)})}if(g)try{await Promise.all([il(this.projectPath,this.projectId),Tl(this.projectPath,this.projectId),Il(this.projectPath,this.projectId)])}catch(P){U.debug("File ranking index build failed (non-critical)",{error:ie(P)})}let C;try{let[P,ge,Xe,mt,gt,Xt,Et,Dt,pn,ko,dc]=await Promise.all([Promise.resolve(Ze.getActive(this.projectId)).catch(()=>null),Me.getActive(this.projectId).catch(()=>null),At.getRecent(this.projectId,3).catch(()=>[]),fu.getMetrics(this.projectId).catch(()=>null),Ms.getBacklog(this.projectId).catch(()=>[]),L.getTaskHistory(this.projectId).catch(()=>[]),L.getAllPausedTasks(this.projectId).catch(()=>[]),L.getAggregatedFeedback(this.projectId).catch(()=>null),L.getCurrentTask(this.projectId).catch(()=>null),_s.getCounts(this.projectId).catch(()=>({pending:0,converted:0,archived:0})),At.getCount(this.projectId).catch(()=>0)]),q={backlogCount:gt.length,completedTaskCount:Xt.length,pausedTaskCount:Et.length,hasActiveTask:!!pn},ve=P?P.patterns.map(Z=>({name:Z.name,description:Z.description,location:Z.locations?.[0]})):(ge?.patterns??[]).filter(Z=>Z.source!=="repo").map(Z=>({name:Z.name,description:Z.description,location:Z.location})),qt=P?P.antiPatterns.map(Z=>({issue:Z.issue,file:Z.files?.[0]??"multiple",suggestion:Z.suggestion,severity:Z.severity??"medium"})):(ge?.antiPatterns??[]).filter(Z=>Z.source!=="repo").map(Z=>({issue:Z.issue,file:Z.file,suggestion:Z.suggestion,severity:Z.severity??"medium"})),Fp=P?.commands?{install:P.commands.install??u.install,run:u.run,test:P.commands.test??u.test,build:P.commands.build??u.build,dev:P.commands.dev??u.dev,lint:P.commands.lint??u.lint,format:P.commands.format??u.format}:u,Up={version:l.version,fileCount:l.fileCount,patterns:ve,antiPatterns:qt,recentShipped:Xe.map(Z=>({name:Z.name,type:Z.type??"feature",duration:Z.duration,filesChanged:Z.changes?.length})),velocity:mt?{avgPoints:mt.averageVelocity,trend:mt.velocityTrend,accuracy:mt.estimationAccuracy}:null,backlogCount:gt.length,completedTaskCount:Xt.length,pausedTaskCount:Et.length,knownGotchas:Dt?.knownGotchas??[],userPatterns:Dt?.patternsDiscovered??[],hasActiveTask:!!pn,activeTaskDescription:pn?.description??"",pausedTasks:Et.map(Z=>({description:Z.description,pausedAt:Z.pausedAt??""})),topBacklog:gt.slice(0,3).map(Z=>({description:Z.description,priority:Z.priority??"medium"})),ideasCount:ko?.pending??0,shippedCount:dc};C=await bu.generateAndInstall({success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:a,stats:l,commands:Fp,stack:d},q,Up)}catch(P){U.debug("Native skill generation failed (non-critical)",{error:ie(P)})}await Promise.all([this.updateProjectJson(a,l),this.updateStateJson(l,d),this.logToMemory(a,l),this.saveDraftAnalysis(a,l,d,r.verified)]);let A=await Me.getActive(this.projectId),k={patterns:A?.patterns?.length||0,antiPatterns:A?.antiPatterns?.length||0,criticalAntiPatterns:A?.antiPatterns?.filter(P=>P.severity==="high").length||0},I=Date.now()-s,E=await this.recordSyncMetrics(l,I);await this.archiveStaleData(),await this.autoLearnFromHistory(),await pe.installGlobalConfig(),await pe.syncCommands();let te;try{let P=await $.readConfig(this.projectPath);te=await Iu.verify(this.projectPath,this.globalPath,P?.verification)}catch(P){U.debug("Verification failed (non-critical)",{error:ie(P)})}return{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:a,stats:l,commands:u,stack:d,context7:{installed:r.installed,verified:r.verified,message:r.message},analysisSummary:k,syncMetrics:E,verification:te,incremental:m,generatedSkills:C}}catch(o){return{success:!1,projectId:this.projectId||"",cliVersion:this.cliVersion,git:this.emptyGitData(),stats:this.emptyStats(),commands:this.emptyCommands(),stack:this.emptyStack(),context7:{installed:r.installed,verified:r.verified,message:r.message},error:ie(o)}}}async ensureDirectories(){let e=["storage","context","memory","analysis","config","sync"];await Promise.all(e.map(t=>Nu.mkdir(Ki.join(this.globalPath,t),{recursive:!0})))}async updateProjectJson(e,t){let s=R.getDoc(this.projectId,"project")||{},r={...s,projectId:this.projectId,repoPath:this.projectPath,name:t.name,version:t.version,cliVersion:this.cliVersion,techStack:t.frameworks,fileCount:t.fileCount,commitCount:e.commits,stack:t.ecosystem,currentBranch:e.branch,hasUncommittedChanges:e.hasChanges,createdAt:s.createdAt||b(),lastSync:b(),lastSyncCommit:e.recentCommits[0]?.hash||null,lastSyncBranch:e.branch};R.setDoc(this.projectId,"project",r)}async updateStateJson(e,t){let r={...await L.read(this.projectId)};r.projectId=this.projectId,r.stack={language:e.languages[0]||"Unknown",framework:e.frameworks[0]||null},r.domains={hasFrontend:t.hasFrontend,hasBackend:t.hasBackend,hasDatabase:t.hasDatabase,hasTesting:t.hasTesting,hasDocker:t.hasDocker},r.projectType=e.projectType,r.metrics={totalFiles:e.fileCount},r.lastSync=b(),r.lastUpdated=b(),r.context={...r.context||{},lastSession:b(),lastAction:"Synced project",nextAction:'Run `p. task "description"` to start working'},await L.write(this.projectId,r);try{await yu.generate(this.projectPath,r)}catch(o){U.debug("Local state generation failed (optional)",{error:ie(o)})}}async logToMemory(e,t){R.appendEvent(this.projectId,"sync",{branch:e.branch,uncommitted:e.hasChanges,fileCount:t.fileCount,commitCount:e.commits})}async recordSyncMetrics(e,t){let s=0;try{let a=vr(this.projectId);if(a)for(let l of Object.values(a.documents))s+=l.length}catch(a){U.debug("Could not load BM25 index for metrics",{error:ie(a)})}s===0&&(s=e.fileCount*200);let r=0,o=s>0?Math.max(0,(s-r)/s):0;try{await Ns.recordSync(this.projectId,{originalSize:s,filteredSize:r,duration:t,isWatch:!1})}catch(a){U.debug("Failed to record sync metrics",{error:ie(a)})}let i={};try{let a=vr(this.projectId);a&&(i.bm25Files=a.totalDocs,i.bm25AvgTokens=Math.round(a.avgDocLength),i.bm25VocabSize=Object.keys(a.invertedIndex).length);let l=Pr(this.projectId);l&&(i.importEdges=l.edgeCount,i.importFiles=l.fileCount);let u=Dl(this.projectId);u&&(i.cochangeCommits=u.commitsAnalyzed,i.cochangeFiles=u.filesAnalyzed)}catch(a){U.debug("Could not load index stats",{error:ie(a)})}return{duration:t,originalSize:s,filteredSize:r,compressionRate:o,indexes:i}}async saveDraftAnalysis(e,t,s,r){try{let o=e.recentCommits[0]?.hash||null,i=[],a=[],l;try{l=await L.getAggregatedFeedback(this.projectId),l.patternsDiscovered.length>0&&(i=l.patternsDiscovered.map(d=>({name:d,description:`Discovered during task execution: ${d}`,source:"feedback",confidence:.74}))),l.knownGotchas.length>0&&(a=l.knownGotchas.map(d=>({issue:d,file:"multiple",suggestion:`Recurring issue reported across tasks: ${d}`,source:"feedback",severity:"medium",confidence:.7})))}catch{}let u=await ku.extract({projectId:this.projectId,projectPath:this.projectPath,languages:t.languages,frameworks:Array.from(new Set([...t.frameworks,...s.frameworks])),feedback:l,context7Verified:r});i=u.patterns,a=u.antiPatterns,await Me.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:ie(o)})}}async archiveStaleData(){if(this.projectId)try{let[e,t,s,r,o]=await Promise.all([At.archiveOldShipped(this.projectId).catch(()=>0),_s.markDormantIdeas(this.projectId).catch(()=>0),Ms.removeStaleCompleted(this.projectId).catch(()=>0),L.archiveStalePausedTasks(this.projectId).catch(()=>[]),He.capEntries(this.projectId).catch(()=>0)]),i=e+t+s+r.length+o;if(i>0){U.info("Archived stale data",{shipped:e,dormant:t,staleQueue:s,stalePaused:r.length,memoryCapped:o,total:i});let a=et.getStats(this.projectId);U.debug("Archive stats",a)}}catch(e){U.debug("Archival failed (non-critical)",{error:ie(e)})}}async autoLearnFromHistory(){}async getCliVersion(){try{let e=Ki.join(__dirname,"..","..","package.json");return(await me(e))?.version||"0.0.0"}catch(e){return U.debug("Failed to read CLI version",{error:ie(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:[]}}},Os=new Yi});function Xf(){return"---"}function qf(){return`---
641
641
  prjct v${qn()}`}function M(...n){return ea(Xf(),...n.filter(Boolean),qf())}function Mu(n,e){let t=`| ${n.join(" | ")} |`,s=`|${n.map(()=>"---").join("|")}|`,r=e.map(o=>`| ${o.join(" | ")} |`);return[t,s,...r].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prjct-cli",
3
- "version": "2.4.7",
3
+ "version": "2.4.11",
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": {