prjct-cli 2.37.4 → 2.37.6
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 +24 -1
- package/dist/bin/prjct-core.mjs +304 -304
- package/dist/daemon/entry.mjs +229 -229
- package/dist/mcp/server.mjs +79 -79
- package/package.json +1 -2
package/dist/mcp/server.mjs
CHANGED
|
@@ -5,13 +5,13 @@ import { dirname as __pathDirname } from 'path';
|
|
|
5
5
|
var require = __createRequire(import.meta.url);
|
|
6
6
|
var __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
var __dirname = __pathDirname(__filename);
|
|
8
|
-
var
|
|
9
|
-
`;await et.writeFile(s,
|
|
10
|
-
`).map(o=>o.replace(/^\s*-\s*['"]?|['"]?\s*$/g,"")).filter(Boolean))}else if(t==="npm"||t==="lerna"){let
|
|
11
|
-
`)[0];if(
|
|
8
|
+
var It=Object.defineProperty;var gi=Object.getOwnPropertyDescriptor;var fi=Object.getOwnPropertyNames;var hi=Object.prototype.hasOwnProperty;var c=(n,t)=>It(n,"name",{value:t,configurable:!0}),Tr=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var E=(n,t)=>()=>(n&&(t=n(n=0)),t);var K=(n,t)=>{for(var e in t)It(n,e,{get:t[e],enumerable:!0})},yi=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of fi(t))!hi.call(n,s)&&s!==e&&It(n,s,{get:()=>t[s],enumerable:!(r=gi(t,s))||r.enumerable});return n};var ie=n=>yi(It({},"__esModule",{value:!0}),n);var Er,kr,Sr,oe=E(()=>{"use strict";Er=new Set(["node_modules",".git","dist","build","out",".next",".nuxt","coverage",".cache",".turbo",".vercel",".parcel-cache","__pycache__",".pytest_cache","target","vendor",".venv","venv","eggs","*.egg-info",".prjct",".worktrees"]),kr=["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"],Sr=/(?:import|from)\s+['"]([^'"]+)['"]/g});function wr(n){return{year:n.getFullYear().toString(),month:(n.getMonth()+1).toString().padStart(2,"0"),day:n.getDate().toString().padStart(2,"0")}}function f(){return new Date().toISOString()}function _r(n){let t=new Date;return t.setDate(t.getDate()-n),t}var Ha,N=E(()=>{"use strict";c(wr,"getYearMonthDay");c(f,"getTimestamp");c(_r,"getDaysAgo");Ha=new Intl.RelativeTimeFormat("en",{numeric:"always"})});function Ei(n){return n instanceof Error&&"code"in n}function M(n){return Ei(n)&&n.code==="ENOENT"}function Ct(n){return n instanceof Error?n.message:typeof n=="string"?n:"Unknown error"}var tt=E(()=>{"use strict";c(Ei,"isNodeError");c(M,"isNotFoundError");c(Ct,"getErrorMessage")});import Rr from"node:fs/promises";async function xr(n,t){let e;try{e=await Rr.readFile(n,"utf-8")}catch(i){if(M(i))return null;throw i}let r;try{r=JSON.parse(e)}catch{return await br(n,e),vr(n,"Malformed JSON"),null}let s=t.safeParse(r);return s.success?r:(await br(n,e),vr(n,ki(s.error)),null)}async function br(n,t){let e=`${n}.backup`;try{await Rr.writeFile(e,t,{encoding:"utf-8",flag:"wx"})}catch{}}function vr(n,t){console.error(`[prjct] Warning: Corrupted storage file: ${n}`),console.error(`[prjct] Reason: ${t}`),console.error("[prjct] A .backup file has been created. Returning defaults.")}function ki(n){return n.issues.slice(0,3).map(t=>`${t.path.join(".")}: ${t.message}`).join("; ")}var Pr=E(()=>{"use strict";tt();c(xr,"safeRead");c(br,"createBackup");c(vr,"logCorruption");c(ki,"formatZodError")});import et from"node:fs/promises";import ae from"node:path";async function Ar(n,t={}){let e=[],r=t.maxFiles??1/0,s=t.dotfileAllowlist?new Set(t.dotfileAllowlist):null;async function i(o){if(e.length>=r)return;let a=await et.readdir(o,{withFileTypes:!0}).catch(()=>[]);for(let u of a){if(e.length>=r)break;let l=String(u.name);if(Er.has(l)||t.skipDotfiles&&l.startsWith(".")&&(!s||!s.has(l)))continue;let d=ae.join(o,l);u.isDirectory()?await i(d):u.isFile()&&e.push(ae.relative(n,d))}}return c(i,"walk"),await i(n),e}async function Nr(n,t,e){let r=[];for(let s=0;s<n.length;s+=t){let i=await Promise.all(n.slice(s,s+t).map(e));for(let o of i)o!==null&&r.push(o)}return r}async function Lt(n,t=null,e){if(e)return await xr(n,e)??t;try{let r=await et.readFile(n,"utf-8");return JSON.parse(r)}catch(r){if(M(r))return t;throw r}}async function F(n,t,e=2){let r=ae.dirname(n);await et.mkdir(r,{recursive:!0});let s=`${JSON.stringify(t,null,e)}
|
|
9
|
+
`;await et.writeFile(n,s,"utf-8")}async function I(n){try{return await et.access(n),!0}catch(t){if(M(t))return!1;throw t}}async function ce(n){try{return(await et.stat(n)).isDirectory()}catch(t){if(M(t))return!1;throw t}}async function G(n){await et.mkdir(n,{recursive:!0})}var U=E(()=>{"use strict";oe();Pr();tt();c(Ar,"walkDir");c(Nr,"batchProcess");c(Lt,"readJson");c(F,"writeJson");c(I,"fileExists");c(ce,"dirExists");c(G,"ensureDir")});import ot from"node:fs/promises";import D from"node:path";import{globSync as Si}from"glob";async function ue(n){let t={isMonorepo:!1,type:null,rootPath:n,packages:[]},e=[{file:"pnpm-workspace.yaml",type:"pnpm"},{file:"lerna.json",type:"lerna"},{file:"nx.json",type:"nx"},{file:"rush.json",type:"rush"},{file:"turbo.json",type:"turborepo"}];for(let r of e)if(await I(D.join(n,r.file))){t.isMonorepo=!0,t.type=r.type;break}if(!t.isMonorepo){let r=D.join(n,"package.json");if(await I(r))try{JSON.parse(await ot.readFile(r,"utf-8")).workspaces&&(t.isMonorepo=!0,t.type="npm")}catch{}}return t.isMonorepo&&(t.packages=await le(n,t.type)),t}async function le(n,t){let e=[],r=[];try{if(t==="pnpm"){let i=(await ot.readFile(D.join(n,"pnpm-workspace.yaml"),"utf-8")).match(/packages:\s*\n((?:\s*-\s*.+\n?)+)/);i&&(r=i[1].split(`
|
|
10
|
+
`).map(o=>o.replace(/^\s*-\s*['"]?|['"]?\s*$/g,"")).filter(Boolean))}else if(t==="npm"||t==="lerna"){let s=D.join(n,"package.json"),i=JSON.parse(await ot.readFile(s,"utf-8"));if(Array.isArray(i.workspaces)?r=i.workspaces:i.workspaces?.packages&&(r=i.workspaces.packages),t==="lerna"){let o=D.join(n,"lerna.json");if(await I(o)){let a=JSON.parse(await ot.readFile(o,"utf-8"));a.packages&&(r=a.packages)}}}else if(t==="nx")r=["apps/*","libs/*","packages/*"];else if(t==="turborepo"){let s=D.join(n,"package.json"),i=JSON.parse(await ot.readFile(s,"utf-8"));Array.isArray(i.workspaces)&&(r=i.workspaces)}r.length===0&&(r=["packages/*","apps/*","libs/*"]);for(let s of r){if(s.startsWith("!"))continue;let i=Si(s,{cwd:n,absolute:!1});for(let o of i){let a=D.join(n,o),u=D.join(a,"package.json");if(await I(u))try{let l=JSON.parse(await ot.readFile(u,"utf-8")),d=D.join(a,"PRJCT.md");e.push({name:l.name||D.basename(o),path:a,relativePath:o,hasPrjctMd:await I(d)})}catch{}}}}catch{}return e}async function Ir(n,t){if(!t.isMonorepo)return null;let e=D.resolve(n);for(let r of t.packages){let s=D.resolve(r.path);if(e.startsWith(s))return r}return null}async function Cr(n){let t=D.resolve(n),e=D.parse(t).root;for(;t!==e;){if((await ue(t)).isMonorepo)return t;t=D.dirname(t)}return null}var Lr=E(()=>{"use strict";U();c(ue,"detectMonorepo");c(le,"discoverMonorepoPackages");c(Ir,"findContainingPackage");c(Cr,"findMonorepoRoot")});import{exec as wi,execFile as _i}from"node:child_process";import{promisify as Dr}from"node:util";var b,Or,rt=E(()=>{"use strict";b=Dr(wi),Or=Dr(_i)});var me={};K(me,{default:()=>bi,worktreeService:()=>jr});import pe from"node:fs/promises";import $ from"node:path";var Mr,de,jr,bi,ge=E(()=>{"use strict";rt();U();Mr=".worktrees",de=class{static{c(this,"WorktreeService")}async create(t,e,r={}){let s=await this.getMainWorktree(t),i=$.join(s,Mr,e),o=r.branch||`feat/${e}`;await pe.mkdir($.join(s,Mr),{recursive:!0});let a=r.baseBranch?` ${r.baseBranch}`:"";await b(`git worktree add "${i}" -b "${o}"${a}`,{cwd:s});let{stdout:u}=await b("git rev-parse HEAD",{cwd:i});return{path:i,branch:o,commit:u.trim(),isMain:!1,slug:e}}async remove(t,e=!1){let r=await this.getMainWorktree(t),s;if(e)try{let{stdout:i}=await b("git rev-parse --abbrev-ref HEAD",{cwd:t});s=i.trim()}catch{}if(await b(`git worktree remove "${t}" --force`,{cwd:r}),e&&s&&s!=="main"&&s!=="master")try{await b(`git branch -D "${s}"`,{cwd:r})}catch{}}async list(t){let e=await this.getMainWorktree(t),{stdout:r}=await b("git worktree list --porcelain",{cwd:e});return this.parsePorcelainOutput(r,e)}async detect(t){try{let{stdout:e}=await b("git rev-parse --git-common-dir",{cwd:t}),{stdout:r}=await b("git rev-parse --git-dir",{cwd:t}),s=$.resolve(t,e.trim()),i=$.resolve(t,r.trim());if(s!==i){let{stdout:o}=await b("git rev-parse --abbrev-ref HEAD",{cwd:t}),{stdout:a}=await b("git rev-parse HEAD",{cwd:t}),{stdout:u}=await b("git rev-parse --show-toplevel",{cwd:t}),l=u.trim(),d=$.basename(l);return{path:l,branch:o.trim(),commit:a.trim(),isMain:!1,slug:d}}return null}catch{return null}}async getMainWorktree(t){try{let{stdout:r}=await b("git worktree list --porcelain",{cwd:t}),s=r.split(`
|
|
11
|
+
`)[0];if(s?.startsWith("worktree "))return s.replace("worktree ","").trim()}catch{}let{stdout:e}=await b("git rev-parse --show-toplevel",{cwd:t});return e.trim()}async setup(t,e){let r=$.join(e,".env");await I(r)&&await pe.copyFile(r,$.join(t,".env"));let s=$.join(e,".prjct"),i=$.join(t,".prjct");await I(s)&&!await I(i)&&await pe.symlink(s,i,"dir")}async teardown(t){}async clean(t){let e=await this.list(t),r=[],s=await this.getMainWorktree(t);await b("git worktree prune",{cwd:s});for(let i of e)i.isMain||await I(i.path)||r.push(i.slug);return r}parsePorcelainOutput(t,e){let r=[],s=t.trim().split(`
|
|
12
12
|
|
|
13
|
-
`);for(let i of
|
|
14
|
-
`),a="",u="",l="",d=!1;for(let p of o)p.startsWith("worktree ")?a=p.replace("worktree ","").trim():p.startsWith("HEAD ")?u=p.replace("HEAD ","").trim():p.startsWith("branch ")?l=p.replace("branch refs/heads/","").trim():p==="bare"?d=!0:p==="detached"&&(l="(detached)");if(a){let p=a===e||d;r.push({path:a,branch:l,commit:u,isMain:p,slug:p?"main":U.basename(a)})}}return r}},Lr=new ue,Ti=Lr});import de from"node:os";import X from"node:path";async function Or(s,t){if(t&&t.trim().length>0)return ki(s,t);let e=await Ei(s),n=X.basename(X.resolve(e)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project";return X.join(de.homedir(),"Documents","prjct",n)}function Mr(s,t){let r=X.basename(X.resolve(s)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project",n=t.replace(/-/g,"").slice(0,8);return X.join(de.homedir(),"Documents","prjct",`${r}-${n}`)}function jr(s){return X.join(s,".prjct","wiki")}async function Ei(s){try{let{worktreeService:t}=await Promise.resolve().then(()=>(pe(),le));return await t.detect(s)&&await t.getMainWorktree(s)||s}catch{return s}}function ki(s,t){let e=t.trim();return(e.startsWith("~/")||e==="~")&&(e=X.join(de.homedir(),e.slice(1))),X.isAbsolute(e)||(e=X.resolve(s,e)),e}var Fr=E(()=>{"use strict";c(Or,"getWikiPath");c(Mr,"getWikiPathWithProjectHash");c(jr,"getLegacyWikiPath");c(Ei,"resolveProjectRootPath");c(ki,"resolveVaultOverride")});var $r=E(()=>{"use strict"});import{z as yt}from"zod";function Ur(s,t){let e=s.split(".").map(Number),r=t.split(".").map(Number);for(let n=0;n<3;n++){let i=e[n]??0,o=r[n]??0;if(i<o)return-1;if(i>o)return 1}return 0}var me,ge=E(()=>{"use strict";me=yt.object({provider:yt.string(),model:yt.string(),cliVersion:yt.string().optional(),recordedAt:yt.string()});c(Ur,"compareSemver")});function Xr(s,t){let e=typeof s=="string"?new Date(s).getTime():s;return Date.now()-e>t}var Dt,fe=E(()=>{"use strict";c(Xr,"isExpired");Dt=class{static{c(this,"TTLCache")}cache=new Map;ttl;maxSize;constructor(t={}){this.ttl=t.ttl??5e3,this.maxSize=t.maxSize??50}isValid(t){let e=this.cache.get(t);return e?Date.now()-e.timestamp<this.ttl:!1}get(t){let e=this.cache.get(t);return e?this.isValid(t)?e.data:(this.cache.delete(t),null):null}set(t,e){this.cache.set(t,{data:e,timestamp:Date.now()}),this.evictOldEntries()}delete(t){this.cache.delete(t)}clear(){this.cache.clear()}has(t){return this.cache.has(t)}get size(){return this.cache.size}evictOldEntries(){if(this.cache.size<=this.maxSize)return;let e=Array.from(this.cache.entries()).sort((r,n)=>r[1].timestamp-n[1].timestamp).slice(0,this.cache.size-this.maxSize);for(let[r]of e)this.cache.delete(r)}stats(){return{size:this.cache.size,maxSize:this.maxSize,ttl:this.ttl}}prune(){let t=0;for(let e of this.cache.keys())this.isValid(e)||(this.cache.delete(e),t++);return t}}});import Si from"node:fs/promises";import wi from"node:path";async function Br(){try{let s=await Si.readFile(Wr(),"utf-8"),t=JSON.parse(s);return!t.timestamp||!t.detection||!t.detection.claude||!t.detection.gemini||!t.detection.codex||Xr(t.timestamp,_i)?null:t.detection}catch{return null}}async function Hr(s){let t={timestamp:new Date().toISOString(),detection:s};await F(Wr(),t)}var Wr,_i,qr=E(()=>{"use strict";at();fe();$();Wr=c(()=>wi.join(R.getCachePath(),"providers.json"),"cacheFile"),_i=10*60*1e3;c(Br,"readProviderCache");c(Hr,"writeProviderCache")});var Ot={};K(Ot,{ClaudeProvider:()=>Lt,CursorProvider:()=>Jr,GeminiProvider:()=>ye,Providers:()=>Tt,detectAllProviders:()=>Te,detectAntigravity:()=>Pi,detectCodex:()=>Qr,detectProvider:()=>he,getActiveProvider:()=>Ri,getProviderBranding:()=>xi,selectProvider:()=>Ai,validateCliVersion:()=>Vr});import V from"node:os";import W from"node:path";async function Kr(s){try{let{stdout:t}=await b(`which ${s}`,{timeout:2e3});return t.trim()}catch{return null}}async function vi(s){try{let{stdout:t}=await b(`${s} --version`,{timeout:2e3}),e=t.match(/\d+\.\d+\.\d+/);return e?e[0]:t.trim()}catch{return null}}async function he(s){let t=Tt[s];if(!t.cliCommand)return{installed:!1};let e=await Kr(t.cliCommand);if(!e)return{installed:!1};let r=await vi(t.cliCommand),n=Vr(s,r||void 0);return{installed:!0,version:r||void 0,path:e,versionWarning:n||void 0}}function Vr(s,t){let e=Tt[s];return!e.minCliVersion||!t?null:Ur(t,e.minCliVersion)<0?`\u26A0\uFE0F ${e.displayName} v${t} is below minimum v${e.minCliVersion}. Some features may not work correctly.`:null}async function Te(s=!1){if(!s){let o=await Br();if(o)return o}let[t,e,r]=await Promise.all([he("claude"),he("gemini"),Qr()]),n={installed:r.installed},i={claude:t,gemini:e,codex:n};return await Hr(i).catch(()=>{}),i}async function Ri(s){if(s&&Tt[s])return Tt[s];let t=await Te();return t.claude.installed&&!t.gemini.installed?Lt:t.gemini.installed&&!t.claude.installed?ye:Lt}function xi(s){return{commitFooter:"Generated with [p/](https://www.prjct.app/)",signature:{claude:"\u26A1 prjct + Claude",gemini:"\u26A1 prjct + Gemini",cursor:"\u26A1 prjct + Cursor",antigravity:"\u26A1 prjct + Antigravity",windsurf:"\u26A1 prjct + Windsurf",codex:"\u26A1 prjct + Codex"}[s]||"\u26A1 prjct"}}async function Pi(){let s=Yr.configDir;if(!s)return{installed:!1,skillInstalled:!1};let t=W.join(s,"skills","prjct","SKILL.md"),[e,r]=await Promise.all([I(s),I(t)]);return{installed:e,skillInstalled:r,configPath:e?s:void 0}}async function Qr(){let s=zr.configDir;if(!s)return{installed:!1,skillInstalled:!1};let t=await Kr("codex"),e=W.join(s,"skills","prjct","SKILL.md"),r=await I(e),n=!!t;return{installed:n,skillInstalled:r,configPath:n?s:void 0}}async function Ai(){let s=await Te(),t=s.claude.installed,e=s.gemini.installed;return!t&&!e?{provider:"claude",userSelected:!1,detection:s}:t&&!e?{provider:"claude",userSelected:!1,detection:s}:e&&!t?{provider:"gemini",userSelected:!1,detection:s}:{provider:"claude",userSelected:!0,detection:s}}var Lt,ye,Yr,Jr,bi,zr,Tt,Mt=E(()=>{"use strict";$r();ge();ot();$();qr();Lt={name:"claude",displayName:"Claude Code",cliCommand:"claude",configDir:W.join(V.homedir(),".claude"),contextFile:"CLAUDE.md",skillsDir:W.join(V.homedir(),".claude","skills"),commandsDir:".claude/commands",commandFormat:"md",settingsFile:"settings.json",projectSettingsFile:"settings.local.json",ignoreFile:".claudeignore",websiteUrl:"https://www.anthropic.com/claude",docsUrl:"https://docs.anthropic.com/claude-code",defaultModel:"sonnet",supportedModels:["opus","sonnet","haiku"],minCliVersion:"1.0.0",capabilityTier:"full"},ye={name:"gemini",displayName:"Gemini CLI",cliCommand:"gemini",configDir:W.join(V.homedir(),".gemini"),contextFile:"GEMINI.md",skillsDir:W.join(V.homedir(),".gemini","skills"),commandsDir:".gemini/commands",commandFormat:"toml",settingsFile:"settings.json",projectSettingsFile:"settings.json",ignoreFile:".geminiignore",websiteUrl:"https://geminicli.com",docsUrl:"https://geminicli.com/docs",defaultModel:"2.5-flash",supportedModels:["2.5-pro","2.5-flash","2.0-flash"],minCliVersion:"1.0.0",capabilityTier:"standard"},Yr={name:"antigravity",displayName:"Google Antigravity",cliCommand:null,configDir:W.join(V.homedir(),".gemini","antigravity"),contextFile:"ANTIGRAVITY.md",skillsDir:W.join(V.homedir(),".gemini","antigravity","global_skills"),commandsDir:".agent/skills",commandFormat:"md",settingsFile:"mcp_config.json",projectSettingsFile:null,ignoreFile:".agentignore",websiteUrl:"https://gemini.google.com/app/antigravity",docsUrl:"https://gemini.google.com/app/antigravity",defaultModel:null,supportedModels:[],minCliVersion:null,capabilityTier:"basic"},Jr={name:"cursor",displayName:"Cursor IDE",cliCommand:null,configDir:null,contextFile:"prjct.mdc",skillsDir:null,commandsDir:".cursor/commands",rulesDir:".cursor/rules",commandFormat:"md",settingsFile:null,projectSettingsFile:null,ignoreFile:".cursorignore",isProjectLevel:!0,websiteUrl:"https://cursor.com",docsUrl:"https://cursor.com/docs",defaultModel:null,supportedModels:[],minCliVersion:null,capabilityTier:"basic"},bi={name:"windsurf",displayName:"Windsurf IDE",cliCommand:null,configDir:null,contextFile:"prjct.md",skillsDir:null,commandsDir:".windsurf/workflows",rulesDir:".windsurf/rules",commandFormat:"md",settingsFile:null,projectSettingsFile:null,ignoreFile:".windsurfignore",isProjectLevel:!0,websiteUrl:"https://windsurf.com",docsUrl:"https://docs.windsurf.com",defaultModel:null,supportedModels:[],minCliVersion:null,capabilityTier:"basic"},zr={name:"codex",displayName:"OpenAI Codex",cliCommand:"codex",configDir:W.join(V.homedir(),".codex"),contextFile:"AGENTS.md",skillsDir:W.join(V.homedir(),".codex","skills"),commandsDir:".agents/skills",commandFormat:"md",settingsFile:null,projectSettingsFile:null,ignoreFile:".codexignore",websiteUrl:"https://openai.com/codex",docsUrl:"https://github.com/openai/codex",defaultModel:null,supportedModels:[],minCliVersion:null,capabilityTier:"basic"},Tt={claude:Lt,gemini:ye,cursor:Jr,antigravity:Yr,windsurf:bi,codex:zr};c(Kr,"whichCommand");c(vi,"getCliVersion");c(he,"detectProvider");c(Vr,"validateCliVersion");c(Te,"detectAllProviders");c(Ri,"getActiveProvider");c(xi,"getProviderBranding");c(Pi,"detectAntigravity");c(Qr,"detectCodex");c(Ai,"selectProvider")});import Ni from"node:crypto";import jt from"node:fs/promises";import Ee from"node:os";import w from"node:path";var ke,Ii,R,at=E(()=>{"use strict";N();$();Ir();Fr();ke=class{static{c(this,"PathManager")}globalBaseDir;globalProjectsDir;globalConfigDir;constructor(){let t=process.env.PRJCT_CLI_HOME?.trim();this.globalBaseDir=t?w.resolve(t):w.join(Ee.homedir(),".prjct-cli"),this.globalProjectsDir=w.join(this.globalBaseDir,"projects"),this.globalConfigDir=w.join(this.globalBaseDir,"config")}setGlobalBaseDir(t){this.globalBaseDir=w.resolve(t),this.globalProjectsDir=w.join(this.globalBaseDir,"projects"),this.globalConfigDir=w.join(this.globalBaseDir,"config")}generateProjectId(t){return Ni.randomUUID()}getGlobalBasePath(){return this.globalBaseDir}getGlobalProjectPath(t){return w.join(this.globalProjectsDir,t)}getLocalConfigPath(t){return w.join(t,".prjct","prjct.config.json")}getGlobalProjectConfigPath(t){return w.join(this.getGlobalProjectPath(t),"project.json")}getLegacyPrjctPath(t){return w.join(t,".prjct")}async hasLegacyStructure(t){return await ie(this.getLegacyPrjctPath(t))}async hasConfig(t){return await I(this.getLocalConfigPath(t))}async ensureGlobalStructure(){await G(this.globalBaseDir),await G(this.globalProjectsDir),await G(this.globalConfigDir)}async ensureProjectStructure(t){await this.ensureGlobalStructure();let e=this.getGlobalProjectPath(t),r=["analysis","memory"];for(let n of r)await G(w.join(e,n));return await G(w.join(e,"sessions")),e}getSessionPath(t,e=new Date){let{year:r,month:n,day:i}=Er(e);return w.join(this.getGlobalProjectPath(t),"sessions",r,n,i)}getCurrentSessionPath(t){return this.getSessionPath(t,new Date)}async ensureSessionPath(t,e=new Date){let r=this.getSessionPath(t,e);return await G(r),r}async listSessions(t,e=null,r=null){let n=w.join(this.getGlobalProjectPath(t),"sessions"),i=[];try{let o=await jt.readdir(n,{withFileTypes:!0});for(let a of o){if(!a.isDirectory()||e&&a.name!==e.toString())continue;let u=w.join(n,a.name),l=await jt.readdir(u,{withFileTypes:!0});for(let d of l){if(!d.isDirectory()||r&&d.name!==r.toString().padStart(2,"0"))continue;let p=w.join(u,d.name),g=await jt.readdir(p,{withFileTypes:!0});for(let T of g)T.isDirectory()&&i.push({year:a.name,month:d.name,day:T.name,path:w.join(p,T.name),date:new Date(`${a.name}-${d.name}-${T.name}`)})}}return i.sort((a,u)=>u.date.getTime()-a.date.getTime()),i}catch{return[]}}async getSessionsInRange(t,e,r=new Date){return(await this.listSessions(t)).filter(i=>i.date>=e&&i.date<=r)}getFilePath(t,e,r){return w.join(this.getGlobalProjectPath(t),e,r)}async listProjects(){try{return await this.ensureGlobalStructure(),(await jt.readdir(this.globalProjectsDir,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async projectExists(t){return await ie(this.getGlobalProjectPath(t))}getDisplayPath(t){let e=Ee.homedir();return t.startsWith(e)?t.replace(e,"~"):t}getAuthConfigPath(){return w.join(this.globalConfigDir,"auth.json")}getSyncPendingPath(t){return w.join(this.getGlobalProjectPath(t),"sync","pending.json")}getLastSyncPath(t){return w.join(this.getGlobalProjectPath(t),"sync","last-sync.json")}getRunningStatusPath(){return w.join(this.globalBaseDir,".running")}getDocsPath(){return w.join(this.globalBaseDir,"docs")}getCachePath(){return w.join(this.globalBaseDir,"cache")}getStatePath(){return w.join(this.globalBaseDir,"state")}getStatusLinePath(){return w.join(this.globalBaseDir,"statusline")}async getAgentDir(){return(await(Mt(),re(Ot)).getActiveProvider()).configDir}async getAgentSettingsPath(){let t=await(Mt(),re(Ot)).getActiveProvider();return(Mt(),re(Ot)).getGlobalSettingsPath(t.name)}getClaudeDir(){return w.join(Ee.homedir(),".claude")}getClaudeSettingsPath(){return w.join(this.getClaudeDir(),"settings.json")}getStoragePath(t,e){return w.join(this.getGlobalProjectPath(t),"storage",e)}getContextPath(t){return w.join(this.getGlobalProjectPath(t),"context")}async getWikiPath(t,e){return Or(t,e)}getWikiPathWithProjectHash(t,e){return Mr(t,e)}getLegacyWikiPath(t){return jr(t)}async detectMonorepo(t){return oe(t)}async discoverMonorepoPackages(t,e){return ae(t,e)}async findContainingPackage(t,e){return Ar(t,e)}async findMonorepoRoot(t){return Nr(t)}},Ii=new ke,R=Ii});import Ci from"node:crypto";function Et(s){let t=s.toLowerCase().replace(/\s+/g," ").trim();return Ci.createHash("sha256").update(t).digest("hex")}var Se=E(()=>{"use strict";c(Et,"memoryFingerprint")});var Zr,ts=E(()=>{"use strict";Zr=`
|
|
13
|
+
`);for(let i of s){if(!i.trim())continue;let o=i.trim().split(`
|
|
14
|
+
`),a="",u="",l="",d=!1;for(let p of o)p.startsWith("worktree ")?a=p.replace("worktree ","").trim():p.startsWith("HEAD ")?u=p.replace("HEAD ","").trim():p.startsWith("branch ")?l=p.replace("branch refs/heads/","").trim():p==="bare"?d=!0:p==="detached"&&(l="(detached)");if(a){let p=a===e||d;r.push({path:a,branch:l,commit:u,isMain:p,slug:p?"main":$.basename(a)})}}return r}},jr=new de,bi=jr});import fe from"node:os";import X from"node:path";async function Fr(n,t){if(t&&t.trim().length>0)return Ri(n,t);let e=await vi(n),s=X.basename(X.resolve(e)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project";return X.join(fe.homedir(),"Documents","prjct",s)}function Ur(n,t){let r=X.basename(X.resolve(n)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project",s=t.replace(/-/g,"").slice(0,8);return X.join(fe.homedir(),"Documents","prjct",`${r}-${s}`)}function $r(n){return X.join(n,".prjct","wiki")}async function vi(n){try{let{worktreeService:t}=await Promise.resolve().then(()=>(ge(),me));return await t.detect(n)&&await t.getMainWorktree(n)||n}catch{return n}}function Ri(n,t){let e=t.trim();return(e.startsWith("~/")||e==="~")&&(e=X.join(fe.homedir(),e.slice(1))),X.isAbsolute(e)||(e=X.resolve(n,e)),e}var Xr=E(()=>{"use strict";c(Fr,"getWikiPath");c(Ur,"getWikiPathWithProjectHash");c($r,"getLegacyWikiPath");c(vi,"resolveProjectRootPath");c(Ri,"resolveVaultOverride")});var Wr=E(()=>{"use strict"});import{z as Tt}from"zod";function Br(n,t){let e=n.split(".").map(Number),r=t.split(".").map(Number);for(let s=0;s<3;s++){let i=e[s]??0,o=r[s]??0;if(i<o)return-1;if(i>o)return 1}return 0}var he,ye=E(()=>{"use strict";he=Tt.object({provider:Tt.string(),model:Tt.string(),cliVersion:Tt.string().optional(),recordedAt:Tt.string()});c(Br,"compareSemver")});function Hr(n,t){let e=typeof n=="string"?new Date(n).getTime():n;return Date.now()-e>t}var Ot,Te=E(()=>{"use strict";c(Hr,"isExpired");Ot=class{static{c(this,"TTLCache")}cache=new Map;ttl;maxSize;constructor(t={}){this.ttl=t.ttl??5e3,this.maxSize=t.maxSize??50}isValid(t){let e=this.cache.get(t);return e?Date.now()-e.timestamp<this.ttl:!1}get(t){let e=this.cache.get(t);return e?this.isValid(t)?e.data:(this.cache.delete(t),null):null}set(t,e){this.cache.set(t,{data:e,timestamp:Date.now()}),this.evictOldEntries()}delete(t){this.cache.delete(t)}clear(){this.cache.clear()}has(t){return this.cache.has(t)}get size(){return this.cache.size}evictOldEntries(){if(this.cache.size<=this.maxSize)return;let e=Array.from(this.cache.entries()).sort((r,s)=>r[1].timestamp-s[1].timestamp).slice(0,this.cache.size-this.maxSize);for(let[r]of e)this.cache.delete(r)}stats(){return{size:this.cache.size,maxSize:this.maxSize,ttl:this.ttl}}prune(){let t=0;for(let e of this.cache.keys())this.isValid(e)||(this.cache.delete(e),t++);return t}}});import xi from"node:fs/promises";import Pi from"node:path";async function Gr(){try{let n=await xi.readFile(qr(),"utf-8"),t=JSON.parse(n);return!t.timestamp||!t.detection||!t.detection.claude||!t.detection.gemini||!t.detection.codex||Hr(t.timestamp,Ai)?null:t.detection}catch{return null}}async function Yr(n){let t={timestamp:new Date().toISOString(),detection:n};await F(qr(),t)}var qr,Ai,Jr=E(()=>{"use strict";at();Te();U();qr=c(()=>Pi.join(R.getCachePath(),"providers.json"),"cacheFile"),Ai=10*60*1e3;c(Gr,"readProviderCache");c(Yr,"writeProviderCache")});var jt={};K(jt,{ClaudeProvider:()=>Mt,CursorProvider:()=>Vr,GeminiProvider:()=>ke,Providers:()=>Et,detectAllProviders:()=>Se,detectAntigravity:()=>Di,detectCodex:()=>en,detectProvider:()=>Ee,getActiveProvider:()=>Ci,getProviderBranding:()=>Li,selectProvider:()=>Oi,validateCliVersion:()=>tn});import V from"node:os";import W from"node:path";async function Zr(n){try{let{stdout:t}=await b(`which ${n}`,{timeout:2e3});return t.trim()}catch{return null}}async function Ii(n){try{let{stdout:t}=await b(`${n} --version`,{timeout:2e3}),e=t.match(/\d+\.\d+\.\d+/);return e?e[0]:t.trim()}catch{return null}}async function Ee(n){let t=Et[n];if(!t.cliCommand)return{installed:!1};let e=await Zr(t.cliCommand);if(!e)return{installed:!1};let r=await Ii(t.cliCommand),s=tn(n,r||void 0);return{installed:!0,version:r||void 0,path:e,versionWarning:s||void 0}}function tn(n,t){let e=Et[n];return!e.minCliVersion||!t?null:Br(t,e.minCliVersion)<0?`\u26A0\uFE0F ${e.displayName} v${t} is below minimum v${e.minCliVersion}. Some features may not work correctly.`:null}async function Se(n=!1){if(!n){let o=await Gr();if(o)return o}let[t,e,r]=await Promise.all([Ee("claude"),Ee("gemini"),en()]),s={installed:r.installed},i={claude:t,gemini:e,codex:s};return await Yr(i).catch(()=>{}),i}async function Ci(n){if(n&&Et[n])return Et[n];let t=await Se();return t.claude.installed&&!t.gemini.installed?Mt:t.gemini.installed&&!t.claude.installed?ke:Mt}function Li(n){return{commitFooter:"Generated with [p/](https://www.prjct.app/)",signature:{claude:"\u26A1 prjct + Claude",gemini:"\u26A1 prjct + Gemini",cursor:"\u26A1 prjct + Cursor",antigravity:"\u26A1 prjct + Antigravity",windsurf:"\u26A1 prjct + Windsurf",codex:"\u26A1 prjct + Codex"}[n]||"\u26A1 prjct"}}async function Di(){let n=Kr.configDir;if(!n)return{installed:!1,skillInstalled:!1};let t=W.join(n,"skills","prjct","SKILL.md"),[e,r]=await Promise.all([I(n),I(t)]);return{installed:e,skillInstalled:r,configPath:e?n:void 0}}async function en(){let n=Qr.configDir;if(!n)return{installed:!1,skillInstalled:!1};let t=await Zr("codex"),e=W.join(n,"skills","prjct","SKILL.md"),r=await I(e),s=!!t;return{installed:s,skillInstalled:r,configPath:s?n:void 0}}async function Oi(){let n=await Se(),t=n.claude.installed,e=n.gemini.installed;return!t&&!e?{provider:"claude",userSelected:!1,detection:n}:t&&!e?{provider:"claude",userSelected:!1,detection:n}:e&&!t?{provider:"gemini",userSelected:!1,detection:n}:{provider:"claude",userSelected:!0,detection:n}}var Mt,ke,Kr,Vr,Ni,Qr,Et,Ft=E(()=>{"use strict";Wr();ye();rt();U();Jr();Mt={name:"claude",displayName:"Claude Code",cliCommand:"claude",configDir:W.join(V.homedir(),".claude"),contextFile:"CLAUDE.md",skillsDir:W.join(V.homedir(),".claude","skills"),commandsDir:".claude/commands",commandFormat:"md",settingsFile:"settings.json",projectSettingsFile:"settings.local.json",ignoreFile:".claudeignore",websiteUrl:"https://www.anthropic.com/claude",docsUrl:"https://docs.anthropic.com/claude-code",defaultModel:"sonnet",supportedModels:["opus","sonnet","haiku"],minCliVersion:"1.0.0",capabilityTier:"full"},ke={name:"gemini",displayName:"Gemini CLI",cliCommand:"gemini",configDir:W.join(V.homedir(),".gemini"),contextFile:"GEMINI.md",skillsDir:W.join(V.homedir(),".gemini","skills"),commandsDir:".gemini/commands",commandFormat:"toml",settingsFile:"settings.json",projectSettingsFile:"settings.json",ignoreFile:".geminiignore",websiteUrl:"https://geminicli.com",docsUrl:"https://geminicli.com/docs",defaultModel:"2.5-flash",supportedModels:["2.5-pro","2.5-flash","2.0-flash"],minCliVersion:"1.0.0",capabilityTier:"standard"},Kr={name:"antigravity",displayName:"Google Antigravity",cliCommand:null,configDir:W.join(V.homedir(),".gemini","antigravity"),contextFile:"ANTIGRAVITY.md",skillsDir:W.join(V.homedir(),".gemini","antigravity","global_skills"),commandsDir:".agent/skills",commandFormat:"md",settingsFile:"mcp_config.json",projectSettingsFile:null,ignoreFile:".agentignore",websiteUrl:"https://gemini.google.com/app/antigravity",docsUrl:"https://gemini.google.com/app/antigravity",defaultModel:null,supportedModels:[],minCliVersion:null,capabilityTier:"basic"},Vr={name:"cursor",displayName:"Cursor IDE",cliCommand:null,configDir:null,contextFile:"prjct.mdc",skillsDir:null,commandsDir:".cursor/commands",rulesDir:".cursor/rules",commandFormat:"md",settingsFile:null,projectSettingsFile:null,ignoreFile:".cursorignore",isProjectLevel:!0,websiteUrl:"https://cursor.com",docsUrl:"https://cursor.com/docs",defaultModel:null,supportedModels:[],minCliVersion:null,capabilityTier:"basic"},Ni={name:"windsurf",displayName:"Windsurf IDE",cliCommand:null,configDir:null,contextFile:"prjct.md",skillsDir:null,commandsDir:".windsurf/workflows",rulesDir:".windsurf/rules",commandFormat:"md",settingsFile:null,projectSettingsFile:null,ignoreFile:".windsurfignore",isProjectLevel:!0,websiteUrl:"https://windsurf.com",docsUrl:"https://docs.windsurf.com",defaultModel:null,supportedModels:[],minCliVersion:null,capabilityTier:"basic"},Qr={name:"codex",displayName:"OpenAI Codex",cliCommand:"codex",configDir:W.join(V.homedir(),".codex"),contextFile:"AGENTS.md",skillsDir:W.join(V.homedir(),".codex","skills"),commandsDir:".agents/skills",commandFormat:"md",settingsFile:null,projectSettingsFile:null,ignoreFile:".codexignore",websiteUrl:"https://openai.com/codex",docsUrl:"https://github.com/openai/codex",defaultModel:null,supportedModels:[],minCliVersion:null,capabilityTier:"basic"},Et={claude:Mt,gemini:ke,cursor:Vr,antigravity:Kr,windsurf:Ni,codex:Qr};c(Zr,"whichCommand");c(Ii,"getCliVersion");c(Ee,"detectProvider");c(tn,"validateCliVersion");c(Se,"detectAllProviders");c(Ci,"getActiveProvider");c(Li,"getProviderBranding");c(Di,"detectAntigravity");c(en,"detectCodex");c(Oi,"selectProvider")});import Mi from"node:crypto";import Ut from"node:fs/promises";import we from"node:os";import w from"node:path";var _e,ji,R,at=E(()=>{"use strict";N();U();Lr();Xr();_e=class{static{c(this,"PathManager")}globalBaseDir;globalProjectsDir;globalConfigDir;constructor(){let t=process.env.PRJCT_CLI_HOME?.trim();this.globalBaseDir=t?w.resolve(t):w.join(we.homedir(),".prjct-cli"),this.globalProjectsDir=w.join(this.globalBaseDir,"projects"),this.globalConfigDir=w.join(this.globalBaseDir,"config")}setGlobalBaseDir(t){this.globalBaseDir=w.resolve(t),this.globalProjectsDir=w.join(this.globalBaseDir,"projects"),this.globalConfigDir=w.join(this.globalBaseDir,"config")}generateProjectId(t){return Mi.randomUUID()}getGlobalBasePath(){return this.globalBaseDir}getGlobalProjectPath(t){return w.join(this.globalProjectsDir,t)}getLocalConfigPath(t){return w.join(t,".prjct","prjct.config.json")}getGlobalProjectConfigPath(t){return w.join(this.getGlobalProjectPath(t),"project.json")}getLegacyPrjctPath(t){return w.join(t,".prjct")}async hasLegacyStructure(t){return await ce(this.getLegacyPrjctPath(t))}async hasConfig(t){return await I(this.getLocalConfigPath(t))}async ensureGlobalStructure(){await G(this.globalBaseDir),await G(this.globalProjectsDir),await G(this.globalConfigDir)}async ensureProjectStructure(t){await this.ensureGlobalStructure();let e=this.getGlobalProjectPath(t),r=["analysis","memory"];for(let s of r)await G(w.join(e,s));return await G(w.join(e,"sessions")),e}getSessionPath(t,e=new Date){let{year:r,month:s,day:i}=wr(e);return w.join(this.getGlobalProjectPath(t),"sessions",r,s,i)}getCurrentSessionPath(t){return this.getSessionPath(t,new Date)}async ensureSessionPath(t,e=new Date){let r=this.getSessionPath(t,e);return await G(r),r}async listSessions(t,e=null,r=null){let s=w.join(this.getGlobalProjectPath(t),"sessions"),i=[];try{let o=await Ut.readdir(s,{withFileTypes:!0});for(let a of o){if(!a.isDirectory()||e&&a.name!==e.toString())continue;let u=w.join(s,a.name),l=await Ut.readdir(u,{withFileTypes:!0});for(let d of l){if(!d.isDirectory()||r&&d.name!==r.toString().padStart(2,"0"))continue;let p=w.join(u,d.name),g=await Ut.readdir(p,{withFileTypes:!0});for(let T of g)T.isDirectory()&&i.push({year:a.name,month:d.name,day:T.name,path:w.join(p,T.name),date:new Date(`${a.name}-${d.name}-${T.name}`)})}}return i.sort((a,u)=>u.date.getTime()-a.date.getTime()),i}catch{return[]}}async getSessionsInRange(t,e,r=new Date){return(await this.listSessions(t)).filter(i=>i.date>=e&&i.date<=r)}getFilePath(t,e,r){return w.join(this.getGlobalProjectPath(t),e,r)}async listProjects(){try{return await this.ensureGlobalStructure(),(await Ut.readdir(this.globalProjectsDir,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async projectExists(t){return await ce(this.getGlobalProjectPath(t))}getDisplayPath(t){let e=we.homedir();return t.startsWith(e)?t.replace(e,"~"):t}getAuthConfigPath(){return w.join(this.globalConfigDir,"auth.json")}getSyncPendingPath(t){return w.join(this.getGlobalProjectPath(t),"sync","pending.json")}getLastSyncPath(t){return w.join(this.getGlobalProjectPath(t),"sync","last-sync.json")}getRunningStatusPath(){return w.join(this.globalBaseDir,".running")}getDocsPath(){return w.join(this.globalBaseDir,"docs")}getCachePath(){return w.join(this.globalBaseDir,"cache")}getStatePath(){return w.join(this.globalBaseDir,"state")}getStatusLinePath(){return w.join(this.globalBaseDir,"statusline")}async getAgentDir(){return(await(Ft(),ie(jt)).getActiveProvider()).configDir}async getAgentSettingsPath(){let t=await(Ft(),ie(jt)).getActiveProvider();return(Ft(),ie(jt)).getGlobalSettingsPath(t.name)}getClaudeDir(){return w.join(we.homedir(),".claude")}getClaudeSettingsPath(){return w.join(this.getClaudeDir(),"settings.json")}getStoragePath(t,e){return w.join(this.getGlobalProjectPath(t),"storage",e)}getContextPath(t){return w.join(this.getGlobalProjectPath(t),"context")}async getWikiPath(t,e){return Fr(t,e)}getWikiPathWithProjectHash(t,e){return Ur(t,e)}getLegacyWikiPath(t){return $r(t)}async detectMonorepo(t){return ue(t)}async discoverMonorepoPackages(t,e){return le(t,e)}async findContainingPackage(t,e){return Ir(t,e)}async findMonorepoRoot(t){return Cr(t)}},ji=new _e,R=ji});import Fi from"node:crypto";function kt(n){let t=n.toLowerCase().replace(/\s+/g," ").trim();return Fi.createHash("sha256").update(t).digest("hex")}var be=E(()=>{"use strict";c(kt,"memoryFingerprint")});var rn,nn=E(()=>{"use strict";rn=`
|
|
15
15
|
-- =======================================================================
|
|
16
16
|
-- Document storage (backward-compatible with JSON file pattern)
|
|
17
17
|
-- =======================================================================
|
|
@@ -225,7 +225,7 @@ CREATE TABLE velocity_sprints (
|
|
|
225
225
|
started_at TEXT,
|
|
226
226
|
ended_at TEXT
|
|
227
227
|
);
|
|
228
|
-
`});var
|
|
228
|
+
`});var sn,on=E(()=>{"use strict";be();nn();sn=[{version:1,name:"initial-schema",up:c(n=>{n.run(rn)},"up")},{version:2,name:"archives-table",up:c(n=>{n.run(`
|
|
229
229
|
-- =======================================================================
|
|
230
230
|
-- Archives: Stale data moved out of active storage (PRJ-267)
|
|
231
231
|
-- =======================================================================
|
|
@@ -242,7 +242,7 @@ CREATE TABLE velocity_sprints (
|
|
|
242
242
|
CREATE INDEX idx_archives_entity_type ON archives(entity_type);
|
|
243
243
|
CREATE INDEX idx_archives_archived_at ON archives(archived_at);
|
|
244
244
|
CREATE INDEX idx_archives_entity_id ON archives(entity_id);
|
|
245
|
-
`)},"up")},{version:3,name:"workflow-rules-table",up:c(
|
|
245
|
+
`)},"up")},{version:3,name:"workflow-rules-table",up:c(n=>{n.run(`
|
|
246
246
|
-- =======================================================================
|
|
247
247
|
-- Workflow Rules: hooks, gates, and custom steps (Phase 2)
|
|
248
248
|
-- =======================================================================
|
|
@@ -260,7 +260,7 @@ CREATE TABLE velocity_sprints (
|
|
|
260
260
|
);
|
|
261
261
|
|
|
262
262
|
CREATE INDEX idx_workflow_rules_command ON workflow_rules(command);
|
|
263
|
-
`)},"up")},{version:4,name:"custom-workflows-table",up:c(
|
|
263
|
+
`)},"up")},{version:4,name:"custom-workflows-table",up:c(n=>{n.run(`
|
|
264
264
|
-- =======================================================================
|
|
265
265
|
-- Custom Workflows: User-defined workflows with agentic auto-config
|
|
266
266
|
-- =======================================================================
|
|
@@ -285,7 +285,7 @@ CREATE TABLE velocity_sprints (
|
|
|
285
285
|
('done', 'Complete current task/subtask', 1, 1, datetime('now'), datetime('now')),
|
|
286
286
|
('ship', 'Ship feature with version bump and PR', 1, 1, datetime('now'), datetime('now')),
|
|
287
287
|
('sync', 'Analyze project and regenerate context', 1, 1, datetime('now'), datetime('now'));
|
|
288
|
-
`)},"up")},{version:5,name:"llm-analysis-table",up:c(
|
|
288
|
+
`)},"up")},{version:5,name:"llm-analysis-table",up:c(n=>{n.run(`
|
|
289
289
|
-- =======================================================================
|
|
290
290
|
-- LLM Analysis: Structured findings from hybrid sync pipeline
|
|
291
291
|
-- Pipeline: CLI (collect) \u2192 LLM (analyze) \u2192 CLI (store)
|
|
@@ -301,7 +301,7 @@ CREATE TABLE velocity_sprints (
|
|
|
301
301
|
|
|
302
302
|
CREATE INDEX idx_llm_analysis_status ON llm_analysis(status);
|
|
303
303
|
CREATE INDEX idx_llm_analysis_commit ON llm_analysis(commit_hash);
|
|
304
|
-
`)},"up")},{version:6,name:"context-feedback-table",up:c(
|
|
304
|
+
`)},"up")},{version:6,name:"context-feedback-table",up:c(n=>{n.run(`
|
|
305
305
|
-- =======================================================================
|
|
306
306
|
-- Context Feedback: RL loop for file suggestion improvement
|
|
307
307
|
-- Records suggested vs actual files per task for scoring boosts
|
|
@@ -319,7 +319,7 @@ CREATE TABLE velocity_sprints (
|
|
|
319
319
|
);
|
|
320
320
|
|
|
321
321
|
CREATE INDEX idx_cf_task ON context_feedback(task_id);
|
|
322
|
-
`)},"up")},{version:7,name:"sessions-table",up:c(
|
|
322
|
+
`)},"up")},{version:7,name:"sessions-table",up:c(n=>{n.run(`
|
|
323
323
|
-- =======================================================================
|
|
324
324
|
-- Sessions: Task lifecycle tracking (replaces current.json + archive/)
|
|
325
325
|
-- =======================================================================
|
|
@@ -339,13 +339,13 @@ CREATE TABLE velocity_sprints (
|
|
|
339
339
|
CREATE INDEX idx_sessions_project ON sessions(project_id);
|
|
340
340
|
CREATE INDEX idx_sessions_status ON sessions(status);
|
|
341
341
|
CREATE INDEX idx_sessions_completed ON sessions(completed_at);
|
|
342
|
-
`)},"up")},{version:8,name:"task-token-tracking",up:c(
|
|
342
|
+
`)},"up")},{version:8,name:"task-token-tracking",up:c(n=>{n.run(`
|
|
343
343
|
-- =======================================================================
|
|
344
344
|
-- Token usage tracking per task (input + output)
|
|
345
345
|
-- =======================================================================
|
|
346
346
|
ALTER TABLE tasks ADD COLUMN tokens_in INTEGER DEFAULT 0;
|
|
347
347
|
ALTER TABLE tasks ADD COLUMN tokens_out INTEGER DEFAULT 0;
|
|
348
|
-
`)},"up")},{version:9,name:"context-health-tables",up:c(
|
|
348
|
+
`)},"up")},{version:9,name:"context-health-tables",up:c(n=>{n.run(`
|
|
349
349
|
-- =======================================================================
|
|
350
350
|
-- Context Zone Events: Track zone transitions for health analytics
|
|
351
351
|
-- =======================================================================
|
|
@@ -375,7 +375,7 @@ CREATE TABLE velocity_sprints (
|
|
|
375
375
|
);
|
|
376
376
|
|
|
377
377
|
CREATE INDEX idx_cc_project ON context_compactions(project_id);
|
|
378
|
-
`)},"up")},{version:10,name:"fts5-memories",up:c(
|
|
378
|
+
`)},"up")},{version:10,name:"fts5-memories",up:c(n=>{n.run(`
|
|
379
379
|
-- =======================================================================
|
|
380
380
|
-- Memories: Tagged, searchable memory store (replaces memories.json)
|
|
381
381
|
-- =======================================================================
|
|
@@ -424,11 +424,11 @@ CREATE TABLE velocity_sprints (
|
|
|
424
424
|
INSERT INTO memories_fts(rowid, title, content, tags)
|
|
425
425
|
VALUES (NEW.rowid, NEW.title, NEW.content, NEW.tags);
|
|
426
426
|
END;
|
|
427
|
-
`);try{let t=
|
|
427
|
+
`);try{let t=n.prepare("SELECT data FROM kv_store WHERE key = 'memory:memories'").get();if(t){let e=JSON.parse(t.data);if(e.memories&&e.memories.length>0){let r=n.prepare(`
|
|
428
428
|
INSERT OR IGNORE INTO memories
|
|
429
429
|
(id, project_id, title, content, tags, content_hash, user_triggered, confidence, observation_count, created_at, updated_at)
|
|
430
430
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
431
|
-
`);for(let
|
|
431
|
+
`);for(let s of e.memories)r.run(s.id,"_migrated",s.title,s.content,(s.tags||[]).join(","),null,s.userTriggered?1:0,s.confidence??null,s.observationCount??0,s.createdAt,s.updatedAt)}}}catch{}},"up")},{version:11,name:"agent-sessions",up:c(n=>{n.run(`
|
|
432
432
|
-- =======================================================================
|
|
433
433
|
-- Agent Sessions: Track AI agent work sessions across compactions
|
|
434
434
|
-- =======================================================================
|
|
@@ -461,7 +461,7 @@ CREATE TABLE velocity_sprints (
|
|
|
461
461
|
|
|
462
462
|
CREATE INDEX IF NOT EXISTS idx_user_prompts_project ON user_prompts(project_id);
|
|
463
463
|
CREATE INDEX IF NOT EXISTS idx_user_prompts_session ON user_prompts(session_id);
|
|
464
|
-
`);try{
|
|
464
|
+
`);try{n.run("ALTER TABLE memories ADD COLUMN session_id TEXT")}catch{}},"up")},{version:12,name:"task-body-and-comments",up:c(n=>{try{n.run("ALTER TABLE queue_tasks ADD COLUMN body TEXT")}catch{}n.run(`
|
|
465
465
|
CREATE TABLE IF NOT EXISTS queue_task_comments (
|
|
466
466
|
id TEXT PRIMARY KEY,
|
|
467
467
|
task_id TEXT NOT NULL,
|
|
@@ -472,7 +472,7 @@ CREATE TABLE velocity_sprints (
|
|
|
472
472
|
);
|
|
473
473
|
|
|
474
474
|
CREATE INDEX IF NOT EXISTS idx_qtc_task_id ON queue_task_comments(task_id);
|
|
475
|
-
`)},"up")},{version:13,name:"workflow-rules-v2",up:c(
|
|
475
|
+
`)},"up")},{version:13,name:"workflow-rules-v2",up:c(n=>{try{n.run("ALTER TABLE workflow_rules ADD COLUMN when_expr TEXT")}catch{}try{n.run("ALTER TABLE workflow_rules ADD COLUMN parallel INTEGER NOT NULL DEFAULT 1")}catch{}n.run(`
|
|
476
476
|
CREATE TABLE IF NOT EXISTS workflow_rule_cache (
|
|
477
477
|
rule_id INTEGER NOT NULL,
|
|
478
478
|
context_hash TEXT NOT NULL,
|
|
@@ -482,7 +482,7 @@ CREATE TABLE velocity_sprints (
|
|
|
482
482
|
);
|
|
483
483
|
|
|
484
484
|
CREATE INDEX IF NOT EXISTS idx_wrc_rule ON workflow_rule_cache(rule_id);
|
|
485
|
-
`)},"up")},{version:14,name:"workflow-rules-trust-source",up:c(
|
|
485
|
+
`)},"up")},{version:14,name:"workflow-rules-trust-source",up:c(n=>{try{n.run("ALTER TABLE workflow_rules ADD COLUMN trust_source TEXT NOT NULL DEFAULT 'local'")}catch{}},"up")},{version:15,name:"disable-orphan-workflow-rules",up:c(n=>{let e=["pause","resume","reopen","next","dash","bug","idea","linear","jira","tokens","velocity","plan"].map(r=>`'${r}'`).join(",");n.run(`UPDATE workflow_rules SET enabled = 0 WHERE command IN (${e}) AND enabled = 1`)},"up")},{version:16,name:"specs-and-task-linkage",up:c(n=>{n.run(`
|
|
486
486
|
CREATE TABLE IF NOT EXISTS specs (
|
|
487
487
|
id TEXT PRIMARY KEY,
|
|
488
488
|
title TEXT NOT NULL,
|
|
@@ -498,7 +498,7 @@ CREATE TABLE velocity_sprints (
|
|
|
498
498
|
|
|
499
499
|
CREATE INDEX IF NOT EXISTS idx_specs_status ON specs(status);
|
|
500
500
|
CREATE INDEX IF NOT EXISTS idx_specs_created ON specs(created_at);
|
|
501
|
-
`);try{
|
|
501
|
+
`);try{n.run("ALTER TABLE tasks ADD COLUMN linked_spec_id TEXT"),n.run("CREATE INDEX IF NOT EXISTS idx_tasks_spec ON tasks(linked_spec_id)")}catch{}},"up")},{version:17,name:"sync-engine-wire-format",up:c(n=>{let t=[["server_event_id","INTEGER"],["entity_type","TEXT"],["entity_id","TEXT"],["event_type","TEXT"],["device_id","TEXT"],["origin_device_id","TEXT"],["content_hash","TEXT"],["revision_count","INTEGER NOT NULL DEFAULT 1"]];for(let[e,r]of t)try{n.run(`ALTER TABLE events ADD COLUMN ${e} ${r}`)}catch{}try{n.run("CREATE INDEX IF NOT EXISTS idx_events_server_id ON events(server_event_id)"),n.run("CREATE INDEX IF NOT EXISTS idx_events_entity ON events(entity_type, entity_id)"),n.run("CREATE INDEX IF NOT EXISTS idx_events_device ON events(device_id)")}catch{}n.run(`
|
|
502
502
|
CREATE TABLE IF NOT EXISTS sync_pending (
|
|
503
503
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
504
504
|
project_id TEXT NOT NULL,
|
|
@@ -512,7 +512,7 @@ CREATE TABLE velocity_sprints (
|
|
|
512
512
|
|
|
513
513
|
CREATE INDEX IF NOT EXISTS idx_sync_pending_project ON sync_pending(project_id);
|
|
514
514
|
CREATE INDEX IF NOT EXISTS idx_sync_pending_entity ON sync_pending(entity_type, entity_id);
|
|
515
|
-
`),
|
|
515
|
+
`),n.run(`
|
|
516
516
|
CREATE TABLE IF NOT EXISTS sync_cursors (
|
|
517
517
|
user_id TEXT,
|
|
518
518
|
device_id TEXT NOT NULL,
|
|
@@ -523,7 +523,7 @@ CREATE TABLE velocity_sprints (
|
|
|
523
523
|
);
|
|
524
524
|
|
|
525
525
|
CREATE INDEX IF NOT EXISTS idx_sync_cursors_project ON sync_cursors(project_id);
|
|
526
|
-
`)},"up")},{version:18,name:"specs-shipped-sha",up:c(
|
|
526
|
+
`)},"up")},{version:18,name:"specs-shipped-sha",up:c(n=>{try{n.run("ALTER TABLE specs ADD COLUMN shipped_sha TEXT")}catch{}},"up")},{version:19,name:"sync-applied-hashes",up:c(n=>{n.run(`
|
|
527
527
|
CREATE TABLE IF NOT EXISTS sync_applied_hashes (
|
|
528
528
|
entity_type TEXT NOT NULL,
|
|
529
529
|
entity_id TEXT NOT NULL,
|
|
@@ -531,7 +531,7 @@ CREATE TABLE velocity_sprints (
|
|
|
531
531
|
applied_at TEXT NOT NULL,
|
|
532
532
|
PRIMARY KEY (entity_type, entity_id)
|
|
533
533
|
);
|
|
534
|
-
`)},"up")},{version:20,name:"events-type-timestamp-index",up:c(
|
|
534
|
+
`)},"up")},{version:20,name:"events-type-timestamp-index",up:c(n=>{n.run("CREATE INDEX IF NOT EXISTS idx_events_type_ts ON events(type, timestamp DESC)")},"up")},{version:21,name:"memories-type-and-fts-backfill",up:c(n=>{try{n.run("ALTER TABLE memories ADD COLUMN type TEXT")}catch{}try{n.run("ALTER TABLE memories ADD COLUMN provenance TEXT")}catch{}n.run(`
|
|
535
535
|
INSERT INTO memories
|
|
536
536
|
(id, project_id, title, content, tags, type, provenance, user_triggered,
|
|
537
537
|
created_at, updated_at)
|
|
@@ -549,7 +549,7 @@ CREATE TABLE velocity_sprints (
|
|
|
549
549
|
FROM events e
|
|
550
550
|
WHERE e.type LIKE 'remember.%'
|
|
551
551
|
AND NOT EXISTS (SELECT 1 FROM memories m WHERE m.id = 'mem_' || e.id)
|
|
552
|
-
`)},"up")},{version:22,name:"memory-embeddings-store",up:c(
|
|
552
|
+
`)},"up")},{version:22,name:"memory-embeddings-store",up:c(n=>{n.run(`
|
|
553
553
|
CREATE TABLE IF NOT EXISTS memory_embeddings (
|
|
554
554
|
memory_id TEXT PRIMARY KEY,
|
|
555
555
|
vector BLOB NOT NULL,
|
|
@@ -557,7 +557,7 @@ CREATE TABLE velocity_sprints (
|
|
|
557
557
|
dims INTEGER NOT NULL,
|
|
558
558
|
created_at TEXT NOT NULL
|
|
559
559
|
)
|
|
560
|
-
`)},"up")},{version:23,name:"memory-usefulness-ledger",up:c(
|
|
560
|
+
`)},"up")},{version:23,name:"memory-usefulness-ledger",up:c(n=>{n.run(`
|
|
561
561
|
CREATE TABLE IF NOT EXISTS memory_usefulness (
|
|
562
562
|
memory_id TEXT PRIMARY KEY,
|
|
563
563
|
score REAL NOT NULL DEFAULT 0,
|
|
@@ -565,111 +565,111 @@ CREATE TABLE velocity_sprints (
|
|
|
565
565
|
fetch_count INTEGER NOT NULL DEFAULT 0,
|
|
566
566
|
last_used_at TEXT NOT NULL
|
|
567
567
|
)
|
|
568
|
-
`)},"up")},{version:24,name:"memory-surface-log",up:c(
|
|
568
|
+
`)},"up")},{version:24,name:"memory-surface-log",up:c(n=>{n.run(`
|
|
569
569
|
CREATE TABLE IF NOT EXISTS memory_surface_log (
|
|
570
570
|
memory_id TEXT NOT NULL,
|
|
571
571
|
task_id TEXT NOT NULL,
|
|
572
572
|
created_at TEXT NOT NULL,
|
|
573
573
|
PRIMARY KEY (memory_id, task_id)
|
|
574
574
|
)
|
|
575
|
-
`)},"up")},{version:25,name:"memory-dedup-content-hash",up:c(
|
|
576
|
-
FROM events WHERE type LIKE 'memory.remember.%' ORDER BY id ASC`).all(),l=new Set,d=
|
|
575
|
+
`)},"up")},{version:25,name:"memory-dedup-content-hash",up:c(n=>{let t=c(p=>Number(String(p).replace(/^mem[_-]/i,""))||0,"numOf"),e=n.prepare("SELECT id, content, content_hash FROM memories").all(),r=n.prepare("UPDATE memories SET content_hash = ? WHERE id = ?");for(let p of e)p.content_hash||r.run(kt(p.content??""),p.id);let s=n.prepare("SELECT id, type, content_hash FROM memories WHERE deleted_at IS NULL").all(),i=new Map;for(let p of s){if(!p.content_hash)continue;let g=`${p.type??""}::${p.content_hash}`,T=t(p.id),L=i.get(g);(L===void 0||T<L)&&i.set(g,T)}let o=new Date().toISOString(),a=n.prepare("UPDATE memories SET deleted_at = ? WHERE id = ?");for(let p of s){if(!p.content_hash)continue;let g=`${p.type??""}::${p.content_hash}`;i.get(g)!==t(p.id)&&a.run(o,p.id)}let u=n.prepare(`SELECT id, type, json_extract(data, '$.content') AS content
|
|
576
|
+
FROM events WHERE type LIKE 'memory.remember.%' ORDER BY id ASC`).all(),l=new Set,d=n.prepare("DELETE FROM events WHERE id = ?");for(let p of u){if(p.content==null)continue;let g=`${p.type}::${kt(p.content)}`;if(l.has(g)){d.run(p.id);continue}l.add(g)}},"up")},{version:26,name:"events-type-id-index",up:c(n=>{n.run("CREATE INDEX IF NOT EXISTS idx_events_type_id ON events(type, id DESC)")},"up")}]});function Ui(){return typeof globalThis<"u"&&"Bun"in globalThis?"bun":"node"}function an(){return Ui()==="bun"}var cn=E(()=>{"use strict";c(Ui,"detectRuntime");c(an,"isBun")});function un(n){let t=$i(n);return t.run("PRAGMA journal_mode = WAL"),t.run("PRAGMA busy_timeout = 5000"),t}function $i(n){if(an()){let{Database:r}=Tr("bun:sqlite");return new r(n,{create:!0})}let t;try{({DatabaseSync:t}=Tr("node:sqlite"))}catch(r){throw new Error(`prjct needs SQLite: run on Bun, or Node >=22.5 with --experimental-sqlite (the \`prjct\` launcher sets this automatically \u2014 invoke \`prjct\`, not \`node dist/bin/prjct.mjs\` directly). Underlying error: ${r instanceof Error?r.message:String(r)}`)}let e=new t(n);return Xi(e)}function Xi(n){let t=0,e=0,r={prepare:c(s=>n.prepare(s),"prepare"),run:c(s=>{n.exec(s)},"run"),close:c(()=>n.close(),"close"),transaction:c(s=>{let i=c(a=>(...u)=>{if(t>0){let l=`prjct_sp_${++e}`;n.exec(`SAVEPOINT ${l}`),t++;try{let d=s(...u.length?u:[r]);return n.exec(`RELEASE ${l}`),d}catch(d){throw n.exec(`ROLLBACK TO ${l}`),n.exec(`RELEASE ${l}`),d}finally{t--}}n.exec(a),t++;try{let l=s(...u.length?u:[r]);return n.exec("COMMIT"),l}catch(l){throw n.exec("ROLLBACK"),l}finally{t--}},"make"),o=i("BEGIN");return o.deferred=i("BEGIN DEFERRED"),o.immediate=i("BEGIN IMMEDIATE"),o.exclusive=i("BEGIN EXCLUSIVE"),o},"transaction")};return r}var ln=E(()=>{"use strict";cn();c(un,"openDatabase");c($i,"openRaw");c(Xi,"adaptNodeSqlite")});import St from"node:fs";import pn from"node:path";function dn(n,t){let e=n.transaction(t);return typeof e.immediate=="function"?e.immediate(n):e(n)}var Wi,ve,k,h,j=E(()=>{"use strict";at();on();ln();c(dn,"runImmediate");Wi=3,ve=class{static{c(this,"PrjctDatabase")}connections=new Map;accessOrder=[];statementCache=new WeakMap;prepareCached(t,e){let r=this.statementCache.get(t);r||(r=new Map,this.statementCache.set(t,r));let s=r.get(e);if(s)return s;let i=t.prepare(e);return r.set(e,i),i}getDbPath(t){return pn.join(R.getGlobalProjectPath(t),"prjct.db")}getDb(t){let e=this.connections.get(t);if(e)return this.touchAccessOrder(t),e;this.connections.size>=Wi&&this.evictLru();let r=this.getDbPath(t),s=pn.dirname(r);St.existsSync(s)||St.mkdirSync(s,{recursive:!0});let i=un(r);return i.run("PRAGMA synchronous = NORMAL"),i.run("PRAGMA cache_size = -2000"),i.run("PRAGMA temp_store = MEMORY"),i.run("PRAGMA mmap_size = 33554432"),this.runMigrations(i,r),this.connections.set(t,i),this.touchAccessOrder(t),i}close(t){if(t){let e=this.connections.get(t);e&&(this.statementCache.delete(e),e.close(),this.connections.delete(t),this.accessOrder=this.accessOrder.filter(r=>r!==t))}else this.connections.forEach(e=>{this.statementCache.delete(e),e.close()}),this.connections.clear(),this.accessOrder=[]}touchAccessOrder(t){this.accessOrder=this.accessOrder.filter(e=>e!==t),this.accessOrder.push(t)}evictLru(){if(this.accessOrder.length===0)return;let t=this.accessOrder.shift(),e=this.connections.get(t);e&&(this.statementCache.delete(e),e.close(),this.connections.delete(t))}checkpointAll(){for(let[t,e]of this.connections)try{this.prepareCached(e,"PRAGMA wal_checkpoint(PASSIVE)").get()}catch{}}exists(t){return St.existsSync(this.getDbPath(t))}getDoc(t,e){let r=this.getDb(t),s=this.prepareCached(r,"SELECT data FROM kv_store WHERE key = ?").get(e);return s?JSON.parse(s.data):null}setDoc(t,e,r){let s=this.getDb(t),i=JSON.stringify(r),o=new Date().toISOString();this.prepareCached(s,"INSERT OR REPLACE INTO kv_store (key, data, updated_at) VALUES (?, ?, ?)").run(e,i,o)}getDocWithStamp(t,e){let r=this.getDb(t),s=this.prepareCached(r,"SELECT data, updated_at FROM kv_store WHERE key = ?").get(e);return s?{data:JSON.parse(s.data),updatedAt:s.updated_at}:null}nextKvStamp(t,e){let r=this.prepareCached(t,"SELECT updated_at FROM kv_store WHERE key = ?").get(e),s=new Date().toISOString(),i=r?.updated_at;return!i||s>i?s:new Date(new Date(i).getTime()+1).toISOString()}casSetDoc(t,e,r,s){let i=this.getDb(t),o=JSON.stringify(r),a=this.nextKvStamp(i,e);return s===null?this.prepareCached(i,"INSERT INTO kv_store (key, data, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO NOTHING").run(e,o,a).changes===1:this.prepareCached(i,"UPDATE kv_store SET data = ?, updated_at = ? WHERE key = ? AND updated_at = ?").run(o,a,e,s).changes===1}deleteDoc(t,e){let r=this.getDb(t);this.prepareCached(r,"DELETE FROM kv_store WHERE key = ?").run(e)}hasDoc(t,e){let r=this.getDb(t);return this.prepareCached(r,"SELECT 1 FROM kv_store WHERE key = ?").get(e)!==null}listDocsByPrefix(t,e){let r=this.getDb(t);return this.prepareCached(r,"SELECT key, data FROM kv_store WHERE key LIKE ? || '%' ORDER BY key").all(e).map(i=>({key:i.key,data:JSON.parse(i.data)}))}appendEvent(t,e,r,s){let i=this.getDb(t),o=new Date().toISOString(),u=this.prepareCached(i,"INSERT INTO events (type, task_id, data, timestamp) VALUES (?, ?, ?, ?)").run(e,s??null,JSON.stringify(r),o).lastInsertRowid;return typeof u=="bigint"?Number(u):u??null}getEvents(t,e,r=100){let s=this.getDb(t);return e?this.prepareCached(s,"SELECT * FROM events WHERE type = ? ORDER BY id DESC LIMIT ?").all(e,r):this.prepareCached(s,"SELECT * FROM events ORDER BY id DESC LIMIT ?").all(r)}query(t,e,...r){let s=this.getDb(t);return this.prepareCached(s,e).all(...r)}run(t,e,...r){let s=this.getDb(t);return this.prepareCached(s,e).run(...r)}get(t,e,...r){let s=this.getDb(t);return this.prepareCached(s,e).get(...r)??null}transaction(t,e){let r=this.getDb(t);return dn(r,e)}runMigrations(t,e){t.run(`
|
|
577
577
|
CREATE TABLE IF NOT EXISTS _migrations (
|
|
578
578
|
version INTEGER PRIMARY KEY,
|
|
579
579
|
name TEXT NOT NULL,
|
|
580
580
|
applied_at TEXT NOT NULL
|
|
581
581
|
)
|
|
582
|
-
`);let r=new Set(t.prepare("SELECT version FROM _migrations").all().map(i=>i.version)),n=es.filter(i=>!r.has(i.version));if(n.length!==0){if(e&&r.size>0)try{let i=`${e}.pre-migrate.bak`;kt.existsSync(i)&&kt.rmSync(i,{force:!0}),t.prepare("VACUUM INTO ?").run(i)}catch(i){console.warn(`prjct: pre-migration backup failed (continuing): ${i?.message??i}`)}for(let i of n)cs(t,()=>{i.up(t),t.prepare("INSERT INTO _migrations (version, name, applied_at) VALUES (?, ?, ?)").run(i.version,i.name,new Date().toISOString())})}}getMigrations(t){return this.getDb(t).prepare("SELECT * FROM _migrations ORDER BY version").all()}getSchemaVersion(t){return this.getDb(t).prepare("SELECT MAX(version) as version FROM _migrations").get()?.version??0}},k=new we,h=k});function Yi(s){return s instanceof xe}function Pe(s){return Yi(s)||s instanceof Error?s.message:typeof s=="string"?s:"Unknown error"}var xe,ys=E(()=>{"use strict";xe=class extends Error{static{c(this,"PrjctError")}code;isOperational;constructor(t,e="PRJCT_ERROR"){super(t),this.name="PrjctError",this.code=e,this.isOperational=!0,Error.captureStackTrace?.(this,this.constructor)}};c(Yi,"isPrjctError");c(Pe,"getErrorMessage")});import Ae from"node:fs";import Ut from"node:path";function Ts(){if(wt)return wt;let s=__dirname;for(let t=0;t<5;t++){let e=Ut.join(s,"package.json");if(Ae.existsSync(e))try{if(JSON.parse(Ae.readFileSync(e,"utf-8")).name==="prjct-cli")return wt=s,s}catch{}s=Ut.dirname(s)}return wt=Ut.join(__dirname,"..","..",".."),wt}function Ji(){if(ut)return ut;let s=process.env.PRJCT_VERSION;if(s&&/^\d+\.\d+\.\d+/.test(s))return ut=s,ut;try{let t=Ut.join(Ts(),"package.json");return ut=JSON.parse(Ae.readFileSync(t,"utf-8")).version,ut}catch(t){return process.env.PRJCT_DEBUG==="1"&&console.error("Failed to read version from package.json:",Sr(t)),"0.0.0"}}var ut,wt,Ne,Nu,Es=E(()=>{"use strict";tt();ut=null,wt=null;c(Ts,"getPackageRoot");c(Ji,"getVersion");Ne=Ji(),Nu=Ts()});async function Xt(s){try{let{stdout:t}=await b(s,{timeout:5e3});return{success:!0,output:t.trim()}}catch{return{success:!1,output:""}}}async function zi(){let s=await Xt("gh api user --jq .login");return s.success&&s.output||(s=await Xt("git config --global github.user"),s.success&&s.output)?s.output:null}async function Ki(){let s=await Xt("git config user.name");return s.success&&s.output?s.output:null}async function Vi(){let s=await Xt("git config user.email");return s.success&&s.output?s.output:null}async function ks(){let[s,t,e]=await Promise.all([zi(),Ki(),Vi()]);return{github:s,email:e,name:t||s||"Unknown"}}var Ss=E(()=>{"use strict";ot();c(Xt,"execCommand");c(zi,"detectGitHubUsername");c(Ki,"detectGitName");c(Vi,"detectGitEmail");c(ks,"detect")});var _s={};K(_s,{default:()=>B});import Ie from"node:fs/promises";import Zi from"node:path";import*as Wt from"jsonc-parser";function ws(s){let t=[],e=Wt.parse(s,t,{allowTrailingComma:!0,disallowComments:!1});if(t.length>0){let r=t[0];throw new SyntaxError(`JSON parse error at offset ${r.offset}: ${Wt.printParseErrorCode(r.error)}`)}return e}var Ce,to,B,_t=E(()=>{"use strict";ys();tt();N();$();Es();Ss();at();c(ws,"parseJsonc");Ce=class{static{c(this,"ConfigManager")}async readConfig(t){try{let e=R.getLocalConfigPath(t),r=await Ie.readFile(e,"utf-8");return ws(r)}catch(e){return M(e)||console.warn(`Warning: Could not read config at ${t}: ${Pe(e)}`),null}}async writeConfig(t,e){let r=R.getLocalConfigPath(t);await F(r,e)}async readGlobalConfig(t){try{let e=R.getGlobalProjectConfigPath(t),r=await Ie.readFile(e,"utf-8");return ws(r)}catch(e){return M(e)||console.warn(`Warning: Could not read global config for ${t}: ${Pe(e)}`),null}}async writeGlobalConfig(t,e){let r=R.getGlobalProjectConfigPath(t);await F(r,e)}async ensureGlobalConfig(t){let e=await this.readGlobalConfig(t);if(!e){let r=f();e={projectId:t,authors:[],version:Ne,lastSync:r},await this.writeGlobalConfig(t,e)}return e}async createConfig(t,e){let r=R.generateProjectId(t),n=R.getGlobalProjectPath(r),i=R.getDisplayPath(n),o=f(),a={projectId:r,dataPath:i,showMetrics:!0};await this.writeConfig(t,a);let u={projectId:r,authors:[{name:e.name||"Unknown",email:e.email||"",github:e.github||"",firstContribution:o,lastActivity:o}],version:Ne,created:o,lastSync:o};return await this.writeGlobalConfig(r,u),a}async updateLastSync(t){let e=await this.getProjectId(t),r=await this.readGlobalConfig(e);r&&(r.lastSync=f(),await this.writeGlobalConfig(e,r))}validateConfig(t){return!(!t||!t.projectId||!t.dataPath)}async needsMigration(t){if(!await R.hasLegacyStructure(t))return!1;if(!await R.hasConfig(t))return!0;let n=await this.readConfig(t);if(!n||!n.projectId)return!0;let i=R.getGlobalProjectPath(n.projectId);try{return(await Ie.readdir(Zi.join(i,"core"))).length===0}catch(o){return M(o),!0}}async getProjectId(t){let e=await this.readConfig(t);if(e?.projectId)return e.projectId;try{let{worktreeService:r}=await Promise.resolve().then(()=>(pe(),le));if(await r.detect(t)){let i=await r.getMainWorktree(t);if(i!==t){let o=await this.readConfig(i);if(o?.projectId)return o.projectId}}}catch{}return""}async findAuthor(t,e){let r=await this.readGlobalConfig(t);return!r||!r.authors?null:r.authors.find(n=>n.github===e)||null}async addAuthor(t,e){let r=await this.ensureGlobalConfig(t);if(r.authors.some(o=>o.github===e.github))return;let i=f();r.authors.push({name:e.name||"Unknown",email:e.email||"",github:e.github||"",firstContribution:i,lastActivity:i}),r.lastSync=i,await this.writeGlobalConfig(t,r)}async updateAuthorActivity(t,e){let r=await this.readGlobalConfig(t);if(!r||!r.authors)return;let n=r.authors.find(i=>i.github===e);n&&(n.lastActivity=f(),r.lastSync=n.lastActivity,await this.writeGlobalConfig(t,r))}async getCurrentAuthor(t){let e=await ks(),r=await this.getProjectId(t);return await this.addAuthor(r,{name:e.name??void 0,email:e.email??void 0,github:e.github??void 0}),e.github||e.name||"Unknown"}async isConfigured(t){let e=await this.readConfig(t);return this.validateConfig(e)}async getShowMetrics(t){return(await this.readConfig(t))?.showMetrics??!0}async setShowMetrics(t,e){let r=await this.readConfig(t);r&&(r.showMetrics=e,await this.writeConfig(t,r))}async getConfigWithDefaults(t){let e=await this.readConfig(t);if(e)return e;let r=R.generateProjectId(t);return{projectId:r,dataPath:R.getDisplayPath(R.getGlobalProjectPath(r))}}},to=new Ce,B=to});import{z as m}from"zod";var ro,Bt,so,no,De,Rs,xs,Ps,As,vs,io,oo,ao,Ns,co,Is,Ht=E(()=>{"use strict";ge();ro=m.enum(["low","medium","high","critical"]),Bt=m.enum(["feature","bug","improvement","chore"]),so=m.enum(["active","backlog","previously_active"]),no=m.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),De=m.object({title:m.string(),description:m.string(),filesChanged:m.array(m.object({path:m.string(),action:m.enum(["created","modified","deleted"])})),whatWasDone:m.array(m.string()).min(1),outputForNextAgent:m.string().min(1),notes:m.string().optional()}),Rs=m.object({output:m.string().min(1,"Subtask output is required"),summary:De}),xs=m.object({id:m.string(),description:m.string(),domain:m.string(),agent:m.string(),status:no,dependsOn:m.array(m.string()),startedAt:m.string().optional(),completedAt:m.string().optional(),output:m.string().optional(),summary:De.optional(),skipReason:m.string().optional(),blockReason:m.string().optional(),estimatedPoints:m.number().optional(),estimatedMinutes:m.number().optional()}),Ps=m.object({completed:m.number(),total:m.number(),percentage:m.number()}),As=m.object({id:m.string(),description:m.string(),type:Bt.optional(),startedAt:m.string(),sessionId:m.string(),featureId:m.string().optional(),subtasks:m.array(xs).optional(),currentSubtaskIndex:m.number().optional(),subtaskProgress:Ps.optional(),linearId:m.string().optional(),linearUuid:m.string().optional(),linkedSpecId:m.string().optional(),estimatedPoints:m.number().optional(),estimatedMinutes:m.number().optional(),modelMetadata:me.optional(),tokensIn:m.number().optional(),tokensOut:m.number().optional(),parentDescription:m.string().optional(),branch:m.string().optional(),prUrl:m.string().optional()}),vs=m.object({id:m.string(),description:m.string(),status:m.literal("paused"),startedAt:m.string(),pausedAt:m.string(),pauseReason:m.string().optional(),type:Bt.optional(),sessionId:m.string().optional(),featureId:m.string().optional(),subtasks:m.array(xs).optional(),currentSubtaskIndex:m.number().optional(),subtaskProgress:Ps.optional(),linearId:m.string().optional(),linearUuid:m.string().optional(),estimatedPoints:m.number().optional(),estimatedMinutes:m.number().optional(),modelMetadata:me.optional(),tokensIn:m.number().optional(),tokensOut:m.number().optional()}),io=m.object({stackConfirmed:m.array(m.string()).optional(),patternsDiscovered:m.array(m.string()).optional(),agentAccuracy:m.array(m.object({agent:m.string(),rating:m.enum(["helpful","neutral","inaccurate"]),note:m.string().optional()})).optional(),issuesEncountered:m.array(m.string()).optional()}),oo=m.object({taskId:m.string(),title:m.string(),classification:Bt,startedAt:m.string(),completedAt:m.string(),subtaskCount:m.number(),subtaskSummaries:m.array(De),outcome:m.string(),branchName:m.string(),linearId:m.string().optional(),linearUuid:m.string().optional(),prUrl:m.string().optional(),feedback:io.optional(),tokensIn:m.number().optional(),tokensOut:m.number().optional()}),ao=As.extend({workspaceId:m.string(),worktreePath:m.string().optional(),agentSessionId:m.string().optional(),jiraId:m.string().optional(),jiraUuid:m.string().optional(),dispatchedFrom:m.string().optional()}),Ns=m.object({currentTask:As.nullable(),previousTask:vs.nullable().optional(),pausedTasks:m.array(vs).optional(),taskHistory:m.array(oo).optional(),activeTasks:m.array(ao).optional(),lastUpdated:m.string()}),co=m.object({id:m.string(),description:m.string(),body:m.string().optional(),priority:ro,type:Bt,featureId:m.string().optional(),originFeature:m.string().optional(),completed:m.boolean(),completedAt:m.string().optional(),createdAt:m.string(),section:so,agent:m.string().optional(),groupName:m.string().optional(),groupId:m.string().optional()}),Is=m.object({tasks:m.array(co),lastUpdated:m.string()})});import uo from"node:crypto";function H(){return uo.randomUUID()}var vt=E(()=>{"use strict";c(H,"generateUUID")});var Me,rt,Cs=E(()=>{"use strict";N();j();Me=class{static{c(this,"SyncPendingStorage")}append(t,e){let r=f(),n=JSON.stringify(e);return e.entityType&&e.entityId&&e.contentHash&&h.run(t,`DELETE FROM sync_pending
|
|
582
|
+
`);let r=new Set(t.prepare("SELECT version FROM _migrations").all().map(i=>i.version)),s=sn.filter(i=>!r.has(i.version));if(s.length!==0){if(e&&r.size>0)try{let i=`${e}.pre-migrate.bak`;St.existsSync(i)&&St.rmSync(i,{force:!0}),t.prepare("VACUUM INTO ?").run(i)}catch(i){console.warn(`prjct: pre-migration backup failed (continuing): ${i?.message??i}`)}for(let i of s)dn(t,()=>{i.up(t),t.prepare("INSERT INTO _migrations (version, name, applied_at) VALUES (?, ?, ?)").run(i.version,i.name,new Date().toISOString())})}}getMigrations(t){return this.getDb(t).prepare("SELECT * FROM _migrations ORDER BY version").all()}getSchemaVersion(t){return this.getDb(t).prepare("SELECT MAX(version) as version FROM _migrations").get()?.version??0}},k=new ve,h=k});function Zi(n){return n instanceof Ne}function Ie(n){return Zi(n)||n instanceof Error?n.message:typeof n=="string"?n:"Unknown error"}var Ne,Sn=E(()=>{"use strict";Ne=class extends Error{static{c(this,"PrjctError")}code;isOperational;constructor(t,e="PRJCT_ERROR"){super(t),this.name="PrjctError",this.code=e,this.isOperational=!0,Error.captureStackTrace?.(this,this.constructor)}};c(Zi,"isPrjctError");c(Ie,"getErrorMessage")});import Ce from"node:fs";import Wt from"node:path";function wn(){if(_t)return _t;let n=__dirname;for(let t=0;t<5;t++){let e=Wt.join(n,"package.json");if(Ce.existsSync(e))try{if(JSON.parse(Ce.readFileSync(e,"utf-8")).name==="prjct-cli")return _t=n,n}catch{}n=Wt.dirname(n)}return _t=Wt.join(__dirname,"..","..",".."),_t}function to(){if(ut)return ut;let n=process.env.PRJCT_VERSION;if(n&&/^\d+\.\d+\.\d+/.test(n))return ut=n,ut;try{let t=Wt.join(wn(),"package.json");return ut=JSON.parse(Ce.readFileSync(t,"utf-8")).version,ut}catch(t){return process.env.PRJCT_DEBUG==="1"&&console.error("Failed to read version from package.json:",Ct(t)),"0.0.0"}}var ut,_t,Le,ju,_n=E(()=>{"use strict";tt();ut=null,_t=null;c(wn,"getPackageRoot");c(to,"getVersion");Le=to(),ju=wn()});async function Bt(n){try{let{stdout:t}=await b(n,{timeout:5e3});return{success:!0,output:t.trim()}}catch{return{success:!1,output:""}}}async function eo(){let n=await Bt("gh api user --jq .login");return n.success&&n.output||(n=await Bt("git config --global github.user"),n.success&&n.output)?n.output:null}async function ro(){let n=await Bt("git config user.name");return n.success&&n.output?n.output:null}async function no(){let n=await Bt("git config user.email");return n.success&&n.output?n.output:null}async function bn(){let[n,t,e]=await Promise.all([eo(),ro(),no()]);return{github:n,email:e,name:t||n||"Unknown"}}var vn=E(()=>{"use strict";rt();c(Bt,"execCommand");c(eo,"detectGitHubUsername");c(ro,"detectGitName");c(no,"detectGitEmail");c(bn,"detect")});var xn={};K(xn,{default:()=>B});import De from"node:fs/promises";import io from"node:path";import*as Ht from"jsonc-parser";function Rn(n){let t=[],e=Ht.parse(n,t,{allowTrailingComma:!0,disallowComments:!1});if(t.length>0){let r=t[0];throw new SyntaxError(`JSON parse error at offset ${r.offset}: ${Ht.printParseErrorCode(r.error)}`)}return e}var Oe,oo,B,bt=E(()=>{"use strict";Sn();tt();N();U();_n();vn();at();c(Rn,"parseJsonc");Oe=class{static{c(this,"ConfigManager")}async readConfig(t){try{let e=R.getLocalConfigPath(t),r=await De.readFile(e,"utf-8");return Rn(r)}catch(e){return M(e)||console.warn(`Warning: Could not read config at ${t}: ${Ie(e)}`),null}}async writeConfig(t,e){let r=R.getLocalConfigPath(t);await F(r,e)}async readGlobalConfig(t){try{let e=R.getGlobalProjectConfigPath(t),r=await De.readFile(e,"utf-8");return Rn(r)}catch(e){return M(e)||console.warn(`Warning: Could not read global config for ${t}: ${Ie(e)}`),null}}async writeGlobalConfig(t,e){let r=R.getGlobalProjectConfigPath(t);await F(r,e)}async ensureGlobalConfig(t){let e=await this.readGlobalConfig(t);if(!e){let r=f();e={projectId:t,authors:[],version:Le,lastSync:r},await this.writeGlobalConfig(t,e)}return e}async createConfig(t,e){let r=R.generateProjectId(t),s=R.getGlobalProjectPath(r),i=R.getDisplayPath(s),o=f(),a={projectId:r,dataPath:i,showMetrics:!0};await this.writeConfig(t,a);let u={projectId:r,authors:[{name:e.name||"Unknown",email:e.email||"",github:e.github||"",firstContribution:o,lastActivity:o}],version:Le,created:o,lastSync:o};return await this.writeGlobalConfig(r,u),a}async updateLastSync(t){let e=await this.getProjectId(t),r=await this.readGlobalConfig(e);r&&(r.lastSync=f(),await this.writeGlobalConfig(e,r))}validateConfig(t){return!(!t||!t.projectId||!t.dataPath)}async needsMigration(t){if(!await R.hasLegacyStructure(t))return!1;if(!await R.hasConfig(t))return!0;let s=await this.readConfig(t);if(!s||!s.projectId)return!0;let i=R.getGlobalProjectPath(s.projectId);try{return(await De.readdir(io.join(i,"core"))).length===0}catch(o){return M(o),!0}}async getProjectId(t){let e=await this.readConfig(t);if(e?.projectId)return e.projectId;try{let{worktreeService:r}=await Promise.resolve().then(()=>(ge(),me));if(await r.detect(t)){let i=await r.getMainWorktree(t);if(i!==t){let o=await this.readConfig(i);if(o?.projectId)return o.projectId}}}catch{}return""}async findAuthor(t,e){let r=await this.readGlobalConfig(t);return!r||!r.authors?null:r.authors.find(s=>s.github===e)||null}async addAuthor(t,e){let r=await this.ensureGlobalConfig(t);if(r.authors.some(o=>o.github===e.github))return;let i=f();r.authors.push({name:e.name||"Unknown",email:e.email||"",github:e.github||"",firstContribution:i,lastActivity:i}),r.lastSync=i,await this.writeGlobalConfig(t,r)}async updateAuthorActivity(t,e){let r=await this.readGlobalConfig(t);if(!r||!r.authors)return;let s=r.authors.find(i=>i.github===e);s&&(s.lastActivity=f(),r.lastSync=s.lastActivity,await this.writeGlobalConfig(t,r))}async getCurrentAuthor(t){let e=await bn(),r=await this.getProjectId(t);return await this.addAuthor(r,{name:e.name??void 0,email:e.email??void 0,github:e.github??void 0}),e.github||e.name||"Unknown"}async isConfigured(t){let e=await this.readConfig(t);return this.validateConfig(e)}async getShowMetrics(t){return(await this.readConfig(t))?.showMetrics??!0}async setShowMetrics(t,e){let r=await this.readConfig(t);r&&(r.showMetrics=e,await this.writeConfig(t,r))}async getConfigWithDefaults(t){let e=await this.readConfig(t);if(e)return e;let r=R.generateProjectId(t);return{projectId:r,dataPath:R.getDisplayPath(R.getGlobalProjectPath(r))}}},oo=new Oe,B=oo});import{z as m}from"zod";var co,qt,uo,lo,Me,Nn,In,Cn,Ln,An,po,mo,go,Dn,fo,On,Gt=E(()=>{"use strict";ye();co=m.enum(["low","medium","high","critical"]),qt=m.enum(["feature","bug","improvement","chore"]),uo=m.enum(["active","backlog","previously_active"]),lo=m.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),Me=m.object({title:m.string(),description:m.string(),filesChanged:m.array(m.object({path:m.string(),action:m.enum(["created","modified","deleted"])})),whatWasDone:m.array(m.string()).min(1),outputForNextAgent:m.string().min(1),notes:m.string().optional()}),Nn=m.object({output:m.string().min(1,"Subtask output is required"),summary:Me}),In=m.object({id:m.string(),description:m.string(),domain:m.string(),agent:m.string(),status:lo,dependsOn:m.array(m.string()),startedAt:m.string().optional(),completedAt:m.string().optional(),output:m.string().optional(),summary:Me.optional(),skipReason:m.string().optional(),blockReason:m.string().optional(),estimatedPoints:m.number().optional(),estimatedMinutes:m.number().optional()}),Cn=m.object({completed:m.number(),total:m.number(),percentage:m.number()}),Ln=m.object({id:m.string(),description:m.string(),type:qt.optional(),startedAt:m.string(),sessionId:m.string(),featureId:m.string().optional(),subtasks:m.array(In).optional(),currentSubtaskIndex:m.number().optional(),subtaskProgress:Cn.optional(),linearId:m.string().optional(),linearUuid:m.string().optional(),linkedSpecId:m.string().optional(),estimatedPoints:m.number().optional(),estimatedMinutes:m.number().optional(),modelMetadata:he.optional(),tokensIn:m.number().optional(),tokensOut:m.number().optional(),parentDescription:m.string().optional(),branch:m.string().optional(),prUrl:m.string().optional()}),An=m.object({id:m.string(),description:m.string(),status:m.literal("paused"),startedAt:m.string(),pausedAt:m.string(),pauseReason:m.string().optional(),type:qt.optional(),sessionId:m.string().optional(),featureId:m.string().optional(),subtasks:m.array(In).optional(),currentSubtaskIndex:m.number().optional(),subtaskProgress:Cn.optional(),linearId:m.string().optional(),linearUuid:m.string().optional(),estimatedPoints:m.number().optional(),estimatedMinutes:m.number().optional(),modelMetadata:he.optional(),tokensIn:m.number().optional(),tokensOut:m.number().optional()}),po=m.object({stackConfirmed:m.array(m.string()).optional(),patternsDiscovered:m.array(m.string()).optional(),agentAccuracy:m.array(m.object({agent:m.string(),rating:m.enum(["helpful","neutral","inaccurate"]),note:m.string().optional()})).optional(),issuesEncountered:m.array(m.string()).optional()}),mo=m.object({taskId:m.string(),title:m.string(),classification:qt,startedAt:m.string(),completedAt:m.string(),subtaskCount:m.number(),subtaskSummaries:m.array(Me),outcome:m.string(),branchName:m.string(),linearId:m.string().optional(),linearUuid:m.string().optional(),prUrl:m.string().optional(),feedback:po.optional(),tokensIn:m.number().optional(),tokensOut:m.number().optional()}),go=Ln.extend({workspaceId:m.string(),worktreePath:m.string().optional(),agentSessionId:m.string().optional(),jiraId:m.string().optional(),jiraUuid:m.string().optional(),dispatchedFrom:m.string().optional()}),Dn=m.object({currentTask:Ln.nullable(),previousTask:An.nullable().optional(),pausedTasks:m.array(An).optional(),taskHistory:m.array(mo).optional(),activeTasks:m.array(go).optional(),lastUpdated:m.string()}),fo=m.object({id:m.string(),description:m.string(),body:m.string().optional(),priority:co,type:qt,featureId:m.string().optional(),originFeature:m.string().optional(),completed:m.boolean(),completedAt:m.string().optional(),createdAt:m.string(),section:uo,agent:m.string().optional(),groupName:m.string().optional(),groupId:m.string().optional()}),On=m.object({tasks:m.array(fo),lastUpdated:m.string()})});import ho from"node:crypto";function H(){return ho.randomUUID()}var Rt=E(()=>{"use strict";c(H,"generateUUID")});var Ue,nt,Mn=E(()=>{"use strict";N();j();Ue=class{static{c(this,"SyncPendingStorage")}append(t,e){let r=f(),s=JSON.stringify(e);return e.entityType&&e.entityId&&e.contentHash&&h.run(t,`DELETE FROM sync_pending
|
|
583
583
|
WHERE project_id = ?
|
|
584
584
|
AND entity_type = ?
|
|
585
585
|
AND entity_id = ?
|
|
586
586
|
AND content_hash = ?`,t,e.entityType,e.entityId,e.contentHash),h.run(t,`INSERT INTO sync_pending
|
|
587
587
|
(project_id, entity_type, entity_id, event_type, content_hash, payload, enqueued_at)
|
|
588
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`,t,e.entityType??null,e.entityId??null,e.eventType??null,e.contentHash??null,n,r),{id:h.get(t,"SELECT last_insert_rowid() AS id")?.id??0,event:e,enqueuedAt:r}}list(t,e){let r=e?"SELECT * FROM sync_pending WHERE project_id = ? ORDER BY id ASC LIMIT ?":"SELECT * FROM sync_pending WHERE project_id = ? ORDER BY id ASC";return(e?h.query(t,r,t,e):h.query(t,r,t)).map(i=>this.rowToEntry(i))}count(t){return h.get(t,"SELECT COUNT(*) AS n FROM sync_pending WHERE project_id = ?",t)?.n??0}clearUpTo(t,e){if(e<=0)return 0;let r=this.count(t);return h.run(t,"DELETE FROM sync_pending WHERE project_id = ? AND id <= ?",t,e),r-this.count(t)}clearAll(t){h.run(t,"DELETE FROM sync_pending WHERE project_id = ?",t)}clearByIds(t,e){if(e.length===0)return;let r=e.map(()=>"?").join(",");h.run(t,`DELETE FROM sync_pending WHERE project_id = ? AND id IN (${r})`,t,...e)}rowToEntry(t){let e;try{e=JSON.parse(t.payload)}catch{e={type:"unknown.corrupt",path:[],data:null,timestamp:t.enqueued_at,projectId:t.project_id}}return{id:t.id,event:e,enqueuedAt:t.enqueued_at}}},rt=new Me});var je,qt,Fe=E(()=>{"use strict";at();Cs();N();$();je=class{static{c(this,"SyncEventBus")}async publish(t){rt.append(t.projectId,t)}async getPending(t){return rt.list(t).map(e=>e.event)}async clearPending(t){rt.clearAll(t)}async getPendingEntries(t){return rt.list(t)}async clearPendingUpTo(t,e){return rt.clearUpTo(t,e)}async clearPendingByIds(t,e){rt.clearByIds(t,e)}async updateLastSync(t){let e=R.getLastSyncPath(t),r={timestamp:f(),success:!0};await F(e,r)}async getLastSync(t){let e=R.getLastSyncPath(t);return await It(e,null)}},qt=new je});var Ue={};K(Ue,{default:()=>go});import lo from"node:crypto";import Ds from"node:fs/promises";import Ls from"node:os";import po from"node:path";function Ms(){return lo.randomUUID()}var js,Os,$e,mo,go,Xe=E(()=>{"use strict";at();$();js="https://api.prjct.app",Os={apiKey:null,apiUrl:js,userId:null,email:null,lastAuth:null};c(Ms,"freshDeviceId");$e=class{static{c(this,"AuthConfigManager")}configPath;cachedConfig=null;constructor(){this.configPath=R.getAuthConfigPath()}getConfigPath(){return this.configPath}async read(){if(this.cachedConfig)return this.cachedConfig;let t=await It(this.configPath),e=t??{...Os},r=!1;if(e.deviceId||(e.deviceId=Ms(),r=!0),e.hostname||(e.hostname=Ls.hostname(),r=!0),this.cachedConfig=e,r&&t)try{await F(this.configPath,this.cachedConfig),await Ds.chmod(this.configPath,384)}catch{}return this.cachedConfig}async getDeviceId(){return(await this.read()).deviceId??Ms()}async getHostname(){return(await this.read()).hostname??Ls.hostname()}async write(t){let r={...await this.read(),...t,lastAuth:new Date().toISOString()};await G(po.dirname(this.configPath)),await F(this.configPath,r),await Ds.chmod(this.configPath,384),this.cachedConfig=r}async hasAuth(){let t=await this.read();return t.apiKey!==null&&t.apiKey.length>0}async getApiKey(){return(await this.read()).apiKey}async getApiUrl(){return(await this.read()).apiUrl||js}async saveAuth(t,e,r){await this.write({apiKey:t,userId:e,email:r})}async clearAuth(){this.cachedConfig={...Os},await F(this.configPath,this.cachedConfig)}async getStatus(){let t=await this.read();return{authenticated:t.apiKey!==null,email:t.email,apiKeyPrefix:t.apiKey?`${t.apiKey.substring(0,12)}...`:null,lastAuth:t.lastAuth}}clearCache(){this.cachedConfig=null}},mo=new $e,go=mo});var $s={};K($s,{publishCRUD:()=>Fs,publishCRUDSync:()=>q});import fo from"node:crypto";function yo(s){let t=s&&typeof s=="object"&&!Array.isArray(s)?JSON.stringify(To(s)):JSON.stringify(s);return fo.createHash("sha256").update(t).digest("hex")}function To(s){let t={};for(let e of Object.keys(s).sort())t[e]=s[e];return t}async function Eo(){if(We)return We;try{let{default:s}=await Promise.resolve().then(()=>(Xe(),Ue)),t=s;if(typeof t.getDeviceId=="function"){let e=await t.getDeviceId();return We=e,e}return"unknown-device"}catch{return"unknown-device"}}async function Fs(s){try{let t=await Eo(),e=yo(s.data),r={type:`${s.entityType}.${ho[s.eventType]}`,path:[s.entityType,s.entityId],data:s.data,timestamp:new Date().toISOString(),projectId:s.projectId,entityType:s.entityType,entityId:s.entityId,eventType:s.eventType,contentHash:e,deviceId:t,originDeviceId:s.originDeviceId??t,revisionCount:s.revisionCount??1};await qt.publish(r)}catch{}}function q(s){Fs(s)}var ho,We,Rt=E(()=>{"use strict";Fe();ho={upsert:"updated",delete:"deleted"};c(yo,"hashPayload");c(To,"sortKeys");We=null;c(Eo,"resolveDeviceId");c(Fs,"publishCRUD");c(q,"publishCRUDSync")});var xt,Be,lt,Gt=E(()=>{"use strict";vt();Rt();N();j();xt={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Be=class{static{c(this,"ArchiveStorage")}archive(t,e){let r=H(),n=f();return k.run(t,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",r,e.entityType,e.entityId,JSON.stringify(e.entityData),e.summary??null,n,e.reason),q({projectId:t,entityType:"archives",entityId:r,eventType:"upsert",data:{id:r,entity_type:e.entityType,entity_id:e.entityId,summary:e.summary??null,reason:e.reason,archived_at:n}}),r}archiveMany(t,e){if(e.length===0)return 0;let r=f();return k.transaction(t,n=>{let i=n.prepare("INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let o of e)i.run(H(),o.entityType,o.entityId,JSON.stringify(o.entityData),o.summary??null,r,o.reason)}),e.length}getArchived(t,e,r=50){return e?k.query(t,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",e,r):k.query(t,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",r)}getStats(t){let e=k.query(t,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),r={shipped:0,idea:0,queue_task:0,paused_task:0,memory_entry:0,total:0};for(let n of e){let i=n.entity_type;i in r&&(r[i]=n.count),r.total+=n.count}return r}restore(t,e){let r=k.get(t,"SELECT * FROM archives WHERE id = ?",e);return r?(k.run(t,"DELETE FROM archives WHERE id = ?",e),JSON.parse(r.entity_data)):null}pruneOldArchives(t,e){let r=new Date(Date.now()-e*24*60*60*1e3).toISOString(),n=this.getTotalCount(t);k.run(t,"DELETE FROM archives WHERE archived_at < ?",r);let i=this.getTotalCount(t);return n-i}getTotalCount(t){return k.get(t,"SELECT COUNT(*) as count FROM archives")?.count??0}},lt=new Be});import bo from"node:crypto";function vo(s){let[t,e]=s.split(".");return t?{entityType:t.endsWith("s")?t:`${t}s`,eventType:e==="deleted"||e==="archived"||e==="removed"?"delete":"upsert"}:{}}function Ro(s){if(!s||typeof s!="object")return;let t=s;for(let e of["taskId","task_id","id","feature_id","featureId","specId","spec_id"]){let r=t[e];if(typeof r=="string"&&r.length>0)return r}}function xo(s){let t=s&&typeof s=="object"&&!Array.isArray(s)?JSON.stringify(Po(s)):JSON.stringify(s);return bo.createHash("sha256").update(t).digest("hex")}function Po(s){let t={};for(let e of Object.keys(s).sort())t[e]=s[e];return t}async function Ao(){if(Yt)return Yt;try{let{default:s}=await Promise.resolve().then(()=>(Xe(),Ue)),t=s;return typeof t.getDeviceId=="function"?(Yt=await t.getDeviceId(),Yt):"unknown-device"}catch{return"unknown-device"}}var Yt,pt,Ge=E(()=>{"use strict";Fe();fe();N();j();c(vo,"deriveEntityShape");c(Ro,"entityIdOf");c(xo,"hashPayload");c(Po,"sortKeys");Yt=null;c(Ao,"_resolveDeviceId");pt=class{static{c(this,"StorageManager")}filename;cache;constructor(t,e){this.filename=t,this.cache=new Dt({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(t){if(!(process.env.PRJCT_IN_DAEMON==="1")){let r=this.cache.get(t);if(r!==null)return r}try{let r=k.getDoc(t,this.getStoreKey());if(r!==null)return this.cache.set(t,r),r}catch{}return this.getDefault()}async write(t,e){k.setDoc(t,this.getStoreKey(),e),this.cache.set(t,e)}async update(t,e){let r=this.getStoreKey(),n=8;for(let i=1;i<=n;i++){let o=k.getDocWithStamp(t,r),a=o?o.data:this.getDefault(),u=e(a);if(k.casSetDoc(t,r,u,o?.updatedAt??null))return this.cache.set(t,u),u}throw new Error(`StorageManager.update: unresolved write contention after ${n} attempts (key=${r})`)}async publishEvent(t,e,r){let n=vo(e),i={type:e,path:[this.filename.replace(".json","")],data:r,timestamp:f(),projectId:t,entityType:n.entityType,entityId:Ro(r),eventType:n.eventType,contentHash:xo(r),deviceId:await Ao(),revisionCount:1};await qt.publish(i)}async publishEntityEvent(t,e,r,n){let i=`${e}.${r}`,o={...n,timestamp:f()};await this.publishEvent(t,i,o)}async exists(t){try{return k.hasDoc(t,this.getStoreKey())}catch{return!1}}clearCache(t){t?this.cache.delete(t):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});var yn,Tn,En,kn,Sn=E(()=>{"use strict";yn={frontend:["component","page","view","ui","layout","style","css","scss","sass","hook","context","store","redux","zustand","react","vue","svelte","angular","next","nuxt","app","client"],backend:["api","route","controller","service","middleware","handler","resolver","schema","model","entity","repository","server","socket","graphql","rest","trpc"],database:["migration","seed","schema","model","entity","repository","prisma","drizzle","sequelize","typeorm","mongoose","knex","sql","db"],auth:["auth","login","logout","session","token","jwt","oauth","passport","credential","permission","role","user","account"],testing:["test","spec","e2e","integration","unit","mock","fixture","stub","jest","vitest","cypress","playwright"],config:["config","env","setting","constant","option","tsconfig","eslint","prettier","vite","webpack","rollup"],infra:["docker","compose","kubernetes","k8s","ci","cd","github","gitlab","jenkins","terraform","ansible","deploy"],util:["util","helper","lib","common","shared","core","base","abstract"]},Tn=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".swift",".rb",".php",".c",".cpp",".h",".hpp",".cs",".vue",".svelte"]),En=new Set(["node_modules",".git","dist","build",".next",".nuxt",".output","coverage",".cache","__pycache__",".pytest_cache","vendor","target",".turbo",".vercel"]),kn=new Set(["a","an","the","and","or","but","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","to","of","in","for","on","with","at","by","from","as","into","through","during","before","after","above","below","between","under","again","further","then","once","here","there","when","where","why","how","all","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","add","create","make","implement","fix","update","change","modify","remove","delete","new"])});import No from"node:fs/promises";import Jt from"node:path";async function zt(s,t,e={}){let r=Date.now(),n=e.maxFiles??30,i=e.minScore??.1,o=e.includeTests??!1,a=Io(s),u=await Co(t),l=await Do(t),d=[];for(let g of u){if(!o&&Oo(g))continue;let T=Lo(g,a,l,e.historicalBoosts);T.score>=i&&d.push(T)}d.sort((g,T)=>T.score-g.score);let p=d.slice(0,n);return{files:p,metrics:{filesScanned:u.length,filesReturned:p.length,scanDuration:Date.now()-r}}}function Io(s){return s.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).filter(e=>!kn.has(e)&&e.length>2)}async function Co(s){let t=[];async function e(r,n=""){try{let i=await No.readdir(r,{withFileTypes:!0});for(let o of i){let a=Jt.join(r,o.name),u=Jt.join(n,o.name);if(o.isDirectory()){if(En.has(o.name)||o.name.startsWith("."))continue;await e(a,u)}else if(o.isFile()){let l=Jt.extname(o.name).toLowerCase();Tn.has(l)&&t.push(u)}}}catch(i){M(i)}}return c(e,"walk"),await e(s),t}async function Do(s){let t=new Map;try{let{stdout:e}=await b(`git log -30 --pretty=format:"%H %ct" --name-only | awk '
|
|
588
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,t,e.entityType??null,e.entityId??null,e.eventType??null,e.contentHash??null,s,r),{id:h.get(t,"SELECT last_insert_rowid() AS id")?.id??0,event:e,enqueuedAt:r}}list(t,e){let r=e?"SELECT * FROM sync_pending WHERE project_id = ? ORDER BY id ASC LIMIT ?":"SELECT * FROM sync_pending WHERE project_id = ? ORDER BY id ASC";return(e?h.query(t,r,t,e):h.query(t,r,t)).map(i=>this.rowToEntry(i))}count(t){return h.get(t,"SELECT COUNT(*) AS n FROM sync_pending WHERE project_id = ?",t)?.n??0}clearUpTo(t,e){if(e<=0)return 0;let r=this.count(t);return h.run(t,"DELETE FROM sync_pending WHERE project_id = ? AND id <= ?",t,e),r-this.count(t)}clearAll(t){h.run(t,"DELETE FROM sync_pending WHERE project_id = ?",t)}clearByIds(t,e){if(e.length===0)return;let r=e.map(()=>"?").join(",");h.run(t,`DELETE FROM sync_pending WHERE project_id = ? AND id IN (${r})`,t,...e)}rowToEntry(t){let e;try{e=JSON.parse(t.payload)}catch{e={type:"unknown.corrupt",path:[],data:null,timestamp:t.enqueued_at,projectId:t.project_id}}return{id:t.id,event:e,enqueuedAt:t.enqueued_at}}},nt=new Ue});var $e,Yt,Xe=E(()=>{"use strict";at();Mn();N();U();$e=class{static{c(this,"SyncEventBus")}async publish(t){nt.append(t.projectId,t)}async getPending(t){return nt.list(t).map(e=>e.event)}async clearPending(t){nt.clearAll(t)}async getPendingEntries(t){return nt.list(t)}async clearPendingUpTo(t,e){return nt.clearUpTo(t,e)}async clearPendingByIds(t,e){nt.clearByIds(t,e)}async updateLastSync(t){let e=R.getLastSyncPath(t),r={timestamp:f(),success:!0};await F(e,r)}async getLastSync(t){let e=R.getLastSyncPath(t);return await Lt(e,null)}},Yt=new $e});var Be={};K(Be,{default:()=>ko});import yo from"node:crypto";import jn from"node:fs/promises";import Fn from"node:os";import To from"node:path";function $n(){return yo.randomUUID()}var Xn,Un,We,Eo,ko,He=E(()=>{"use strict";at();U();Xn="https://api.prjct.app",Un={apiKey:null,apiUrl:Xn,userId:null,email:null,lastAuth:null};c($n,"freshDeviceId");We=class{static{c(this,"AuthConfigManager")}configPath;cachedConfig=null;constructor(){this.configPath=R.getAuthConfigPath()}getConfigPath(){return this.configPath}async read(){if(this.cachedConfig)return this.cachedConfig;let t=await Lt(this.configPath),e=t??{...Un},r=!1;if(e.deviceId||(e.deviceId=$n(),r=!0),e.hostname||(e.hostname=Fn.hostname(),r=!0),this.cachedConfig=e,r&&t)try{await F(this.configPath,this.cachedConfig),await jn.chmod(this.configPath,384)}catch{}return this.cachedConfig}async getDeviceId(){return(await this.read()).deviceId??$n()}async getHostname(){return(await this.read()).hostname??Fn.hostname()}async write(t){let r={...await this.read(),...t,lastAuth:new Date().toISOString()};await G(To.dirname(this.configPath)),await F(this.configPath,r),await jn.chmod(this.configPath,384),this.cachedConfig=r}async hasAuth(){let t=await this.read();return t.apiKey!==null&&t.apiKey.length>0}async getApiKey(){return(await this.read()).apiKey}async getApiUrl(){return(await this.read()).apiUrl||Xn}async saveAuth(t,e,r){await this.write({apiKey:t,userId:e,email:r})}async clearAuth(){this.cachedConfig={...Un},await F(this.configPath,this.cachedConfig)}async getStatus(){let t=await this.read();return{authenticated:t.apiKey!==null,email:t.email,apiKeyPrefix:t.apiKey?`${t.apiKey.substring(0,12)}...`:null,lastAuth:t.lastAuth}}clearCache(){this.cachedConfig=null}},Eo=new We,ko=Eo});var Bn={};K(Bn,{publishCRUD:()=>Wn,publishCRUDSync:()=>q});import So from"node:crypto";function _o(n){let t=n&&typeof n=="object"&&!Array.isArray(n)?JSON.stringify(bo(n)):JSON.stringify(n);return So.createHash("sha256").update(t).digest("hex")}function bo(n){let t={};for(let e of Object.keys(n).sort())t[e]=n[e];return t}async function vo(){if(qe)return qe;try{let{default:n}=await Promise.resolve().then(()=>(He(),Be)),t=n;if(typeof t.getDeviceId=="function"){let e=await t.getDeviceId();return qe=e,e}return"unknown-device"}catch{return"unknown-device"}}async function Wn(n){try{let t=await vo(),e=_o(n.data),r={type:`${n.entityType}.${wo[n.eventType]}`,path:[n.entityType,n.entityId],data:n.data,timestamp:new Date().toISOString(),projectId:n.projectId,entityType:n.entityType,entityId:n.entityId,eventType:n.eventType,contentHash:e,deviceId:t,originDeviceId:n.originDeviceId??t,revisionCount:n.revisionCount??1};await Yt.publish(r)}catch{}}function q(n){Wn(n)}var wo,qe,xt=E(()=>{"use strict";Xe();wo={upsert:"updated",delete:"deleted"};c(_o,"hashPayload");c(bo,"sortKeys");qe=null;c(vo,"resolveDeviceId");c(Wn,"publishCRUD");c(q,"publishCRUDSync")});var Pt,Ge,lt,Jt=E(()=>{"use strict";Rt();xt();N();j();Pt={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Ge=class{static{c(this,"ArchiveStorage")}archive(t,e){let r=H(),s=f();return k.run(t,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",r,e.entityType,e.entityId,JSON.stringify(e.entityData),e.summary??null,s,e.reason),q({projectId:t,entityType:"archives",entityId:r,eventType:"upsert",data:{id:r,entity_type:e.entityType,entity_id:e.entityId,summary:e.summary??null,reason:e.reason,archived_at:s}}),r}archiveMany(t,e){if(e.length===0)return 0;let r=f();return k.transaction(t,s=>{let i=s.prepare("INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let o of e)i.run(H(),o.entityType,o.entityId,JSON.stringify(o.entityData),o.summary??null,r,o.reason)}),e.length}getArchived(t,e,r=50){return e?k.query(t,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",e,r):k.query(t,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",r)}getStats(t){let e=k.query(t,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),r={shipped:0,idea:0,queue_task:0,paused_task:0,memory_entry:0,total:0};for(let s of e){let i=s.entity_type;i in r&&(r[i]=s.count),r.total+=s.count}return r}restore(t,e){let r=k.get(t,"SELECT * FROM archives WHERE id = ?",e);return r?(k.run(t,"DELETE FROM archives WHERE id = ?",e),JSON.parse(r.entity_data)):null}pruneOldArchives(t,e){let r=new Date(Date.now()-e*24*60*60*1e3).toISOString(),s=this.getTotalCount(t);k.run(t,"DELETE FROM archives WHERE archived_at < ?",r);let i=this.getTotalCount(t);return s-i}getTotalCount(t){return k.get(t,"SELECT COUNT(*) as count FROM archives")?.count??0}},lt=new Ge});import No from"node:crypto";function Io(n){let[t,e]=n.split(".");return t?{entityType:t.endsWith("s")?t:`${t}s`,eventType:e==="deleted"||e==="archived"||e==="removed"?"delete":"upsert"}:{}}function Co(n){if(!n||typeof n!="object")return;let t=n;for(let e of["taskId","task_id","id","feature_id","featureId","specId","spec_id"]){let r=t[e];if(typeof r=="string"&&r.length>0)return r}}function Lo(n){let t=n&&typeof n=="object"&&!Array.isArray(n)?JSON.stringify(Do(n)):JSON.stringify(n);return No.createHash("sha256").update(t).digest("hex")}function Do(n){let t={};for(let e of Object.keys(n).sort())t[e]=n[e];return t}async function Oo(){if(zt)return zt;try{let{default:n}=await Promise.resolve().then(()=>(He(),Be)),t=n;return typeof t.getDeviceId=="function"?(zt=await t.getDeviceId(),zt):"unknown-device"}catch{return"unknown-device"}}var zt,pt,ze=E(()=>{"use strict";Xe();Te();N();j();c(Io,"deriveEntityShape");c(Co,"entityIdOf");c(Lo,"hashPayload");c(Do,"sortKeys");zt=null;c(Oo,"_resolveDeviceId");pt=class{static{c(this,"StorageManager")}filename;cache;constructor(t,e){this.filename=t,this.cache=new Ot({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(t){if(!(process.env.PRJCT_IN_DAEMON==="1")){let r=this.cache.get(t);if(r!==null)return r}try{let r=k.getDoc(t,this.getStoreKey());if(r!==null)return this.cache.set(t,r),r}catch{}return this.getDefault()}async write(t,e){k.setDoc(t,this.getStoreKey(),e),this.cache.set(t,e)}async update(t,e){let r=this.getStoreKey(),s=8;for(let i=1;i<=s;i++){let o=k.getDocWithStamp(t,r),a=o?o.data:this.getDefault(),u=e(a);if(k.casSetDoc(t,r,u,o?.updatedAt??null))return this.cache.set(t,u),u}throw new Error(`StorageManager.update: unresolved write contention after ${s} attempts (key=${r})`)}async publishEvent(t,e,r){let s=Io(e),i={type:e,path:[this.filename.replace(".json","")],data:r,timestamp:f(),projectId:t,entityType:s.entityType,entityId:Co(r),eventType:s.eventType,contentHash:Lo(r),deviceId:await Oo(),revisionCount:1};await Yt.publish(i)}async publishEntityEvent(t,e,r,s){let i=`${e}.${r}`,o={...s,timestamp:f()};await this.publishEvent(t,i,o)}async exists(t){try{return k.hasDoc(t,this.getStoreKey())}catch{return!1}}clearCache(t){t?this.cache.delete(t):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});function jo(){let n=process.env.PRJCT_DEBUG||process.env.DEBUG||"";if(!n)return{level:-1,name:"disabled"};if(Mo.has(n)||n.includes("prjct"))return{level:mt.debug,name:"debug"};let t=mt[n]??-1,e=t>=0?n:"disabled";return{level:t,name:e}}function Kt(n,t,e){return ks>=n?(...r)=>console[e](t,...r):Uo}var mt,Mo,ks,Fo,Uo,$o,Ss,ws=E(()=>{"use strict";mt={error:0,warn:1,info:2,debug:3},Mo=new Set(["1","true","*"]);c(jo,"getLogLevel");({level:ks,name:Fo}=jo()),Uo=c(()=>{},"noop");c(Kt,"createLogMethod");$o={error:Kt(mt.error,"[prjct:error]","error"),warn:Kt(mt.warn,"[prjct:warn]","warn"),info:Kt(mt.info,"[prjct:info]","log"),debug:Kt(mt.debug,"[prjct:debug]","log"),isEnabled:c(()=>ks>=0,"isEnabled"),level:c(()=>Fo,"level")},Ss=$o});var _s,bs,vs,Rs,xs=E(()=>{"use strict";_s={frontend:["component","page","view","ui","layout","style","css","scss","sass","hook","context","store","redux","zustand","react","vue","svelte","angular","next","nuxt","app","client"],backend:["api","route","controller","service","middleware","handler","resolver","schema","model","entity","repository","server","socket","graphql","rest","trpc"],database:["migration","seed","schema","model","entity","repository","prisma","drizzle","sequelize","typeorm","mongoose","knex","sql","db"],auth:["auth","login","logout","session","token","jwt","oauth","passport","credential","permission","role","user","account"],testing:["test","spec","e2e","integration","unit","mock","fixture","stub","jest","vitest","cypress","playwright"],config:["config","env","setting","constant","option","tsconfig","eslint","prettier","vite","webpack","rollup"],infra:["docker","compose","kubernetes","k8s","ci","cd","github","gitlab","jenkins","terraform","ansible","deploy"],util:["util","helper","lib","common","shared","core","base","abstract"]},bs=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".swift",".rb",".php",".c",".cpp",".h",".hpp",".cs",".vue",".svelte"]),vs=new Set(["node_modules",".git","dist","build",".next",".nuxt",".output","coverage",".cache","__pycache__",".pytest_cache","vendor","target",".turbo",".vercel"]),Rs=new Set(["a","an","the","and","or","but","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","to","of","in","for","on","with","at","by","from","as","into","through","during","before","after","above","below","between","under","again","further","then","once","here","there","when","where","why","how","all","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","add","create","make","implement","fix","update","change","modify","remove","delete","new"])});import Xo from"node:fs/promises";import Vt from"node:path";async function Qt(n,t,e={}){let r=Date.now(),s=e.maxFiles??30,i=e.minScore??.1,o=e.includeTests??!1,a=Wo(n),u=await Bo(t),l=await Ho(t),d=[];for(let g of u){if(!o&&Go(g))continue;let T=qo(g,a,l,e.historicalBoosts);T.score>=i&&d.push(T)}d.sort((g,T)=>T.score-g.score);let p=d.slice(0,s);return{files:p,metrics:{filesScanned:u.length,filesReturned:p.length,scanDuration:Date.now()-r}}}function Wo(n){return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).filter(e=>!Rs.has(e)&&e.length>2)}async function Bo(n){let t=[];async function e(r,s=""){try{let i=await Xo.readdir(r,{withFileTypes:!0});for(let o of i){let a=Vt.join(r,o.name),u=Vt.join(s,o.name);if(o.isDirectory()){if(vs.has(o.name)||o.name.startsWith("."))continue;await e(a,u)}else if(o.isFile()){let l=Vt.extname(o.name).toLowerCase();bs.has(l)&&t.push(u)}}}catch(i){M(i)||Ss.debug(`files-tool: skipped unreadable path during walk: ${Ct(i)}`)}}return c(e,"walk"),await e(n),t}async function Ho(n){let t=new Map;try{let{stdout:e}=await b(`git log -30 --pretty=format:"%H %ct" --name-only | awk '
|
|
589
589
|
/^[a-f0-9]{40}/ { commit=$1; timestamp=$2; next }
|
|
590
590
|
NF { files[$0]++; if (!lastmod[$0]) lastmod[$0]=timestamp }
|
|
591
591
|
END { for (f in files) print files[f], lastmod[f], f }
|
|
592
|
-
'`,{cwd:
|
|
593
|
-
`).filter(Boolean);for(let i of
|
|
592
|
+
'`,{cwd:n,maxBuffer:10485760}),r=Math.floor(Date.now()/1e3),s=e.trim().split(`
|
|
593
|
+
`).filter(Boolean);for(let i of s){let o=i.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(o){let a=parseInt(o[1],10),u=parseInt(o[2],10),l=o[3],d=Math.floor((r-u)/86400);t.set(l,{commits:a,daysAgo:d})}}}catch{}return t}function qo(n,t,e,r){let s=[],i=0,o=0,a=0,u=0,l=0,d=n.toLowerCase(),p=d.split("/").join(" ").split(/[^a-z0-9]+/);for(let A of t){d.includes(A)&&(i+=.3,s.push(`keyword:${A}`));for(let Z of p)if(Z.includes(A)||A.includes(Z)){i+=.15;break}}i=Math.min(1,i);for(let[A,Z]of Object.entries(_s))for(let Nt of Z)if(d.includes(Nt)&&t.some(it=>Z.includes(it)||it.includes(A)||A.includes(it))){o+=.4,s.push(`domain:${A}`);break}o=Math.min(1,o);let g=e.get(n);g&&(g.daysAgo<=1?(a=1,s.push("recent:1d")):g.daysAgo<=3?(a=.8,s.push("recent:3d")):g.daysAgo<=7?(a=.6,s.push("recent:1w")):g.daysAgo<=30&&(a=.3,s.push("recent:1m")),g.commits>=5&&(a=Math.min(1,a+.2)));let T=Vt.basename(n).toLowerCase();if((T.includes("index")||T.includes("main")||T.includes("app")||T.includes("entry"))&&(u=.5,s.push("import:0")),(d.includes("/core/")||d.includes("/shared/")||d.includes("/lib/"))&&(u=Math.max(u,.3),s.some(A=>A.startsWith("import:"))||s.push("import:1")),r){let A=r.get(n);A!==void 0&&(l=(A+1)/2,A>0?s.push("history:boosted"):A<0&&s.push("history:penalized"))}let z=r&&r.size>0?i*.54+o*.18+a*.13+u*.05+l*.1:i*.6+o*.2+a*.15+u*.05;return{path:n,score:Math.min(1,z),reasons:[...new Set(s)]}}function Go(n){let t=n.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||t.includes("__tests__")||t.includes("__mocks__")||t.includes("/tests/")||t.includes("/test/")||t.endsWith("_test.go")||t.endsWith("_test.py")}var Ve=E(()=>{"use strict";tt();rt();ws();xs();c(Qt,"findRelevantFiles");c(Wo,"extractKeywords");c(Bo,"getAllCodeFiles");c(Ho,"getGitRecency");c(qo,"scoreFile");c(Go,"isTestFile")});var Ze,Os,Ms=E(()=>{"use strict";bt();Jt();j();Ze=class{static{c(this,"MemoryService")}async log(t,e,r,s){try{let i=await B.getProjectId(t);return i?{eventId:h.appendEvent(i,`memory.${e}`,{...r,author:s}),projectId:i}:null}catch(i){return console.error(`Memory log error: ${i instanceof Error?i.message:String(i)}`),null}}async getRecent(t,e=100){try{let r=await B.getProjectId(t);return r?h.query(r,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",e).reverse().map(i=>{let o=JSON.parse(i.data),{author:a,...u}=o;return{timestamp:i.timestamp,action:i.type.replace("memory.",""),data:u,author:a}}):[]}catch(r){return console.error(`Memory read error: ${r instanceof Error?r.message:String(r)}`),[]}}async search(t,e,r=50){let s=await this.getRecent(t,1e3),i=e.toLowerCase();return s.filter(o=>{let a=o.action.toLowerCase().includes(i),u=JSON.stringify(o.data).toLowerCase().includes(i);return a||u}).slice(-r)}async getByAction(t,e,r=50){try{let s=await B.getProjectId(t);return s?h.query(s,"SELECT type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`memory.${e}`,r).reverse().map(o=>{let a=JSON.parse(o.data),{author:u,...l}=a;return{timestamp:o.timestamp,action:o.type.replace("memory.",""),data:l,author:u}}):[]}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async clear(t){try{let e=await B.getProjectId(t);if(!e)return;h.run(e,"DELETE FROM events WHERE type LIKE 'memory.%'")}catch(e){console.error(`Memory clear error: ${e instanceof Error?e.message:String(e)}`)}}async getRecentEvents(t,e=100){try{return h.query(t,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",e).reverse().map(s=>{let i=JSON.parse(s.data);return{timestamp:s.timestamp,action:s.type.replace("memory.",""),...i}})}catch(r){return console.error(`Memory read error: ${r instanceof Error?r.message:String(r)}`),[]}}async capEntries(t){try{let r=h.get(t,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(r<=Pt.MEMORY_MAX_ENTRIES)return 0;let s=r-Pt.MEMORY_MAX_ENTRIES,i=h.query(t,"SELECT id, type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?",s);lt.archiveMany(t,i.map((a,u)=>({entityType:"memory_entry",entityId:`memory-${a.timestamp||u}`,entityData:{type:a.type,data:JSON.parse(a.data),timestamp:a.timestamp},summary:a.type.replace("memory.",""),reason:"overflow"})));let o=i[i.length-1]?.id;return o!==void 0&&h.run(t,"DELETE FROM events WHERE type LIKE 'memory.%' AND id <= ?",o),s}catch(e){return console.error(`Memory cap error: ${e instanceof Error?e.message:String(e)}`),0}}},Os=new Ze});function Fs(n){let t=[];for(let{name:e,re:r}of js)r.test(n)&&t.push(e);return t}function Us(n){return n.replace(/[`*_[\](){}<>\\]/g,t=>`\\${t}`)}var js,Yp,tr=E(()=>{"use strict";js=[{name:"instruction-override",re:/\b(ignore|disregard|override|forget)\b[^.]{0,40}\b(previous|prior|above|system|prompt|instructions?|rules?|constraints?)\b/i},{name:"role-play-injection",re:/\b(you\s+are\s+now|act\s+as|pretend\s+to\s+be|roleplay\s+as|assume\s+the\s+role)\b[^.]{0,40}\b(system|admin|root|developer|operator|jailbreak)\b/i},{name:"jailbreak-phrase",re:/\b(DAN\s+mode|do\s+anything\s+now|without\s+restrictions?|bypass\s+(?:safety|filters?|guidelines?)|jailbreak\s+mode)\b/i},{name:"fake-system-tag",re:/<\s*(?:system|assistant|tool[_-]?call|function[_-]?call)\s*>/i}],Yp=js.map(n=>n.name);c(Fs,"scanForPromptInjection");c(Us,"escapeMarkdownInline")});var $s,er,Q,Kp,Xs=E(()=>{"use strict";$s="memory.",er="remember.",Q=`${$s}${er}`,Kp=`${$s}task.tagged`});var Hs={};K(Hs,{extractCorrectionIds:()=>sr,extractRefIds:()=>Bs,usefulnessService:()=>ga});function Bs(n,t){let e=new Set;for(let r of da){let s=t[r];if(s)for(let i of String(s).matchAll(nr))e.add(`mem_${i[1]}`)}for(let r of n.matchAll(nr))e.add(`mem_${r[1]}`);for(let r of sr(t))e.delete(r);return[...e]}function sr(n){let t=new Set;for(let e of ma){let r=n[e];if(r)for(let s of String(r).matchAll(nr))t.add(`mem_${s[1]}`)}return[...t]}function Ws(n,t,e,r,s){h.run(n,`INSERT INTO memory_usefulness (memory_id, score, ${r}, last_used_at)
|
|
594
594
|
VALUES (?, ?, 1, ?)
|
|
595
595
|
ON CONFLICT(memory_id) DO UPDATE SET
|
|
596
|
-
score = score + ?, ${r} = ${r} + 1, last_used_at = excluded.last_used_at`,t,e,
|
|
596
|
+
score = score + ?, ${r} = ${r} + 1, last_used_at = excluded.last_used_at`,t,e,s,e)}function rr(n,t,e,r){h.run(n,`INSERT INTO memory_usefulness (memory_id, score, last_used_at)
|
|
597
597
|
VALUES (?, ?, ?)
|
|
598
598
|
ON CONFLICT(memory_id) DO UPDATE SET
|
|
599
|
-
score = score + ?, last_used_at = excluded.last_used_at`,t,e,r,e)}var
|
|
600
|
-
VALUES (?, ?, ?)`,
|
|
601
|
-
`).trim()}var
|
|
599
|
+
score = score + ?, last_used_at = excluded.last_used_at`,t,e,r,e)}var ia,oa,aa,ca,ua,la,pa,da,ma,nr,ga,qs=E(()=>{"use strict";j();ia=45,oa=1,aa=.4,ca=2.5,ua=-2.5,la=-.5,pa=864e5,da=["resolves","relates","supersedes","superseded-by","duplicates","spec"],ma=["corrects","contradicts"],nr=/\bmem[_-](\d+)\b/g;c(Bs,"extractRefIds");c(sr,"extractCorrectionIds");c(Ws,"bump");c(rr,"addScore");ga={recordReferences(n,t,e,r=new Date().toISOString()){try{for(let s of Bs(t,e))Ws(n,s,oa,"ref_count",r)}catch{}},recordCorrection(n,t,e=new Date().toISOString()){try{for(let r of sr(t))rr(n,r,ua,e)}catch{}},recordFetch(n,t,e=new Date().toISOString()){try{Ws(n,t,aa,"fetch_count",e)}catch{}},recordSurfaced(n,t,e,r=new Date().toISOString()){if(!(!e||t.length===0))try{for(let s of t)h.run(n,`INSERT OR IGNORE INTO memory_surface_log (memory_id, task_id, created_at)
|
|
600
|
+
VALUES (?, ?, ?)`,s,e,r)}catch{}},penalizeSurfaced(n,t,e=new Date().toISOString()){if(!t)return 0;try{let r=h.query(n,"SELECT memory_id FROM memory_surface_log WHERE task_id = ?",t);for(let s of r)rr(n,s.memory_id,la,e);return r.length}catch{return 0}},creditShippedTask(n,t,e=new Date().toISOString()){if(!t)return 0;try{let r=h.query(n,"SELECT memory_id FROM memory_surface_log WHERE task_id = ?",t);for(let s of r)rr(n,s.memory_id,ca,e);return h.run(n,"DELETE FROM memory_surface_log WHERE task_id = ?",t),r.length}catch{return 0}},decayedScores(n,t=Date.now()){let e=new Map,r;try{r=h.query(n,"SELECT memory_id, score, last_used_at FROM memory_usefulness")}catch{return e}for(let s of r){let i=Date.parse(s.last_used_at),o=Number.isNaN(i)?1:.5**(Math.max(0,t-i)/pa/ia);e.set(s.memory_id,s.score*o)}return e},rerank(n,t,e=Date.now()){if(t.length<2)return t;let r;try{r=this.decayedScores(n,e)}catch{return t}if(r.size===0)return t;let s=Math.max(1,...r.values()),i=4,o=t.length,a=t.map((u,l)=>{let d=(r.get(u.id)??0)/s;return{entry:u,i:l,rankScore:o-l+i*d}});return a.sort((u,l)=>l.rankScore-u.rankScore||u.i-l.i),a.map(u=>u.entry)}}});function zs(n,t){try{return JSON.parse(n)}catch{return t}}function te(n){let t=n.type.slice(Q.length),e=zs(n.data,{});return{id:`mem_${n.id}`,type:t,content:e.content??"",tags:e.tags??{},rememberedAt:n.timestamp,source:e.source,provenance:e.provenance??"declared"}}function Gs(n){let t=n.data?zs(n.data,{}):{},e=t.tags??{};return n.type&&(e.type=n.type),{id:`ship_${n.id}`,type:"shipped",content:n.name,tags:e,rememberedAt:n.shipped_at,source:t.taskId,provenance:"extracted"}}function Ta(n,t){let e=t.toLowerCase();if(n.content.toLowerCase().includes(e))return!0;for(let r of Object.values(n.tags))if(r.toLowerCase().includes(e))return!0;return!1}function Ea(n,t){for(let[e,r]of Object.entries(t))if(n.tags[e]!==r)return!1;return!0}function ka(n){let t=new Set,e=[];for(let r of n){let s=r.tags.key;if(!s){e.push(r);continue}let i=`${r.type}::${s}`;t.has(i)||(t.add(i),e.push(r))}return e}function wa(n){let t=new Set;for(let e of n){e.tags["superseded-by"]&&t.add(e.id);for(let r of["supersedes","duplicates"]){let s=e.tags[r];if(s)for(let i of String(s).matchAll(Sa))t.add(`mem_${i[1]}`)}}return t}function _a(n){return n.replace(/[[\]|]/g,"").replace(/\s+/g," ").trim()}function Ys(n,t){return n.replace(/\[\[(mem[_-]\d+)\]\]/gi,"$1").replace(/\bmem[_-](\d+)\b/g,(e,r)=>{let s=`mem_${r}`,i=t?.idTypeIndex?.get(s),o=t?.idTitleIndex?.get(s),a=t?.idSlugIndex?.get(s),u=o?_a(o):s;return a&&i&&t?.perEntryTypes?.has(i)?`[[${a}|${u}]]`:i?`[[${i}#^mem-${r}|${u}]]`:o?`[[${s}|${u}]]`:`\`${s}\``})}function ft(n,t){if(n.length===0)return"> No matching memory entries.";let e=new Map;for(let l of n){let d=e.get(l.type)??[];d.push(l),e.set(l.type,d)}let r=["decision","learning","anti-pattern","gotcha","pattern","fact","inbox","todo","idea","insight","question","source","person","shipped"],s=[],i={declared:"DECL",extracted:"EXTR",inferred:"INFR",ambiguous:"AMBG"},o=t?.boundary==="llm",a=c((l,d)=>{if(d.length!==0){s.push(`### ${l.toUpperCase()}`);for(let p of d){let g=Object.entries(p.tags).map(([yr,it])=>`${yr}=${o?Us(it):it}`).join(" "),T=i[p.provenance],L=t?.vault?Ys(p.content,t):p.content,z=g?` _(${t?.vault?Ys(g,t):g})_`:"",A=p.id.replace(/^mem[_-]/,""),Z=t?.vault?` ^mem-${A}`:"",Nt=`- \`${T}\` [${p.id} \xB7 ${p.type}] ${L}${z}${Z}`;o?(s.push(`<user_content id="${p.id}" type="${p.type}">`),s.push(Nt),s.push("</user_content>")):s.push(Nt)}s.push("")}},"renderGroup"),u=new Set;for(let l of r){let d=e.get(l);!d||d.length===0||(a(l,d),u.add(l))}for(let[l,d]of e)u.has(l)||a(l,d);return s.join(`
|
|
601
|
+
`).trim()}var Js,fa,ha,ya,Sa,C,ht=E(()=>{"use strict";Ms();j();tr();be();Xs();Js=["fact","decision","learning","gotcha","pattern","anti-pattern","shipped","inbox","todo","idea","insight","question","source","person","spec"],fa=25,ha=4,ya=100;c(zs,"safeJson");c(te,"rowToEntry");c(Gs,"shippedRowToEntry");c(Ta,"matchesTopic");c(Ea,"matchesTags");c(ka,"dedupeLatestByKey");Sa=/\bmem[_-](\d+)\b/g;c(wa,"collectSupersededIds");C={async remember(n,t){let e=t.tags??{},r=t.provenance??"declared",s=kt(t.content),i;try{let{default:a}=await Promise.resolve().then(()=>(bt(),xn));i=(await a.readConfig(n))?.projectId}catch{}if(i)try{if(h.get(i,"SELECT id FROM memories WHERE content_hash = ? AND type = ? AND deleted_at IS NULL LIMIT 1",s,t.type))return}catch{}let o=await Os.log(n,`${er}${t.type}`,{content:t.content,tags:e,source:t.source,provenance:r});if(o?.eventId!=null)try{let a=`mem_${o.eventId}`,u=new Date().toISOString(),d=(t.content.split(`
|
|
602
602
|
`)[0]??t.content).slice(0,80);h.run(o.projectId,`INSERT OR IGNORE INTO memories
|
|
603
603
|
(id, project_id, title, content, tags, type, provenance, content_hash,
|
|
604
604
|
user_triggered, created_at, updated_at)
|
|
605
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,a,o.projectId,d,t.content,JSON.stringify(e),t.type,r,
|
|
605
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,a,o.projectId,d,t.content,JSON.stringify(e),t.type,r,s,0,u,u)}catch{}if(o?.projectId)try{let{usefulnessService:a}=await Promise.resolve().then(()=>(qs(),Hs));a.recordReferences(o.projectId,t.content,e),a.recordCorrection(o.projectId,e)}catch{}if(i)try{let{publishCRUD:a}=await Promise.resolve().then(()=>(xt(),Bn)),u=t.tags?.spec_id??t.tags?.task_id??t.tags?.id??t.source??`mem-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await a({projectId:i,entityType:"memories",entityId:u,eventType:"upsert",data:{id:u,type:t.type,content:t.content,tags:t.tags??{},source:t.source??null,provenance:t.provenance??"declared",rememberedAt:new Date().toISOString()}})}catch{}},searchFts(n,t,e){if(t.length===0||e<=0)return[];let r=t.map(o=>o.replace(/[^a-z0-9-]/gi,"")).filter(o=>o.length>=2);if(r.length===0)return[];let s=r.map(o=>`"${o}"*`).join(" OR "),i;try{i=h.query(n,`SELECT m.id, m.title, m.content, m.tags, m.type, m.provenance, m.created_at
|
|
606
606
|
FROM memories_fts ft
|
|
607
607
|
JOIN memories m ON m.rowid = ft.rowid
|
|
608
608
|
WHERE memories_fts MATCH ?
|
|
609
609
|
AND m.deleted_at IS NULL
|
|
610
610
|
ORDER BY bm25(memories_fts) ASC, m.created_at DESC
|
|
611
|
-
LIMIT ?`,
|
|
612
|
-
VALUES (?, ?, 'draft', ?, ?, ?, ?)`,r,e.title,JSON.stringify(i),e.tags?JSON.stringify(e.tags):null,
|
|
613
|
-
`)}function
|
|
614
|
-
`)}var
|
|
615
|
-
`)){let o=i.trim();o==="---COMMIT---"?(
|
|
611
|
+
LIMIT ?`,s,e)}catch{return[]}return i.map(o=>{let a={};if(o.tags)try{let u=JSON.parse(o.tags);u&&typeof u=="object"&&(a=u)}catch{}return{id:o.id,type:o.type??"fact",content:o.content,tags:a,rememberedAt:o.created_at,provenance:o.provenance??"declared"}})},recall(n,t={}){let e=t.limit??fa,r=Math.max(e*ha,ya),s=t.types&&t.types.length>0?new Set(t.types):null,i=s?s.has("shipped"):!0,a=(s?[...s].some(d=>d!=="shipped"):!0)?h.query(n,"SELECT id, type, data, timestamp FROM events WHERE type LIKE ? ORDER BY id DESC LIMIT ?",`${Q}%`,r):[],u=i?h.query(n,"SELECT id, name, type, shipped_at, data FROM shipped_features ORDER BY shipped_at DESC LIMIT ?",r):[],l=[...a.map(te),...u.map(Gs)];if(s&&(l=l.filter(d=>s.has(d.type))),t.tags&&(l=l.filter(d=>Ea(d,t.tags??{}))),t.topic&&(l=l.filter(d=>Ta(d,t.topic))),l.sort((d,p)=>p.rememberedAt.localeCompare(d.rememberedAt)),t.dedupeByKey!==!1&&(l=ka(l)),t.pruneSuperseded!==!1){let d=wa(l);d.size>0&&(l=l.filter(p=>!d.has(p.id)))}return l.slice(0,e)},recallForFile(n,t,e=3){if(!t)return[];let r=t.split("/").pop()??t,s=c(a=>a.type==="gotcha"||a.type==="anti-pattern"||a.tags?.pattern==="recurring-bug","isPreventive"),i;try{i=this.recall(n,{limit:500})}catch{return[]}return i.filter(a=>{let u=a.tags?.file;return u?(t===u||t.endsWith(`/${u}`)||(u.split("/").pop()??u)===r)&&s(a):!1}).slice(0,e)},getById(n,t){let e=String(t).trim().match(/^(?:mem[_-])?(\d+)$/i);if(!e)return null;let r=Number(e[1]);try{let s=h.get(n,"SELECT id, type, data, timestamp FROM events WHERE id = ? AND type LIKE ?",r,`${Q}%`);return s?te(s):null}catch{return null}},countByType(n,t){try{return h.get(n,"SELECT COUNT(*) AS n FROM events WHERE type = ?",`${Q}${t}`)?.n??0}catch{return 0}},recallByType(n,t,e){if(e<=0)return[];try{return h.query(n,"SELECT id, type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`${Q}${t}`,e).map(te)}catch{return[]}},forget(n,t){let e=String(t).trim().match(/^(?:mem[_-])?(\d+)$/i);if(!e)return!1;let r=Number(e[1]),s=`mem_${r}`,i=!1;try{h.get(n,"SELECT id FROM events WHERE id = ? AND type LIKE ?",r,`${Q}%`)&&(h.run(n,"DELETE FROM events WHERE id = ?",r),i=!0)}catch{}try{h.get(n,"SELECT id FROM memories WHERE id = ? AND deleted_at IS NULL",s)&&(h.run(n,"UPDATE memories SET deleted_at = ? WHERE id = ?",new Date().toISOString(),s),i=!0)}catch{}try{h.run(n,"DELETE FROM memory_embeddings WHERE memory_id = ?",s)}catch{}return i},expandWithLinks(n,t,e=5){if(t.length===0||e<=0)return[];let r=/\bmem[_-](\d+)\b/g,s=["resolves","relates","supersedes","superseded-by","duplicates","spec"],i=new Set(t.map(a=>a.id)),o=[];for(let a of t){if(o.length>=e)break;let u=new Set;for(let l of s){let d=a.tags?.[l];if(d)for(let p of String(d).matchAll(r))u.add(`mem_${p[1]}`)}for(let l of a.content.matchAll(r))u.add(`mem_${l[1]}`);for(let l of u){if(o.length>=e)break;if(i.has(l))continue;i.add(l);let d=C.getById(n,l);d&&o.push(d)}}return o},allEntriesForIndex(n){try{let t=h.query(n,"SELECT id, type, data, timestamp FROM events WHERE type LIKE ? ORDER BY id DESC",`${Q}%`),e=h.query(n,"SELECT id, name, type, shipped_at, data FROM shipped_features ORDER BY shipped_at DESC");return[...t.map(te),...e.map(Gs)]}catch{return[]}},similar(n,t,e=10){let r=t.toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>3);return r.length===0?[]:C.recall(n,{limit:200}).map(o=>{let a=`${o.content} ${Object.values(o.tags).join(" ")}`.toLowerCase(),u=r.reduce((l,d)=>a.includes(d)?l+1:l,0);return{entry:o,hits:u}}).filter(o=>o.hits>0).sort((o,a)=>a.hits-o.hits).slice(0,e).map(o=>o.entry)}};c(_a,"linkLabel");c(Ys,"linkifyMemRefs");c(ft,"formatMemoryMd")});function ni(n){return[...n].sort((t,e)=>{let r=ri[t.section]-ri[e.section];return r!==0?r:ei[t.priority]-ei[e.priority]})}var ei,ri,si=E(()=>{"use strict";ei={critical:0,high:1,medium:2,low:3},ri={active:0,previously_active:1,backlog:2};c(ni,"sortBySectionAndPriority")});var or,At,ar=E(()=>{"use strict";Rt();Gt();si();N();Jt();ze();or=class extends pt{static{c(this,"QueueStorage")}constructor(){super("queue.json",On)}getDefault(){return{tasks:[],lastUpdated:""}}getEventType(t){return`queue.${t}d`}async getTasks(t){return(await this.read(t)).tasks}async getActiveTasks(t){return(await this.read(t)).tasks.filter(r=>r.section==="active"&&!r.completed)}async getBacklog(t){return(await this.read(t)).tasks.filter(r=>r.section==="backlog"&&!r.completed)}async getNextTask(t){let e=await this.getActiveTasks(t);return ni(e)[0]||null}async addTask(t,e){let r={...e,id:H(),createdAt:f(),completed:!1};return await this.update(t,s=>({tasks:[...s.tasks,r],lastUpdated:f()})),await this.publishEvent(t,"queue.task_added",{taskId:r.id,description:r.description,priority:r.priority,section:r.section}),r}async addTasks(t,e){let r=f(),s=e.map(i=>({...i,id:H(),createdAt:r,completed:!1}));return await this.update(t,i=>({tasks:[...i.tasks,...s],lastUpdated:r})),await this.publishEvent(t,"queue.tasks_added",{count:s.length,tasks:s.map(i=>({id:i.id,description:i.description}))}),s}async removeTask(t,e){await this.update(t,r=>({tasks:r.tasks.filter(s=>s.id!==e),lastUpdated:f()})),await this.publishEvent(t,"queue.task_removed",{taskId:e})}async deleteByFeatureId(t,e){let r=0;return await this.update(t,s=>{let i=s.tasks.length,o=s.tasks.filter(a=>a.featureId!==e);return r=i-o.length,{tasks:o,lastUpdated:f()}}),r>0&&await this.publishEvent(t,"queue.tasks_removed_by_feature",{featureId:e,count:r}),r}async completeTask(t,e){let r=null;if(await this.update(t,s=>({tasks:s.tasks.map(o=>o.id===e?(r={...o,completed:!0,completedAt:f()},r):o),lastUpdated:f()})),r){let s=r;await this.publishEvent(t,"queue.task_completed",{taskId:e,description:s.description,completedAt:s.completedAt})}return r}async moveToSection(t,e,r){await this.update(t,s=>({tasks:s.tasks.map(i=>i.id===e?{...i,section:r}:i),lastUpdated:f()}))}async setPriority(t,e,r){await this.update(t,s=>({tasks:s.tasks.map(i=>i.id===e?{...i,priority:r}:i),lastUpdated:f()}))}async getTask(t,e){return(await this.read(t)).tasks.find(s=>s.id===e)||null}async updateTask(t,e,r){let s=null;return await this.update(t,i=>({tasks:i.tasks.map(o=>o.id===e?(s={...o,...r},s):o),lastUpdated:f()})),s&&await this.publishEvent(t,"queue.task_updated",{taskId:e}),s}async clearCompleted(t){let r=(await this.read(t)).tasks.filter(s=>s.completed).length;return await this.update(t,s=>({tasks:s.tasks.filter(i=>!i.completed),lastUpdated:f()})),r}async removeStaleCompleted(t){let e=await this.read(t),r=_r(Pt.QUEUE_COMPLETED_DAYS),s=e.tasks.filter(o=>o.completed&&o.completedAt&&new Date(o.completedAt)<r);if(s.length===0)return 0;lt.archiveMany(t,s.map(o=>({entityType:"queue_task",entityId:o.id,entityData:o,summary:o.description,reason:"age"})));let i=new Set(s.map(o=>o.id));return await this.update(t,o=>({tasks:o.tasks.filter(a=>!i.has(a.id)),lastUpdated:f()})),await this.publishEvent(t,"queue.stale_removed",{count:s.length}),s.length}},At=new or});import{z as _}from"zod";var yt,lr,ur,va,Y,ee=E(()=>{"use strict";yt=["draft","reviewed","in_progress","shipped","archived"],lr=["strategic","architecture","design"],ur=_.object({verdict:_.enum(["pass","fail"]),notes:_.string(),ts:_.string()}),va=_.object({risk:_.string().min(1),mitigation:_.string().min(1)}),Y=_.object({goal:_.string().min(1),eli10:_.string().default(""),stakes:_.string().default(""),acceptance_criteria:_.array(_.string().min(1)).default([]),scope:_.array(_.string()).default([]),out_of_scope:_.array(_.string()).default([]),risks:_.array(va).default([]),test_plan:_.array(_.string()).default([]),reviews:_.object({strategic:ur.optional(),architecture:ur.optional(),design:ur.optional()}).optional(),linked_tasks:_.array(_.string()).default([]),notes:_.string().default(""),tasks_created_at:_.string().nullable().default(null)})});var pr,P,re=E(()=>{"use strict";Rt();ee();N();j();pr=class{static{c(this,"SpecStorage")}nextUpdatedAt(t,e){let r=f(),i=h.get(t,"SELECT updated_at FROM specs WHERE id = ?",e)?.updated_at;return!i||r>i?r:new Date(new Date(i).getTime()+1).toISOString()}create(t,e){let r=H(),s=f(),i=Y.parse(e.content);return h.run(t,`INSERT INTO specs (id, title, status, content, tags, created_at, updated_at)
|
|
612
|
+
VALUES (?, ?, 'draft', ?, ?, ?, ?)`,r,e.title,JSON.stringify(i),e.tags?JSON.stringify(e.tags):null,s,s),{id:r,title:e.title,status:"draft",content:i,tags:e.tags??{},createdAt:s,updatedAt:s,shippedAt:null,shippedPr:null,shippedSha:null,archivedAt:null}}get(t,e){let r=h.get(t,"SELECT * FROM specs WHERE id = ?",e);return r?this.rowToSpec(r):null}list(t,e={}){let r="SELECT * FROM specs WHERE 1=1",s=[];return e.status&&(r+=" AND status = ?",s.push(e.status)),!e.includeArchived&&!e.status&&(r+=" AND status != 'archived'"),r+=" ORDER BY created_at DESC",h.query(t,r,...s).map(o=>this.rowToSpec(o))}search(t,e){let r=`%${e}%`;return h.query(t,"SELECT * FROM specs WHERE title LIKE ? OR content LIKE ? ORDER BY created_at DESC",r,r).map(i=>this.rowToSpec(i))}updateContent(t,e,r){let s=Y.parse(r),i=this.nextUpdatedAt(t,e);return h.run(t,"UPDATE specs SET content = ?, updated_at = ? WHERE id = ?",JSON.stringify(s),i,e),this.get(t,e)}casUpdate(t,e,r,s){let i=Y.parse(r),o=this.nextUpdatedAt(t,e);return h.run(t,"UPDATE specs SET content = ?, updated_at = ? WHERE id = ? AND updated_at = ?",JSON.stringify(i),o,e,s).changes===1}setStatus(t,e,r){if(!yt.includes(r))throw new Error(`invalid spec status: ${r}`);let s=this.nextUpdatedAt(t,e),i=[],o=[r,s];r==="shipped"&&(i.push("shipped_at = ?"),o.push(s)),r==="archived"&&(i.push("archived_at = ?"),o.push(s));let a=["status = ?","updated_at = ?",...i].join(", ");return o.push(e),h.run(t,`UPDATE specs SET ${a} WHERE id = ?`,...o),this.get(t,e)}setShippedPr(t,e,r){return h.run(t,"UPDATE specs SET shipped_pr = ?, updated_at = ? WHERE id = ?",r,this.nextUpdatedAt(t,e),e),this.get(t,e)}setShippedSha(t,e,r){return h.run(t,"UPDATE specs SET shipped_sha = ?, updated_at = ? WHERE id = ?",r,this.nextUpdatedAt(t,e),e),this.get(t,e)}linkTask(t,e,r){let s=this.get(t,e);if(!s)return null;if(s.content.linked_tasks.includes(r))return s;let i={...s.content,linked_tasks:[...s.content.linked_tasks,r]};return this.updateContent(t,e,i)}delete(t,e){return this.get(t,e)?(h.run(t,"DELETE FROM specs WHERE id = ?",e),!0):!1}count(t){let e=h.query(t,"SELECT status, COUNT(*) AS n FROM specs GROUP BY status"),r={total:0,draft:0,shipped:0};for(let s of e)r.total+=s.n,s.status==="draft"&&(r.draft=s.n),s.status==="shipped"&&(r.shipped=s.n);return r}rowToSpec(t){return{id:t.id,title:t.title,status:yt.includes(t.status)?t.status:"draft",content:Y.parse(JSON.parse(t.content)),tags:t.tags?JSON.parse(t.tags):{},createdAt:t.created_at,updatedAt:t.updated_at,shippedAt:t.shipped_at,shippedPr:t.shipped_pr,shippedSha:t.shipped_sha,archivedAt:t.archived_at}}},P=new pr});var ai={};K(ai,{inferSpecContext:()=>Pa,warnNoContextMatch:()=>Ia});async function Pa(n,t,e){let[r,s]=await Promise.all([Qt(n,e,{maxFiles:oi*4,minScore:xa}).catch(()=>({files:[]})),Promise.resolve(C.recall(t,{topic:n,limit:Ra})).catch(()=>[])]),i=Aa(r.files.map(u=>u.path),oi);return i.length===0&&s.length===0?{notesBlock:"",paths:[],memoryHits:0,empty:!0}:{notesBlock:Na(n,i,s),paths:i,memoryHits:s.length,empty:!1}}function Aa(n,t){let e=new Set,r=[];for(let s of n){let i=s.split("/").slice(0,2).join("/");if(!e.has(i)&&(e.add(i),r.push(s),r.length>=t))break}return r}function Na(n,t,e){let r=[];if(r.push("<!-- auto-context:tentative -->"),r.push("## Existing context (auto-inferred)"),r.push(""),r.push(`_Inferred from title "${n}". Validate before audit \u2014 entries tagged tentative._`),r.push(""),t.length>0){r.push("### Likely paths");for(let s of t)r.push(`- \`${s}\``);r.push("")}if(e.length>0){r.push("### Relevant prior memory");for(let s of e){let i=s.content.length>140?`${s.content.slice(0,137)}\u2026`:s.content,o=Object.entries(s.tags).map(([a,u])=>`${a}:${u}`).join(" ");r.push(`- **${s.type}**${o?` _(${o})_`:""} \u2014 ${i}`)}r.push("")}return r.push("<!-- /auto-context -->"),r.join(`
|
|
613
|
+
`)}function Ia(n,t){let e={level:"warn",code:"no_context_match",message:`No codebase or memory context matched "${n}"`,suggestion:t??"Fill spec.notes manually or run with `--skip-context` next time."};process.stderr.write(`${JSON.stringify(e)}
|
|
614
|
+
`)}var oi,Ra,xa,ci=E(()=>{"use strict";ht();Ve();oi=5,Ra=8,xa=.15;c(Pa,"inferSpecContext");c(Aa,"dedupeTopDirs");c(Na,"buildNotesBlock");c(Ia,"warnNoContextMatch")});var ui={};K(ui,{breakdownSpecToTasks:()=>Ca});async function Ca(n,t,e){let r=e.content.acceptance_criteria;if(r.length===0)return{taskIds:[],skippedReason:"no_acceptance_criteria"};if(e.content.tasks_created_at!==null)return{taskIds:[],skippedReason:"already_broken_down"};let s=!1;if(e.content.linked_tasks.length>0){s=!0,await At.deleteByFeatureId(n,e.id);let a={...e.content,linked_tasks:[]};P.updateContent(n,e.id,a)}let i=await At.addTasks(n,r.map(a=>({description:La(a),body:a,priority:"medium",type:"feature",section:"backlog",featureId:e.id,groupId:e.id,groupName:e.title})));for(let a of i)P.linkTask(n,e.id,a.id);let o=P.get(n,e.id);if(o){let a={...o.content,tasks_created_at:f()};P.updateContent(n,e.id,a)}return await C.remember(t,{type:"spec",content:`Auto-breakdown: ${i.length} tasks created from ${e.title}${s?" (recovered from partial)":""}`,tags:{spec_id:e.id,event:"auto_breakdown",task_count:String(i.length),...s?{recovered:"partial"}:{}},source:e.id}),{taskIds:i.map(a=>a.id),...s?{recoveredFromPartial:!0}:{}}}function La(n){let t=n.replace(/\s+/g," ").trim();return t.length<=140?t:`${t.slice(0,137)}\u2026`}var li=E(()=>{"use strict";ht();ar();re();N();c(Ca,"breakdownSpecToTasks");c(La,"truncateForDescription")});import{StdioServerTransport as $a}from"@modelcontextprotocol/sdk/server/stdio.js";import{McpServer as Fa}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as O}from"zod";oe();j();U();import mn from"node:fs/promises";import ct from"node:path";function Bi(n){let t=[],e,r=new RegExp(Sr.source,"g");for(;(e=r.exec(n))!==null;){let s=e[1];(s.startsWith(".")||s.startsWith("@/"))&&t.push(s)}return t}c(Bi,"extractImportSources");async function Hi(n,t,e){let r;if(n.startsWith("@/"))r=ct.join(e,"src",n.slice(2));else{let s=ct.dirname(ct.join(e,t));r=ct.resolve(s,n)}for(let s of kr){let i=r+s;try{if((await mn.stat(i)).isFile())return ct.relative(e,i)}catch{}}return null}c(Hi,"resolveImport");async function qi(n){let t=await Ar(n),e={},r={},s=0,i=await Nr(t,50,async o=>{try{let a=await mn.readFile(ct.join(n,o),"utf-8"),u=Bi(a),l=[];for(let d of u){let p=await Hi(d,o,n);p&&p!==o&&l.push(p)}return l.length>0?{filePath:o,imports:l}:null}catch{return null}});for(let{filePath:o,imports:a}of i){e[o]=a,s+=a.length;for(let u of a)r[u]||(r[u]=[]),r[u].push(o)}return{forward:e,reverse:r,fileCount:t.length,edgeCount:s,builtAt:new Date().toISOString()}}c(qi,"buildGraph");function gn(n,t,e=2){let r=new Set(n),s=new Map,i=[];for(let o of n){let a=t.forward[o]||[],u=t.reverse[o]||[];for(let l of[...a,...u])r.has(l)||i.push({file:l,depth:1})}for(;i.length>0;){let{file:o,depth:a}=i.shift();if(a>e)continue;let u=1/(a+1),l=s.get(o);if(l){u>l.score&&s.set(o,{score:u,depth:a});continue}if(s.set(o,{score:u,depth:a}),a<e){let d=t.forward[o]||[],p=t.reverse[o]||[];for(let g of[...d,...p])!r.has(g)&&!s.has(g)&&i.push({file:g,depth:a+1})}}return Array.from(s.entries()).map(([o,{score:a,depth:u}])=>({path:o,score:a,depth:u})).sort((o,a)=>a.score-o.score)}c(gn,"scoreFromSeeds");var Re="import-graph",$t=new Map;function Gi(n,t){h.setDoc(n,Re,t),$t.delete(n)}c(Gi,"saveGraph");function wt(n){let t=h.get(n,"SELECT updated_at FROM kv_store WHERE key = ?",Re);if(!t)return $t.delete(n),null;let e=$t.get(n);if(e&&e.updatedAt===t.updated_at)return e.graph;let r=h.getDoc(n,Re);return r&&$t.set(n,{graph:r,updatedAt:t.updated_at}),r}c(wt,"loadGraph");async function fn(n,t){let e=await qi(n);return Gi(t,e),e}c(fn,"indexImports");function hn(n,t){let e=[...n.added,...n.modified],r=new Set(e),s=new Set,i=wt(t);if(i)for(let u of e){let l=i.reverse[u];if(l)for(let d of l)r.has(d)||s.add(d)}let o=Array.from(s),a=[...e,...o];return{directlyChanged:e,affectedByImports:o,deleted:n.deleted,allAffected:a}}c(hn,"propagateChanges");function yn(n){let t=new Set;for(let e of n){let r=e.toLowerCase();(r.endsWith(".tsx")||r.endsWith(".jsx")||r.endsWith(".css")||r.endsWith(".scss")||r.endsWith(".vue")||r.endsWith(".svelte")||r.includes("/components/")||r.includes("/pages/")||r.includes("/app/"))&&(t.add("frontend"),t.add("uxui")),(r.includes(".test.")||r.includes(".spec.")||r.includes("__tests__")||r.includes("/test/"))&&t.add("testing"),(r.includes("dockerfile")||r.includes("docker-compose")||r.includes(".dockerignore")||r.includes(".github/")||r.includes("ci/")||r.includes("cd/"))&&t.add("devops"),(r.endsWith(".sql")||r.includes("prisma")||r.includes("drizzle")||r.includes("migration")||r.includes("/db/"))&&t.add("database"),(r.endsWith(".ts")||r.endsWith(".js"))&&!r.includes(".test.")&&!r.includes(".spec.")&&!r.endsWith(".d.ts")&&t.add("backend")}return t}c(yn,"affectedDomains");j();rt();async function Ji(n,t=100){try{let{stdout:e}=await b(`git log --name-only --pretty=format:'---COMMIT---' -${t}`,{cwd:n,maxBuffer:10485760}),r=[],s=null;for(let i of e.split(`
|
|
615
|
+
`)){let o=i.trim();o==="---COMMIT---"?(s&&s.size>0&&s.size<=30&&r.push(s),s=new Set):o&&s&&zi(o)&&s.add(o)}return s&&s.size>0&&s.size<=30&&r.push(s),r}catch{return[]}}c(Ji,"parseGitLog");function zi(n){return/\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|cs|rb|php|vue|svelte)$/i.test(n)&&!n.includes("node_modules/")}c(zi,"isSourceFile");async function Ki(n,t=100){let e=await Ji(n,t),r=new Map,s=new Map;for(let o of e){let a=Array.from(o);for(let u of a)r.set(u,(r.get(u)||0)+1);for(let u=0;u<a.length;u++)for(let l=u+1;l<a.length;l++){let d=Vi(a[u],a[l]);s.set(d,(s.get(d)||0)+1)}}let i={};for(let[o,a]of s){let[u,l]=o.split("\0"),d=r.get(u)||0,p=r.get(l)||0;if(d<2||p<2)continue;let g=d+p-a,T=g>0?a/g:0;T<.1||(i[u]||(i[u]={}),i[l]||(i[l]={}),i[u][l]=T,i[l][u]=T)}return{matrix:i,commitsAnalyzed:e.length,filesAnalyzed:r.size,builtAt:new Date().toISOString()}}c(Ki,"buildMatrix");function Vi(n,t){return n<t?`${n}\0${t}`:`${t}\0${n}`}c(Vi,"pairKey");function Pe(n,t){let e=new Set(n),r=new Map;for(let s of n){let i=t.matrix[s];if(i)for(let[o,a]of Object.entries(i)){if(e.has(o))continue;let u=r.get(o)||0;a>u&&r.set(o,a)}}return Array.from(r.entries()).map(([s,i])=>({path:s,score:i})).sort((s,i)=>i.score-s.score)}c(Pe,"scoreFromSeeds");var xe="cochange-index",Xt=new Map;function Qi(n,t){h.setDoc(n,xe,t),Xt.delete(n)}c(Qi,"saveMatrix");function Ae(n){let t=h.get(n,"SELECT updated_at FROM kv_store WHERE key = ?",xe);if(!t)return Xt.delete(n),null;let e=Xt.get(n);if(e&&e.updatedAt===t.updated_at)return e.matrix;let r=h.getDoc(n,xe);return r&&Xt.set(n,{matrix:r,updatedAt:t.updated_at}),r}c(Ae,"loadMatrix");async function kn(n,t,e=100){let r=await Ki(n,e);return Qi(t,r),r}c(kn,"indexCoChanges");bt();async function x(n){return B.getProjectId(n)}c(x,"resolveProjectId");function S(n,t){return async e=>{try{return await t(e)}catch(r){return ao(r,n)}}}c(S,"safeMcpCall");function ao(n,t){let e=n instanceof Error?n.message:String(n);return{content:[{type:"text",text:`[${t}] Error: ${e}`}],isError:!0}}c(ao,"mcpError");function Pn(n){let t=n;t.tool("prjct_impact_analysis","Given changed files, find affected files via import graph + affected domains",{projectPath:O.string().describe("Project directory path"),changedFiles:O.array(O.string()).describe("List of changed file paths (relative to project root)")},S("prjct_impact_analysis",async e=>{let r=await x(e.projectPath),s={added:[],modified:e.changedFiles,deleted:[],unchanged:[]},i=hn(s,r),o=yn(i.allAffected),a=["## Impact Analysis"];a.push(`
|
|
616
616
|
### Directly Changed (${i.directlyChanged.length})`);for(let u of i.directlyChanged)a.push(`- ${u}`);if(i.affectedByImports.length>0){a.push(`
|
|
617
617
|
### Affected via Imports (${i.affectedByImports.length})`);for(let u of i.affectedByImports)a.push(`- ${u}`)}return a.push(`
|
|
618
618
|
### Affected Domains`),a.push(o.size>0?Array.from(o).join(", "):"none detected"),a.push(`
|
|
619
619
|
Total affected: ${i.allAffected.length} files`),{content:[{type:"text",text:a.join(`
|
|
620
|
-
`)}]}})),t.tool("prjct_import_graph","Import graph stats + file neighbors (imports/importers). Pass a file for its neighbors, omit for graph stats.",{projectPath:O.string().describe("Project directory path"),file:O.string().optional().describe("File path to get neighbors for (omit for graph stats)"),rebuild:O.boolean().optional().default(!1).describe("Force rebuild the import graph")},S("prjct_import_graph",async e=>{let r=await x(e.projectPath),
|
|
620
|
+
`)}]}})),t.tool("prjct_import_graph","Import graph stats + file neighbors (imports/importers). Pass a file for its neighbors, omit for graph stats.",{projectPath:O.string().describe("Project directory path"),file:O.string().optional().describe("File path to get neighbors for (omit for graph stats)"),rebuild:O.boolean().optional().default(!1).describe("Force rebuild the import graph")},S("prjct_import_graph",async e=>{let r=await x(e.projectPath),s=e.rebuild?null:wt(r);if(s||(s=await fn(e.projectPath,r)),e.file){let o=s.forward[e.file]||[],a=s.reverse[e.file]||[];return{content:[{type:"text",text:[`## Import Neighbors: ${e.file}`,`
|
|
621
621
|
### Imports (${o.length})`,...o.map(l=>`- ${l}`),`
|
|
622
622
|
### Imported By (${a.length})`,...a.map(l=>`- ${l}`)].join(`
|
|
623
|
-
`)}]}}return{content:[{type:"text",text:["## Import Graph Stats",`Files: ${
|
|
624
|
-
`)}]}})),t.tool("prjct_cochange","Files that historically change together (Jaccard similarity from git history)",{projectPath:O.string().describe("Project directory path"),seedFiles:O.array(O.string()).describe("Seed files to find co-change partners for"),rebuild:O.boolean().optional().default(!1).describe("Force rebuild the co-change matrix"),maxResults:O.number().optional().default(10).describe("Max results (default 10)")},S("prjct_cochange",async e=>{let r=await x(e.projectPath),
|
|
625
|
-
`)}]}})),t.tool("prjct_related_context","Combined: import neighbors + co-change partners for seed files",{projectPath:O.string().describe("Project directory path"),seedFiles:O.array(O.string()).describe("Seed files to find related context for"),maxResults:O.number().optional().default(15).describe("Max results (default 15)")},S("prjct_related_context",async e=>{let r=await x(e.projectPath),
|
|
626
|
-
`)}]}}))}c(
|
|
627
|
-
${
|
|
628
|
-
`)}`)}let{output:n,summary:i}=r.data,o=await s.read(t);if(!o.currentTask?.subtasks)return null;let a=o.currentTask.currentSubtaskIndex||0,u=o.currentTask.subtasks[a];if(!u)return null;let l=[...o.currentTask.subtasks];l[a]={...u,status:"completed",completedAt:f(),output:n,summary:i};let d=l.filter(D=>D.status==="completed").length,p=l.length,g=Math.round(d/p*100),T=a+1;return T<l.length&&(l[T]={...l[T],status:"in_progress",startedAt:f()}),await s.update(t,D=>({...D,currentTask:{...D.currentTask,subtasks:l,currentSubtaskIndex:T<p?T:a,subtaskProgress:{completed:d,total:p,percentage:g}},lastUpdated:f()})),await s.publish(t,"subtask.completed",{taskId:o.currentTask.id,subtaskId:u.id,description:u.description,output:n,handoff:i.outputForNextAgent,filesChanged:i.filesChanged.length,progress:{completed:d,total:p,percentage:g}}),T<p?l[T]:null}c(Qs,"completeSubtask");async function Zs(s,t){let e=await s.read(t);if(!e.currentTask?.subtasks)return null;let r=e.currentTask.currentSubtaskIndex||0;return e.currentTask.subtasks[r]||null}c(Zs,"getCurrentSubtask");async function tn(s,t){let e=await s.read(t);if(!e.currentTask?.subtasks)return null;let r=(e.currentTask.currentSubtaskIndex||0)+1;return e.currentTask.subtasks[r]||null}c(tn,"getNextSubtask");async function qe(s,t){let e=await s.read(t);if(!e.currentTask?.subtasks)return null;let r=(e.currentTask.currentSubtaskIndex||0)-1;return r<0?null:e.currentTask.subtasks[r]||null}c(qe,"getPreviousSubtask");async function en(s,t){let e=await qe(s,t);return e?.summary?.outputForNextAgent?{fromSubtask:e.description,outputForNextAgent:e.summary.outputForNextAgent,filesChanged:e.summary.filesChanged,whatWasDone:e.summary.whatWasDone}:null}c(en,"getPreviousHandoff");async function rn(s,t){return(await s.read(t)).currentTask?.subtasks||[]}c(rn,"getSubtasks");async function sn(s,t){return(await s.read(t)).currentTask?.subtaskProgress||null}c(sn,"getSubtaskProgress");async function nn(s,t){return((await s.read(t)).currentTask?.subtasks?.length||0)>0}c(nn,"hasSubtasks");async function on(s,t){let e=await s.read(t);return e.currentTask?.subtasks?e.currentTask.subtasks.every(r=>r.status==="completed"||r.status==="failed"||r.status==="skipped"):!0}c(on,"areAllSubtasksComplete");async function an(s,t,e){let r=await s.read(t);if(!r.currentTask?.subtasks)return null;let n=r.currentTask.currentSubtaskIndex||0,i=r.currentTask.subtasks[n];if(!i)return null;let o=[...r.currentTask.subtasks];o[n]={...i,status:"failed",completedAt:f(),output:`Failed: ${e}`};let a=n+1,u=o.length;a<u&&(o[a]={...o[a],status:"in_progress",startedAt:f()});let l=o.filter(p=>p.status==="completed"||p.status==="failed"||p.status==="skipped").length,d=Math.round(l/u*100);return await s.update(t,p=>({...p,currentTask:{...p.currentTask,subtasks:o,currentSubtaskIndex:a<u?a:n,subtaskProgress:{completed:l,total:u,percentage:d}},lastUpdated:f()})),await s.publish(t,"subtask.failed",{taskId:r.currentTask.id,subtaskId:i.id,description:i.description,error:e}),a<u?o[a]:null}c(an,"failSubtask");async function cn(s,t,e){let r=await s.read(t);if(!r.currentTask?.subtasks)return null;let n=r.currentTask.currentSubtaskIndex||0,i=r.currentTask.subtasks[n];if(!i)return null;let o=[...r.currentTask.subtasks];o[n]={...i,status:"skipped",completedAt:f(),output:`Skipped: ${e}`,skipReason:e};let a=n+1,u=o.length;a<u&&(o[a]={...o[a],status:"in_progress",startedAt:f()});let l=o.filter(p=>p.status==="completed"||p.status==="failed"||p.status==="skipped").length,d=Math.round(l/u*100);return await s.update(t,p=>({...p,currentTask:{...p.currentTask,subtasks:o,currentSubtaskIndex:a<u?a:n,subtaskProgress:{completed:l,total:u,percentage:d}},lastUpdated:f()})),await s.publish(t,"subtask.skipped",{taskId:r.currentTask.id,subtaskId:i.id,description:i.description,reason:e}),a<u?o[a]:null}c(cn,"skipSubtask");async function un(s,t,e){let r=await s.read(t);if(!r.currentTask?.subtasks)return null;let n=r.currentTask.currentSubtaskIndex||0,i=r.currentTask.subtasks[n];if(!i)return null;let o=[...r.currentTask.subtasks];o[n]={...i,status:"blocked",output:`Blocked: ${e}`,blockReason:e};let a=n+1,u=o.length;return a<u&&(o[a]={...o[a],status:"in_progress",startedAt:f()}),await s.update(t,l=>({...l,currentTask:{...l.currentTask,subtasks:o,currentSubtaskIndex:a<u?a:n},lastUpdated:f()})),await s.publish(t,"subtask.blocked",{taskId:r.currentTask.id,subtaskId:i.id,description:i.description,blocker:e}),a<u?o[a]:null}c(un,"blockSubtask");N();async function ln(s,t,e,r){let n={...e,workspaceId:r,startedAt:f()};return await s.update(t,i=>({...i,activeTasks:[...i.activeTasks||[],n],lastUpdated:f()})),await s.publish(t,"task.started",{taskId:n.id,description:n.description,startedAt:n.startedAt,sessionId:n.sessionId,workspaceId:r}),n}c(ln,"startTaskInWorkspace");async function pn(s,t,e){return((await s.read(t)).activeTasks||[]).find(n=>n.workspaceId===e)??null}c(pn,"getCurrentTaskForWorkspace");async function dn(s,t,e,r){let n=await s.read(t),o=(n.activeTasks||[]).find(p=>p.workspaceId===e);if(!o)return null;let a=f(),u=s.createTaskHistoryEntry(o,a,r),l=s.getTaskHistoryFromState(n),d=[u,...l].slice(0,s.maxTaskHistory);return await s.update(t,p=>({...p,activeTasks:(p.activeTasks||[]).filter(g=>g.workspaceId!==e),taskHistory:d,lastUpdated:a})),await s.publish(t,"task.completed",{taskId:o.id,description:o.description,startedAt:o.startedAt,completedAt:a,workspaceId:e}),o}c(dn,"completeTaskInWorkspace");async function mn(s,t){return(await s.read(t)).activeTasks||[]}c(mn,"getActiveTasks");async function gn(s,t){return((await s.read(t)).activeTasks||[]).length}c(gn,"getActiveTaskCount");async function fn(s,t,e,r){let i=(await s.read(t)).activeTasks||[],o=i.findIndex(u=>u.workspaceId===e);if(o===-1)return null;let a={...i[o],...r,workspaceId:e};return await s.update(t,u=>{let l=[...u.activeTasks||[]];return l[o]=a,{...u,activeTasks:l,lastUpdated:f()}}),a}c(fn,"updateWorkspaceTask");async function hn(s,t,e,r){let n=await s.read(t);if(!n.currentTask)return null;let i=(n.currentTask.tokensIn||0)+e,o=(n.currentTask.tokensOut||0)+r;return await s.update(t,a=>({...a,currentTask:{...a.currentTask,tokensIn:i,tokensOut:o},lastUpdated:f()})),{tokensIn:i,tokensOut:o}}c(hn,"addTokens");Ge();var Ye=class extends pt{static{c(this,"StateStorage")}constructor(){super("state.json",Ns)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],activeTasks:[],lastUpdated:""}}getEventType(t){return`state.${t}d`}validateTransition(t,e){let r=Oe.getCurrentState(t),n=Oe.canTransition(r,e);if(!n.valid)throw new Error(`${n.error}. ${n.suggestion||""}`.trim())}async getCurrentTask(t){return(await this.read(t)).currentTask}async getPausedTasks(t){let e=await this.read(t);return this.getPausedTasksFromState(e)}async startTask(t,e){let r=await this.read(t);this.validateTransition(r,"task");let n={...e,startedAt:f()};return await this.update(t,i=>({...i,currentTask:n,lastUpdated:f()})),await this.publishEvent(t,"task.started",{taskId:n.id,description:n.description,startedAt:n.startedAt,sessionId:n.sessionId}),n}async updateCurrentTask(t,e){let r=await this.read(t);if(!r.currentTask)return null;let n={...r.currentTask,...e};return await this.update(t,i=>({...i,currentTask:n,lastUpdated:f()})),n}async completeTask(t,e){let r=await this.read(t),n=r.currentTask;if(!n)return null;this.validateTransition(r,"done");let i=f(),o=this.createTaskHistoryEntry(n,i,e),a=this.getTaskHistoryFromState(r),u=[o,...a].slice(0,this.maxTaskHistory);return await this.update(t,l=>({...l,currentTask:null,previousTask:null,taskHistory:u,lastUpdated:i})),await this.publishEvent(t,"task.completed",{taskId:n.id,description:n.description,startedAt:n.startedAt,completedAt:i}),n}createTaskHistoryEntry(t,e,r){let n=(t.subtasks||[]).filter(a=>a.status==="completed"&&a.summary).map(a=>a.summary),i=n.length>0?n.map(a=>a.title).join(", "):"Task completed",o={taskId:t.id,title:t.parentDescription||t.description,classification:t.type||"improvement",startedAt:t.startedAt,completedAt:e,subtaskCount:t.subtasks?.length||0,subtaskSummaries:n,outcome:i,branchName:t.branch||"unknown",linearId:t.linearId,linearUuid:t.linearUuid,prUrl:t.prUrl};return r&&(o.feedback=r),t.tokensIn&&(o.tokensIn=t.tokensIn),t.tokensOut&&(o.tokensOut=t.tokensOut),o}maxPausedTasks=5;maxTaskHistory=20;stalenessThresholdDays=30;lifecycleBackend(){return{read:this.read.bind(this),update:this.update.bind(this),publish:this.publishEvent.bind(this),validateTransition:this.validateTransition.bind(this),getPausedTasksFromState:this.getPausedTasksFromState.bind(this),maxPausedTasks:this.maxPausedTasks,stalenessThresholdDays:this.stalenessThresholdDays}}async pauseTask(t,e){return Us(this.lifecycleBackend(),t,e)}async resumeTask(t,e){return Xs(this.lifecycleBackend(),t,e)}getPausedTasksFromState(t){return Array.isArray(t.pausedTasks)&&t.pausedTasks.length>0?t.pausedTasks:t.previousTask?[t.previousTask]:[]}getTaskHistoryFromState(t){return t.taskHistory||[]}async getStalePausedTasks(t){return Ws(this.lifecycleBackend(),t)}async archiveStalePausedTasks(t){return Bs(this.lifecycleBackend(),t)}queryBackend(){return{read:this.read.bind(this),update:this.update.bind(this),getPausedTasksFromState:this.getPausedTasksFromState.bind(this),getTaskHistoryFromState:this.getTaskHistoryFromState.bind(this)}}async clearTask(t){return Hs(this.queryBackend(),t)}async hasTask(t){return qs(this.queryBackend(),t)}async getPausedTask(t){return Gs(this.queryBackend(),t)}async getAllPausedTasks(t){return Ys(this.queryBackend(),t)}async getTaskHistory(t){return He(this.queryBackend(),t)}async getMostRecentTask(t){return Js(this.queryBackend(),t)}async getTaskHistoryByType(t,e){return zs(this.queryBackend(),t,e)}async getAggregatedFeedback(t){return Ks(this.queryBackend(),t)}workspaceBackend(){return{read:this.read.bind(this),update:this.update.bind(this),publish:this.publishEvent.bind(this),createTaskHistoryEntry:this.createTaskHistoryEntry.bind(this),getTaskHistoryFromState:this.getTaskHistoryFromState.bind(this),maxTaskHistory:this.maxTaskHistory}}async startTaskInWorkspace(t,e,r){return ln(this.workspaceBackend(),t,e,r)}async getCurrentTaskForWorkspace(t,e){return pn(this.workspaceBackend(),t,e)}async completeTaskInWorkspace(t,e,r){return dn(this.workspaceBackend(),t,e,r)}async getActiveTasks(t){return mn(this.workspaceBackend(),t)}async getActiveTaskCount(t){return gn(this.workspaceBackend(),t)}async updateWorkspaceTask(t,e,r){return fn(this.workspaceBackend(),t,e,r)}async addTokens(t,e,r){return hn(this.workspaceBackend(),t,e,r)}subtaskBackend(){return{read:this.read.bind(this),update:this.update.bind(this),publish:this.publishEvent.bind(this)}}async createSubtasks(t,e){return Vs(this.subtaskBackend(),t,e)}async completeSubtask(t,e){return Qs(this.subtaskBackend(),t,e)}async getCurrentSubtask(t){return Zs(this.subtaskBackend(),t)}async getNextSubtask(t){return tn(this.subtaskBackend(),t)}async getPreviousSubtask(t){return qe(this.subtaskBackend(),t)}async getPreviousHandoff(t){return en(this.subtaskBackend(),t)}async getSubtasks(t){return rn(this.subtaskBackend(),t)}async getSubtaskProgress(t){return sn(this.subtaskBackend(),t)}async hasSubtasks(t){return nn(this.subtaskBackend(),t)}async areAllSubtasksComplete(t){return on(this.subtaskBackend(),t)}async failSubtask(t,e){return an(this.subtaskBackend(),t,e)}async skipSubtask(t,e){return cn(this.subtaskBackend(),t,e)}async blockSubtask(t,e){return un(this.subtaskBackend(),t,e)}},dt=new Ye;Je();tt();import Uo from"node:fs/promises";import mt from"node:path";var jo={"claude-opus-4.5":{input:.005,output:.025},"claude-sonnet-4.5":{input:.003,output:.015},"claude-haiku-4.5":{input:.001,output:.005},"claude-opus-4":{input:.015,output:.075},"claude-opus-4-6":{input:.015,output:.075},"gpt-4o":{input:.0025,output:.01},"gpt-4-turbo":{input:.01,output:.03},"gpt-4o-mini":{input:15e-5,output:6e-4},"gemini-1.5-pro":{input:.00125,output:.005},"gemini-1.5-flash":{input:75e-6,output:3e-4}},Fo="claude-sonnet-4.5";function ze(s){return!s||s.length===0?0:Math.ceil(s.length/4)}c(ze,"countTokens");var _n=["claude-sonnet-4.5","claude-opus-4.5","claude-opus-4-6","gpt-4o","gemini-1.5-pro"];function wn(s,t){let e=jo[t],r=s/1e3*e.input,n=s/1e3*e.output*.3;return{inputSaved:r,outputPotential:n,total:r+n}}c(wn,"calculateModelCost");function $o(s){return s<.001?"<$0.01":s<.01?`$${s.toFixed(3)}`:`$${s.toFixed(2)}`}c($o,"formatCostSaved");function bn(s,t){let e=ze(s),r=ze(t),n=Math.max(0,e-r),i=e>0?(e-r)/e:0,o=wn(n,Fo),a=_n.map(u=>({model:u,...wn(n,u)}));return{tokens:{original:e,filtered:r,saved:n},compression:Math.max(0,Math.min(1,i)),cost:{saved:o.total,formatted:$o(o.total),byModel:a}}}c(bn,"measureCompression");function Kt(s){let t=ze(s);return{tokens:{original:t,filtered:t,saved:0},compression:0,cost:{saved:0,formatted:"$0.00",byModel:_n.map(e=>({model:e,inputSaved:0,outputPotential:0,total:0}))}}}c(Kt,"noCompression");var Xo={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".go":"go",".rs":"rust",".java":"java",".cs":"csharp",".php":"php",".rb":"ruby"},vn=[{type:"function",pattern:/^export\s+(?:async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)\s*(?::\s*([^{;]+))?/gm,nameIndex:1,exported:!0},{type:"function",pattern:/^export\s+const\s+(\w+)\s*(?::\s*[^=]+)?\s*=\s*(?:async\s+)?\([^)]*\)\s*(?::\s*[^=]+)?\s*=>/gm,nameIndex:1,exported:!0},{type:"function",pattern:/^(?:async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)\s*(?::\s*([^{;]+))?/gm,nameIndex:1},{type:"function",pattern:/^const\s+(\w+)\s*(?::\s*[^=]+)?\s*=\s*(?:async\s+)?\([^)]*\)\s*(?::\s*[^=]+)?\s*=>/gm,nameIndex:1},{type:"interface",pattern:/^export\s+interface\s+(\w+)(?:<[^>]+>)?\s*(?:extends\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"interface",pattern:/^interface\s+(\w+)(?:<[^>]+>)?\s*(?:extends\s+[^{]+)?\s*\{/gm,nameIndex:1},{type:"type",pattern:/^export\s+type\s+(\w+)(?:<[^>]+>)?\s*=/gm,nameIndex:1,exported:!0},{type:"type",pattern:/^type\s+(\w+)(?:<[^>]+>)?\s*=/gm,nameIndex:1},{type:"class",pattern:/^export\s+(?:abstract\s+)?class\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+[^{]+)?(?:\s+implements\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"class",pattern:/^(?:abstract\s+)?class\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+[^{]+)?(?:\s+implements\s+[^{]+)?\s*\{/gm,nameIndex:1},{type:"enum",pattern:/^export\s+enum\s+(\w+)\s*\{/gm,nameIndex:1,exported:!0},{type:"enum",pattern:/^enum\s+(\w+)\s*\{/gm,nameIndex:1},{type:"const",pattern:/^export\s+const\s+(\w+)\s*(?::\s*([^=]+))?\s*=/gm,nameIndex:1,exported:!0}],Wo=[{type:"function",pattern:/^def\s+(\w+)\s*\(([^)]*)\)\s*(?:->\s*([^:]+))?\s*:/gm,nameIndex:1},{type:"function",pattern:/^async\s+def\s+(\w+)\s*\(([^)]*)\)\s*(?:->\s*([^:]+))?\s*:/gm,nameIndex:1},{type:"class",pattern:/^class\s+(\w+)(?:\(([^)]*)\))?\s*:/gm,nameIndex:1}],Bo=[{type:"function",pattern:/^func\s+(\w+)\s*\(([^)]*)\)\s*(?:\(([^)]*)\)|([^\s{]+))?\s*\{/gm,nameIndex:1},{type:"method",pattern:/^func\s+\([^)]+\)\s+(\w+)\s*\(([^)]*)\)\s*(?:\(([^)]*)\)|([^\s{]+))?\s*\{/gm,nameIndex:1},{type:"type",pattern:/^type\s+(\w+)\s+(?:struct|interface)\s*\{/gm,nameIndex:1}],Ho=[{type:"function",pattern:/^pub\s+(?:async\s+)?fn\s+(\w+)(?:<[^>]+>)?\s*\(([^)]*)\)\s*(?:->\s*([^{]+))?\s*\{/gm,nameIndex:1,exported:!0},{type:"function",pattern:/^(?:async\s+)?fn\s+(\w+)(?:<[^>]+>)?\s*\(([^)]*)\)\s*(?:->\s*([^{]+))?\s*\{/gm,nameIndex:1},{type:"class",pattern:/^pub\s+struct\s+(\w+)(?:<[^>]+>)?\s*(?:\{|;)/gm,nameIndex:1,exported:!0},{type:"class",pattern:/^struct\s+(\w+)(?:<[^>]+>)?\s*(?:\{|;)/gm,nameIndex:1},{type:"interface",pattern:/^pub\s+trait\s+(\w+)(?:<[^>]+>)?\s*(?:\{|:)/gm,nameIndex:1,exported:!0},{type:"interface",pattern:/^trait\s+(\w+)(?:<[^>]+>)?\s*(?:\{|:)/gm,nameIndex:1},{type:"enum",pattern:/^pub\s+enum\s+(\w+)(?:<[^>]+>)?\s*\{/gm,nameIndex:1,exported:!0},{type:"enum",pattern:/^enum\s+(\w+)(?:<[^>]+>)?\s*\{/gm,nameIndex:1}],Rn=[{type:"class",pattern:/^(?:public\s+)?(?:abstract\s+)?(?:final\s+)?class\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+\w+)?(?:\s+implements\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"interface",pattern:/^(?:public\s+)?interface\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"method",pattern:/^\s+(?:public|private|protected)?\s*(?:static\s+)?(?:final\s+)?(?:synchronized\s+)?(?:<[^>]+>\s+)?(\w+(?:<[^>]+>)?)\s+(\w+)\s*\([^)]*\)\s*(?:throws\s+[^{]+)?\s*\{/gm,nameIndex:2}],qo={typescript:vn,javascript:vn,python:Wo,go:Bo,rust:Ho,java:Rn,csharp:Rn,php:[],ruby:[],unknown:[]};async function xn(s,t=process.cwd()){let e=mt.isAbsolute(s)?s:mt.join(t,s),r=mt.resolve(t),n=mt.resolve(e);if(!n.startsWith(r+mt.sep)&&n!==r)return{file:s,language:"unknown",signatures:[],fallback:!0,fallbackReason:"Path traversal denied: file is outside project directory",metrics:Kt("")};let i;try{i=await Uo.readFile(e,"utf-8")}catch(p){if(M(p))return{file:s,language:"unknown",signatures:[],fallback:!0,fallbackReason:"File not found",metrics:Kt("")};throw p}let o=mt.extname(s).toLowerCase(),a=Xo[o]||"unknown",u=qo[a];if(!u||u.length===0)return{file:s,language:a,signatures:[],fallback:!0,fallbackReason:`No extraction patterns for ${a}`,metrics:Kt(i)};let l=Go(i,u),d=l.map(p=>`${p.exported?"export ":""}${p.type} ${p.name}: ${p.signature}`).join(`
|
|
629
|
-
`);return{file:
|
|
630
|
-
`),
|
|
631
|
-
`).length,p=o[0].trim(),g;if(d>1){let T=r[d-2]?.trim();(T?.startsWith("/**")||T?.startsWith("///")||T?.startsWith("#"))&&(g=T)}e.push({type:i.type,name:a,signature:
|
|
632
|
-
|
|
633
|
-
${
|
|
634
|
-
`)}`}]}})),t.tool("prjct_signatures","Code signatures from a file (90% token reduction vs full content)",{projectPath:st.string().describe("Project directory path"),filePath:st.string().describe("Relative file path to extract signatures from")},S("prjct_signatures",async e=>{let r=await
|
|
623
|
+
`)}]}}return{content:[{type:"text",text:["## Import Graph Stats",`Files: ${s.fileCount}`,`Edges: ${s.edgeCount}`,`Built: ${s.builtAt}`].join(`
|
|
624
|
+
`)}]}})),t.tool("prjct_cochange","Files that historically change together (Jaccard similarity from git history)",{projectPath:O.string().describe("Project directory path"),seedFiles:O.array(O.string()).describe("Seed files to find co-change partners for"),rebuild:O.boolean().optional().default(!1).describe("Force rebuild the co-change matrix"),maxResults:O.number().optional().default(10).describe("Max results (default 10)")},S("prjct_cochange",async e=>{let r=await x(e.projectPath),s=e.rebuild?null:Ae(r);s||(s=await kn(e.projectPath,r));let i=Pe(e.seedFiles,s).slice(0,e.maxResults);if(i.length===0)return{content:[{type:"text",text:"No co-change partners found."}]};let o=["## Co-Change Partners",`Seeds: ${e.seedFiles.join(", ")}`,`Commits analyzed: ${s.commitsAnalyzed}`,""];for(let a of i)o.push(`- ${a.path} (similarity: ${Math.round(a.score*100)}%)`);return{content:[{type:"text",text:o.join(`
|
|
625
|
+
`)}]}})),t.tool("prjct_related_context","Combined: import neighbors + co-change partners for seed files",{projectPath:O.string().describe("Project directory path"),seedFiles:O.array(O.string()).describe("Seed files to find related context for"),maxResults:O.number().optional().default(15).describe("Max results (default 15)")},S("prjct_related_context",async e=>{let r=await x(e.projectPath),s=wt(r),i=s?gn(e.seedFiles,s):[],o=Ae(r),a=o?Pe(e.seedFiles,o):[],u=new Map;for(let p of i)u.set(p.path,{importScore:p.score,cochangeScore:0});for(let p of a){let g=u.get(p.path);g?g.cochangeScore=p.score:u.set(p.path,{importScore:0,cochangeScore:p.score})}let l=Array.from(u.entries()).map(([p,g])=>({path:p,combined:g.importScore*.6+g.cochangeScore*.4,importScore:g.importScore,cochangeScore:g.cochangeScore})).sort((p,g)=>g.combined-p.combined).slice(0,e.maxResults);if(l.length===0)return{content:[{type:"text",text:"No related files found. Run `prjct sync` to build indexes."}]};let d=["## Related Context",`Seeds: ${e.seedFiles.join(", ")}`,""];for(let p of l){let g=[];p.importScore>0&&g.push(`import: ${p.importScore.toFixed(2)}`),p.cochangeScore>0&&g.push(`cochange: ${Math.round(p.cochangeScore*100)}%`),d.push(`- ${p.path} (${g.join(", ")})`)}return{content:[{type:"text",text:d.join(`
|
|
626
|
+
`)}]}}))}c(Pn,"registerCodeIntelTools");import{z as st}from"zod";Gt();N();var vt={idle:{transitions:["task"],prompt:"prjct task <description> Start working",description:"No active task"},working:{transitions:["done","pause"],prompt:"prjct status done Complete task | prjct status paused Switch context",description:"Task in progress"},paused:{transitions:["resume","task","ship"],prompt:"prjct status active Continue | prjct task <new> Start different | prjct ship Ship directly",description:"Task paused"},completed:{transitions:["ship","task","pause","reopen"],prompt:"prjct ship Ship it | prjct task <next> Start next | prjct status active Reopen",description:"Task completed"},shipped:{transitions:["task"],prompt:"prjct task <description> Start new task",description:"Feature shipped"}},je=class{static{c(this,"WorkflowStateMachine")}getCurrentState(t,e){let r=null;if(e&&t?.activeTasks?.length&&(r=t.activeTasks.find(i=>i.workspaceId===e)),r||(r=t?.currentTask),!r)return(t?.pausedTasks?.length||0)>0||t?.previousTask?.status==="paused"?"paused":"idle";switch((typeof r.status=="string"?r.status:"").toLowerCase()){case"in_progress":case"working":return"working";case"paused":return"paused";case"completed":case"done":return"completed";case"shipped":return"shipped";default:return r?"working":"idle"}}canTransition(t,e){if(vt[t].transitions.includes(e))return{valid:!0};let s=this.formatNextSteps(t).join(" | ");return{valid:!1,error:`Cannot transition to '${e}' from '${t}' state`,suggestion:`Valid next steps: ${s}`}}getNextState(t,e){switch(e){case"task":return"working";case"done":return"completed";case"pause":return"paused";case"resume":return"working";case"ship":return"shipped";case"reopen":return"working";default:return t}}getStateInfo(t){return vt[t]}getPrompt(t){return vt[t].prompt}getValidCommands(t){return vt[t].transitions}formatNextSteps(t){return vt[t].transitions.map(r=>{switch(r){case"task":return"prjct task <desc> Start new task";case"done":return"prjct status done Complete current task";case"pause":return"prjct status paused Pause and switch context";case"resume":return"prjct status active Continue paused task";case"ship":return"prjct ship Ship the feature";case"reopen":return"prjct status active Reopen completed task";default:return`prjct ${r}`}})}},Fe=new je;Rt();N();Jt();async function Hn(n,t,e){let r=await n.read(t);if(!r.currentTask)return null;n.validateTransition(r,"pause");let s={...r.currentTask,status:"paused",pausedAt:f(),pauseReason:e},i=n.getPausedTasksFromState(r),o=[s,...i].slice(0,n.maxPausedTasks);return await n.update(t,a=>({...a,currentTask:null,previousTask:null,pausedTasks:o,lastUpdated:f()})),await n.publish(t,"task.paused",{taskId:s.id,description:s.description,pausedAt:s.pausedAt,reason:e,pausedCount:o.length}),s}c(Hn,"pauseTask");async function qn(n,t,e){let r=await n.read(t),s=n.getPausedTasksFromState(r);if(s.length===0)return null;n.validateTransition(r,"resume");let i=0;if(e&&(i=s.findIndex(T=>T.id===e),i===-1))return null;let o=s[i],a=s.filter((T,L)=>L!==i),{status:u,pausedAt:l,pauseReason:d,...p}=o,g={...p,startedAt:f(),sessionId:o.sessionId??H()};return await n.update(t,T=>({...T,currentTask:g,previousTask:null,pausedTasks:a,lastUpdated:f()})),await n.publish(t,"task.resumed",{taskId:g.id,description:g.description,resumedAt:g.startedAt,remainingPaused:a.length}),g}c(qn,"resumeTask");async function Gn(n,t){let e=await n.read(t),r=n.getPausedTasksFromState(e),s=Date.now()-n.stalenessThresholdDays*24*60*60*1e3;return r.filter(i=>new Date(i.pausedAt).getTime()<s)}c(Gn,"getStalePausedTasks");async function Yn(n,t){let e=await n.read(t),r=n.getPausedTasksFromState(e),s=Date.now()-n.stalenessThresholdDays*24*60*60*1e3,i=r.filter(a=>new Date(a.pausedAt).getTime()<s),o=r.filter(a=>new Date(a.pausedAt).getTime()>=s);if(i.length===0)return[];lt.archiveMany(t,i.map(a=>({entityType:"paused_task",entityId:a.id,entityData:a,summary:a.description,reason:"staleness"}))),await n.update(t,a=>({...a,pausedTasks:o,previousTask:null,lastUpdated:f()}));for(let a of i)await n.publish(t,"task.archived",{taskId:a.id,description:a.description,pausedAt:a.pausedAt,reason:"staleness"});return i}c(Yn,"archiveStalePausedTasks");N();async function Jn(n,t){await n.update(t,()=>({currentTask:null,previousTask:null,pausedTasks:[],activeTasks:[],lastUpdated:f()}))}c(Jn,"clearTask");async function zn(n,t){let e=await n.read(t),r=n.getPausedTasksFromState(e);return e.currentTask!==null||r.length>0}c(zn,"hasTask");async function Kn(n,t){let e=await n.read(t);return n.getPausedTasksFromState(e)[0]||null}c(Kn,"getPausedTask");async function Vn(n,t){let e=await n.read(t);return n.getPausedTasksFromState(e)}c(Vn,"getAllPausedTasks");async function Ye(n,t){let e=await n.read(t);return n.getTaskHistoryFromState(e)}c(Ye,"getTaskHistory");async function Qn(n,t){let e=await n.read(t);return n.getTaskHistoryFromState(e)[0]||null}c(Qn,"getMostRecentTask");async function Zn(n,t,e){let r=await n.read(t);return n.getTaskHistoryFromState(r).filter(i=>i.classification===e)}c(Zn,"getTaskHistoryByType");async function ts(n,t){let r=(await Ye(n,t)).filter(g=>g.feedback),s=[],i=[],o=[],a=[];for(let g of r){let T=g.feedback;Array.isArray(T.stackConfirmed)&&s.push(...T.stackConfirmed),Array.isArray(T.patternsDiscovered)&&i.push(...T.patternsDiscovered),Array.isArray(T.agentAccuracy)&&o.push(...T.agentAccuracy),Array.isArray(T.issuesEncountered)&&a.push(...T.issuesEncountered)}let u=[...new Set(s)],l=[...new Set(i)],d=new Map;for(let g of a)d.set(g,(d.get(g)||0)+1);let p=[...d.entries()].filter(([g,T])=>T>=2).map(([g])=>g);return{stackConfirmed:u,patternsDiscovered:l,agentAccuracy:o,issuesEncountered:[...new Set(a)],knownGotchas:p}}c(ts,"getAggregatedFeedback");Gt();N();async function es(n,t,e){let r=await n.read(t);if(!r.currentTask)return;let s=e.map((i,o)=>({...i,status:o===0?"in_progress":"pending",startedAt:o===0?f():void 0,dependsOn:i.dependsOn||[]}));await n.update(t,i=>({...i,currentTask:{...i.currentTask,subtasks:s,currentSubtaskIndex:0,subtaskProgress:{completed:0,total:s.length,percentage:0}},lastUpdated:f()})),await n.publish(t,"subtasks.created",{taskId:r.currentTask.id,subtaskCount:s.length,subtasks:s.map(i=>({id:i.id,description:i.description,domain:i.domain}))})}c(es,"createSubtasks");async function rs(n,t,e){let r=Nn.safeParse(e);if(!r.success){let L=r.error.issues.map(z=>`${z.path.join(".")}: ${z.message}`);throw new Error(`Subtask completion requires handoff data:
|
|
627
|
+
${L.join(`
|
|
628
|
+
`)}`)}let{output:s,summary:i}=r.data,o=await n.read(t);if(!o.currentTask?.subtasks)return null;let a=o.currentTask.currentSubtaskIndex||0,u=o.currentTask.subtasks[a];if(!u)return null;let l=[...o.currentTask.subtasks];l[a]={...u,status:"completed",completedAt:f(),output:s,summary:i};let d=l.filter(L=>L.status==="completed").length,p=l.length,g=Math.round(d/p*100),T=a+1;return T<l.length&&(l[T]={...l[T],status:"in_progress",startedAt:f()}),await n.update(t,L=>({...L,currentTask:{...L.currentTask,subtasks:l,currentSubtaskIndex:T<p?T:a,subtaskProgress:{completed:d,total:p,percentage:g}},lastUpdated:f()})),await n.publish(t,"subtask.completed",{taskId:o.currentTask.id,subtaskId:u.id,description:u.description,output:s,handoff:i.outputForNextAgent,filesChanged:i.filesChanged.length,progress:{completed:d,total:p,percentage:g}}),T<p?l[T]:null}c(rs,"completeSubtask");async function ns(n,t){let e=await n.read(t);if(!e.currentTask?.subtasks)return null;let r=e.currentTask.currentSubtaskIndex||0;return e.currentTask.subtasks[r]||null}c(ns,"getCurrentSubtask");async function ss(n,t){let e=await n.read(t);if(!e.currentTask?.subtasks)return null;let r=(e.currentTask.currentSubtaskIndex||0)+1;return e.currentTask.subtasks[r]||null}c(ss,"getNextSubtask");async function Je(n,t){let e=await n.read(t);if(!e.currentTask?.subtasks)return null;let r=(e.currentTask.currentSubtaskIndex||0)-1;return r<0?null:e.currentTask.subtasks[r]||null}c(Je,"getPreviousSubtask");async function is(n,t){let e=await Je(n,t);return e?.summary?.outputForNextAgent?{fromSubtask:e.description,outputForNextAgent:e.summary.outputForNextAgent,filesChanged:e.summary.filesChanged,whatWasDone:e.summary.whatWasDone}:null}c(is,"getPreviousHandoff");async function os(n,t){return(await n.read(t)).currentTask?.subtasks||[]}c(os,"getSubtasks");async function as(n,t){return(await n.read(t)).currentTask?.subtaskProgress||null}c(as,"getSubtaskProgress");async function cs(n,t){return((await n.read(t)).currentTask?.subtasks?.length||0)>0}c(cs,"hasSubtasks");async function us(n,t){let e=await n.read(t);return e.currentTask?.subtasks?e.currentTask.subtasks.every(r=>r.status==="completed"||r.status==="failed"||r.status==="skipped"):!0}c(us,"areAllSubtasksComplete");async function ls(n,t,e){let r=await n.read(t);if(!r.currentTask?.subtasks)return null;let s=r.currentTask.currentSubtaskIndex||0,i=r.currentTask.subtasks[s];if(!i)return null;let o=[...r.currentTask.subtasks];o[s]={...i,status:"failed",completedAt:f(),output:`Failed: ${e}`};let a=s+1,u=o.length;a<u&&(o[a]={...o[a],status:"in_progress",startedAt:f()});let l=o.filter(p=>p.status==="completed"||p.status==="failed"||p.status==="skipped").length,d=Math.round(l/u*100);return await n.update(t,p=>({...p,currentTask:{...p.currentTask,subtasks:o,currentSubtaskIndex:a<u?a:s,subtaskProgress:{completed:l,total:u,percentage:d}},lastUpdated:f()})),await n.publish(t,"subtask.failed",{taskId:r.currentTask.id,subtaskId:i.id,description:i.description,error:e}),a<u?o[a]:null}c(ls,"failSubtask");async function ps(n,t,e){let r=await n.read(t);if(!r.currentTask?.subtasks)return null;let s=r.currentTask.currentSubtaskIndex||0,i=r.currentTask.subtasks[s];if(!i)return null;let o=[...r.currentTask.subtasks];o[s]={...i,status:"skipped",completedAt:f(),output:`Skipped: ${e}`,skipReason:e};let a=s+1,u=o.length;a<u&&(o[a]={...o[a],status:"in_progress",startedAt:f()});let l=o.filter(p=>p.status==="completed"||p.status==="failed"||p.status==="skipped").length,d=Math.round(l/u*100);return await n.update(t,p=>({...p,currentTask:{...p.currentTask,subtasks:o,currentSubtaskIndex:a<u?a:s,subtaskProgress:{completed:l,total:u,percentage:d}},lastUpdated:f()})),await n.publish(t,"subtask.skipped",{taskId:r.currentTask.id,subtaskId:i.id,description:i.description,reason:e}),a<u?o[a]:null}c(ps,"skipSubtask");async function ds(n,t,e){let r=await n.read(t);if(!r.currentTask?.subtasks)return null;let s=r.currentTask.currentSubtaskIndex||0,i=r.currentTask.subtasks[s];if(!i)return null;let o=[...r.currentTask.subtasks];o[s]={...i,status:"blocked",output:`Blocked: ${e}`,blockReason:e};let a=s+1,u=o.length;return a<u&&(o[a]={...o[a],status:"in_progress",startedAt:f()}),await n.update(t,l=>({...l,currentTask:{...l.currentTask,subtasks:o,currentSubtaskIndex:a<u?a:s},lastUpdated:f()})),await n.publish(t,"subtask.blocked",{taskId:r.currentTask.id,subtaskId:i.id,description:i.description,blocker:e}),a<u?o[a]:null}c(ds,"blockSubtask");N();async function ms(n,t,e,r){let s={...e,workspaceId:r,startedAt:f()};return await n.update(t,i=>({...i,activeTasks:[...i.activeTasks||[],s],lastUpdated:f()})),await n.publish(t,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId,workspaceId:r}),s}c(ms,"startTaskInWorkspace");async function gs(n,t,e){return((await n.read(t)).activeTasks||[]).find(s=>s.workspaceId===e)??null}c(gs,"getCurrentTaskForWorkspace");async function fs(n,t,e,r){let s=await n.read(t),o=(s.activeTasks||[]).find(p=>p.workspaceId===e);if(!o)return null;let a=f(),u=n.createTaskHistoryEntry(o,a,r),l=n.getTaskHistoryFromState(s),d=[u,...l].slice(0,n.maxTaskHistory);return await n.update(t,p=>({...p,activeTasks:(p.activeTasks||[]).filter(g=>g.workspaceId!==e),taskHistory:d,lastUpdated:a})),await n.publish(t,"task.completed",{taskId:o.id,description:o.description,startedAt:o.startedAt,completedAt:a,workspaceId:e}),o}c(fs,"completeTaskInWorkspace");async function hs(n,t){return(await n.read(t)).activeTasks||[]}c(hs,"getActiveTasks");async function ys(n,t){return((await n.read(t)).activeTasks||[]).length}c(ys,"getActiveTaskCount");async function Ts(n,t,e,r){let i=(await n.read(t)).activeTasks||[],o=i.findIndex(u=>u.workspaceId===e);if(o===-1)return null;let a={...i[o],...r,workspaceId:e};return await n.update(t,u=>{let l=[...u.activeTasks||[]];return l[o]=a,{...u,activeTasks:l,lastUpdated:f()}}),a}c(Ts,"updateWorkspaceTask");async function Es(n,t,e,r){let s=await n.read(t);if(!s.currentTask)return null;let i=(s.currentTask.tokensIn||0)+e,o=(s.currentTask.tokensOut||0)+r;return await n.update(t,a=>({...a,currentTask:{...a.currentTask,tokensIn:i,tokensOut:o},lastUpdated:f()})),{tokensIn:i,tokensOut:o}}c(Es,"addTokens");ze();var Ke=class extends pt{static{c(this,"StateStorage")}constructor(){super("state.json",Dn)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],activeTasks:[],lastUpdated:""}}getEventType(t){return`state.${t}d`}validateTransition(t,e){let r=Fe.getCurrentState(t),s=Fe.canTransition(r,e);if(!s.valid)throw new Error(`${s.error}. ${s.suggestion||""}`.trim())}async getCurrentTask(t){return(await this.read(t)).currentTask}async getPausedTasks(t){let e=await this.read(t);return this.getPausedTasksFromState(e)}async startTask(t,e){let r=await this.read(t);this.validateTransition(r,"task");let s={...e,startedAt:f()};return await this.update(t,i=>({...i,currentTask:s,lastUpdated:f()})),await this.publishEvent(t,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId}),s}async updateCurrentTask(t,e){let r=await this.read(t);if(!r.currentTask)return null;let s={...r.currentTask,...e};return await this.update(t,i=>({...i,currentTask:s,lastUpdated:f()})),s}async completeTask(t,e){let r=await this.read(t),s=r.currentTask;if(!s)return null;this.validateTransition(r,"done");let i=f(),o=this.createTaskHistoryEntry(s,i,e),a=this.getTaskHistoryFromState(r),u=[o,...a].slice(0,this.maxTaskHistory);return await this.update(t,l=>({...l,currentTask:null,previousTask:null,taskHistory:u,lastUpdated:i})),await this.publishEvent(t,"task.completed",{taskId:s.id,description:s.description,startedAt:s.startedAt,completedAt:i}),s}createTaskHistoryEntry(t,e,r){let s=(t.subtasks||[]).filter(a=>a.status==="completed"&&a.summary).map(a=>a.summary),i=s.length>0?s.map(a=>a.title).join(", "):"Task completed",o={taskId:t.id,title:t.parentDescription||t.description,classification:t.type||"improvement",startedAt:t.startedAt,completedAt:e,subtaskCount:t.subtasks?.length||0,subtaskSummaries:s,outcome:i,branchName:t.branch||"unknown",linearId:t.linearId,linearUuid:t.linearUuid,prUrl:t.prUrl};return r&&(o.feedback=r),t.tokensIn&&(o.tokensIn=t.tokensIn),t.tokensOut&&(o.tokensOut=t.tokensOut),o}maxPausedTasks=5;maxTaskHistory=20;stalenessThresholdDays=30;lifecycleBackend(){return{read:this.read.bind(this),update:this.update.bind(this),publish:this.publishEvent.bind(this),validateTransition:this.validateTransition.bind(this),getPausedTasksFromState:this.getPausedTasksFromState.bind(this),maxPausedTasks:this.maxPausedTasks,stalenessThresholdDays:this.stalenessThresholdDays}}async pauseTask(t,e){return Hn(this.lifecycleBackend(),t,e)}async resumeTask(t,e){return qn(this.lifecycleBackend(),t,e)}getPausedTasksFromState(t){return Array.isArray(t.pausedTasks)&&t.pausedTasks.length>0?t.pausedTasks:t.previousTask?[t.previousTask]:[]}getTaskHistoryFromState(t){return t.taskHistory||[]}async getStalePausedTasks(t){return Gn(this.lifecycleBackend(),t)}async archiveStalePausedTasks(t){return Yn(this.lifecycleBackend(),t)}queryBackend(){return{read:this.read.bind(this),update:this.update.bind(this),getPausedTasksFromState:this.getPausedTasksFromState.bind(this),getTaskHistoryFromState:this.getTaskHistoryFromState.bind(this)}}async clearTask(t){return Jn(this.queryBackend(),t)}async hasTask(t){return zn(this.queryBackend(),t)}async getPausedTask(t){return Kn(this.queryBackend(),t)}async getAllPausedTasks(t){return Vn(this.queryBackend(),t)}async getTaskHistory(t){return Ye(this.queryBackend(),t)}async getMostRecentTask(t){return Qn(this.queryBackend(),t)}async getTaskHistoryByType(t,e){return Zn(this.queryBackend(),t,e)}async getAggregatedFeedback(t){return ts(this.queryBackend(),t)}workspaceBackend(){return{read:this.read.bind(this),update:this.update.bind(this),publish:this.publishEvent.bind(this),createTaskHistoryEntry:this.createTaskHistoryEntry.bind(this),getTaskHistoryFromState:this.getTaskHistoryFromState.bind(this),maxTaskHistory:this.maxTaskHistory}}async startTaskInWorkspace(t,e,r){return ms(this.workspaceBackend(),t,e,r)}async getCurrentTaskForWorkspace(t,e){return gs(this.workspaceBackend(),t,e)}async completeTaskInWorkspace(t,e,r){return fs(this.workspaceBackend(),t,e,r)}async getActiveTasks(t){return hs(this.workspaceBackend(),t)}async getActiveTaskCount(t){return ys(this.workspaceBackend(),t)}async updateWorkspaceTask(t,e,r){return Ts(this.workspaceBackend(),t,e,r)}async addTokens(t,e,r){return Es(this.workspaceBackend(),t,e,r)}subtaskBackend(){return{read:this.read.bind(this),update:this.update.bind(this),publish:this.publishEvent.bind(this)}}async createSubtasks(t,e){return es(this.subtaskBackend(),t,e)}async completeSubtask(t,e){return rs(this.subtaskBackend(),t,e)}async getCurrentSubtask(t){return ns(this.subtaskBackend(),t)}async getNextSubtask(t){return ss(this.subtaskBackend(),t)}async getPreviousSubtask(t){return Je(this.subtaskBackend(),t)}async getPreviousHandoff(t){return is(this.subtaskBackend(),t)}async getSubtasks(t){return os(this.subtaskBackend(),t)}async getSubtaskProgress(t){return as(this.subtaskBackend(),t)}async hasSubtasks(t){return cs(this.subtaskBackend(),t)}async areAllSubtasksComplete(t){return us(this.subtaskBackend(),t)}async failSubtask(t,e){return ls(this.subtaskBackend(),t,e)}async skipSubtask(t,e){return ps(this.subtaskBackend(),t,e)}async blockSubtask(t,e){return ds(this.subtaskBackend(),t,e)}},dt=new Ke;Ve();tt();import Vo from"node:fs/promises";import gt from"node:path";var Jo={"claude-opus-4.5":{input:.005,output:.025},"claude-sonnet-4.5":{input:.003,output:.015},"claude-haiku-4.5":{input:.001,output:.005},"claude-opus-4":{input:.015,output:.075},"claude-opus-4-6":{input:.015,output:.075},"gpt-4o":{input:.0025,output:.01},"gpt-4-turbo":{input:.01,output:.03},"gpt-4o-mini":{input:15e-5,output:6e-4},"gemini-1.5-pro":{input:.00125,output:.005},"gemini-1.5-flash":{input:75e-6,output:3e-4}},zo="claude-sonnet-4.5";function Qe(n){return!n||n.length===0?0:Math.ceil(n.length/4)}c(Qe,"countTokens");var As=["claude-sonnet-4.5","claude-opus-4.5","claude-opus-4-6","gpt-4o","gemini-1.5-pro"];function Ps(n,t){let e=Jo[t],r=n/1e3*e.input,s=n/1e3*e.output*.3;return{inputSaved:r,outputPotential:s,total:r+s}}c(Ps,"calculateModelCost");function Ko(n){return n<.001?"<$0.01":n<.01?`$${n.toFixed(3)}`:`$${n.toFixed(2)}`}c(Ko,"formatCostSaved");function Ns(n,t){let e=Qe(n),r=Qe(t),s=Math.max(0,e-r),i=e>0?(e-r)/e:0,o=Ps(s,zo),a=As.map(u=>({model:u,...Ps(s,u)}));return{tokens:{original:e,filtered:r,saved:s},compression:Math.max(0,Math.min(1,i)),cost:{saved:o.total,formatted:Ko(o.total),byModel:a}}}c(Ns,"measureCompression");function Zt(n){let t=Qe(n);return{tokens:{original:t,filtered:t,saved:0},compression:0,cost:{saved:0,formatted:"$0.00",byModel:As.map(e=>({model:e,inputSaved:0,outputPotential:0,total:0}))}}}c(Zt,"noCompression");var Qo={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".go":"go",".rs":"rust",".java":"java",".cs":"csharp",".php":"php",".rb":"ruby"},Is=[{type:"function",pattern:/^export\s+(?:async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)\s*(?::\s*([^{;]+))?/gm,nameIndex:1,exported:!0},{type:"function",pattern:/^export\s+const\s+(\w+)\s*(?::\s*[^=]+)?\s*=\s*(?:async\s+)?\([^)]*\)\s*(?::\s*[^=]+)?\s*=>/gm,nameIndex:1,exported:!0},{type:"function",pattern:/^(?:async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)\s*(?::\s*([^{;]+))?/gm,nameIndex:1},{type:"function",pattern:/^const\s+(\w+)\s*(?::\s*[^=]+)?\s*=\s*(?:async\s+)?\([^)]*\)\s*(?::\s*[^=]+)?\s*=>/gm,nameIndex:1},{type:"interface",pattern:/^export\s+interface\s+(\w+)(?:<[^>]+>)?\s*(?:extends\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"interface",pattern:/^interface\s+(\w+)(?:<[^>]+>)?\s*(?:extends\s+[^{]+)?\s*\{/gm,nameIndex:1},{type:"type",pattern:/^export\s+type\s+(\w+)(?:<[^>]+>)?\s*=/gm,nameIndex:1,exported:!0},{type:"type",pattern:/^type\s+(\w+)(?:<[^>]+>)?\s*=/gm,nameIndex:1},{type:"class",pattern:/^export\s+(?:abstract\s+)?class\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+[^{]+)?(?:\s+implements\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"class",pattern:/^(?:abstract\s+)?class\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+[^{]+)?(?:\s+implements\s+[^{]+)?\s*\{/gm,nameIndex:1},{type:"enum",pattern:/^export\s+enum\s+(\w+)\s*\{/gm,nameIndex:1,exported:!0},{type:"enum",pattern:/^enum\s+(\w+)\s*\{/gm,nameIndex:1},{type:"const",pattern:/^export\s+const\s+(\w+)\s*(?::\s*([^=]+))?\s*=/gm,nameIndex:1,exported:!0}],Zo=[{type:"function",pattern:/^def\s+(\w+)\s*\(([^)]*)\)\s*(?:->\s*([^:]+))?\s*:/gm,nameIndex:1},{type:"function",pattern:/^async\s+def\s+(\w+)\s*\(([^)]*)\)\s*(?:->\s*([^:]+))?\s*:/gm,nameIndex:1},{type:"class",pattern:/^class\s+(\w+)(?:\(([^)]*)\))?\s*:/gm,nameIndex:1}],ta=[{type:"function",pattern:/^func\s+(\w+)\s*\(([^)]*)\)\s*(?:\(([^)]*)\)|([^\s{]+))?\s*\{/gm,nameIndex:1},{type:"method",pattern:/^func\s+\([^)]+\)\s+(\w+)\s*\(([^)]*)\)\s*(?:\(([^)]*)\)|([^\s{]+))?\s*\{/gm,nameIndex:1},{type:"type",pattern:/^type\s+(\w+)\s+(?:struct|interface)\s*\{/gm,nameIndex:1}],ea=[{type:"function",pattern:/^pub\s+(?:async\s+)?fn\s+(\w+)(?:<[^>]+>)?\s*\(([^)]*)\)\s*(?:->\s*([^{]+))?\s*\{/gm,nameIndex:1,exported:!0},{type:"function",pattern:/^(?:async\s+)?fn\s+(\w+)(?:<[^>]+>)?\s*\(([^)]*)\)\s*(?:->\s*([^{]+))?\s*\{/gm,nameIndex:1},{type:"class",pattern:/^pub\s+struct\s+(\w+)(?:<[^>]+>)?\s*(?:\{|;)/gm,nameIndex:1,exported:!0},{type:"class",pattern:/^struct\s+(\w+)(?:<[^>]+>)?\s*(?:\{|;)/gm,nameIndex:1},{type:"interface",pattern:/^pub\s+trait\s+(\w+)(?:<[^>]+>)?\s*(?:\{|:)/gm,nameIndex:1,exported:!0},{type:"interface",pattern:/^trait\s+(\w+)(?:<[^>]+>)?\s*(?:\{|:)/gm,nameIndex:1},{type:"enum",pattern:/^pub\s+enum\s+(\w+)(?:<[^>]+>)?\s*\{/gm,nameIndex:1,exported:!0},{type:"enum",pattern:/^enum\s+(\w+)(?:<[^>]+>)?\s*\{/gm,nameIndex:1}],Cs=[{type:"class",pattern:/^(?:public\s+)?(?:abstract\s+)?(?:final\s+)?class\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+\w+)?(?:\s+implements\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"interface",pattern:/^(?:public\s+)?interface\s+(\w+)(?:<[^>]+>)?(?:\s+extends\s+[^{]+)?\s*\{/gm,nameIndex:1,exported:!0},{type:"method",pattern:/^\s+(?:public|private|protected)?\s*(?:static\s+)?(?:final\s+)?(?:synchronized\s+)?(?:<[^>]+>\s+)?(\w+(?:<[^>]+>)?)\s+(\w+)\s*\([^)]*\)\s*(?:throws\s+[^{]+)?\s*\{/gm,nameIndex:2}],ra={typescript:Is,javascript:Is,python:Zo,go:ta,rust:ea,java:Cs,csharp:Cs,php:[],ruby:[],unknown:[]};async function Ls(n,t=process.cwd()){let e=gt.isAbsolute(n)?n:gt.join(t,n),r=gt.resolve(t),s=gt.resolve(e);if(!s.startsWith(r+gt.sep)&&s!==r)return{file:n,language:"unknown",signatures:[],fallback:!0,fallbackReason:"Path traversal denied: file is outside project directory",metrics:Zt("")};let i;try{i=await Vo.readFile(e,"utf-8")}catch(p){if(M(p))return{file:n,language:"unknown",signatures:[],fallback:!0,fallbackReason:"File not found",metrics:Zt("")};throw p}let o=gt.extname(n).toLowerCase(),a=Qo[o]||"unknown",u=ra[a];if(!u||u.length===0)return{file:n,language:a,signatures:[],fallback:!0,fallbackReason:`No extraction patterns for ${a}`,metrics:Zt(i)};let l=na(i,u),d=l.map(p=>`${p.exported?"export ":""}${p.type} ${p.name}: ${p.signature}`).join(`
|
|
629
|
+
`);return{file:n,language:a,signatures:l,fallback:!1,metrics:Ns(i,d)}}c(Ls,"extractSignatures");function na(n,t){let e=[],r=n.split(`
|
|
630
|
+
`),s=new Set;for(let i of t){i.pattern.lastIndex=0;let o;for(;(o=i.pattern.exec(n))!==null;){let a=o[i.nameIndex];if(!a)continue;let u=`${i.type}:${a}`;if(s.has(u))continue;s.add(u);let l=o.index,d=n.substring(0,l).split(`
|
|
631
|
+
`).length,p=o[0].trim(),g;if(d>1){let T=r[d-2]?.trim();(T?.startsWith("/**")||T?.startsWith("///")||T?.startsWith("#"))&&(g=T)}e.push({type:i.type,name:a,signature:sa(p),exported:i.exported||!1,line:d,docstring:g})}}return e.sort((i,o)=>i.line-o.line)}c(na,"extractFromContent");function sa(n){return n.replace(/\{$/,"").replace(/\s+/g," ").trim()}c(sa,"cleanSignature");function Ds(n){let t=n;t.tool("prjct_relevant_files","BM25-ranked files relevant to a query",{projectPath:st.string().describe("Project directory path"),query:st.string().describe("Task or query to find relevant files for"),maxFiles:st.number().optional().default(10).describe("Max files to return")},S("prjct_relevant_files",async e=>{let r=await Qt(e.query,e.projectPath,{maxFiles:e.maxFiles,minScore:.1});if(r.files.length===0)return{content:[{type:"text",text:"No relevant files found."}]};let s=r.files.map(o=>`- \`${o.path}\` (score: ${Math.round(o.score*100)}%) \u2014 ${o.reasons.join(", ")}`);return{content:[{type:"text",text:`## Relevant Files (${r.files.length}/${r.metrics.filesScanned} scanned)
|
|
632
|
+
|
|
633
|
+
${s.join(`
|
|
634
|
+
`)}`}]}})),t.tool("prjct_signatures","Code signatures from a file (90% token reduction vs full content)",{projectPath:st.string().describe("Project directory path"),filePath:st.string().describe("Relative file path to extract signatures from")},S("prjct_signatures",async e=>{let r=await Ls(e.filePath,e.projectPath);if(r.signatures.length===0)return{content:[{type:"text",text:r.fallback?`No signatures extracted: ${r.fallbackReason}`:"No signatures found."}]};let s=r.signatures.map(a=>`${a.exported?"export ":""}${a.type} ${a.name}: ${a.signature}${a.docstring?` // ${a.docstring}`:""}`),i=r.metrics?.compression?` (${Math.round(r.metrics.compression*100)}% reduction)`:"";return{content:[{type:"text",text:`## ${r.file} (${r.language})
|
|
635
635
|
\`\`\`
|
|
636
|
-
${
|
|
636
|
+
${s.join(`
|
|
637
637
|
`)}
|
|
638
|
-
\`\`\`${i}`}]}})),t.tool("prjct_history","Recent completed tasks with outcomes",{projectPath:st.string().describe("Project directory path"),limit:st.number().optional().default(10).describe("Max results")},S("prjct_history",async e=>{let r=await x(e.projectPath),
|
|
638
|
+
\`\`\`${i}`}]}})),t.tool("prjct_history","Recent completed tasks with outcomes",{projectPath:st.string().describe("Project directory path"),limit:st.number().optional().default(10).describe("Max results")},S("prjct_history",async e=>{let r=await x(e.projectPath),s=await dt.getTaskHistory(r);if(s.length===0)return{content:[{type:"text",text:"No task history."}]};let o=s.slice(-e.limit).reverse().map(u=>{let l=[`- **${u.title}**`];return u.completedAt&&l.push(`completed: ${u.completedAt}`),u.classification&&l.push(`type: ${u.classification}`),l.join(" | ")});return{content:[{type:"text",text:`## Task History (${s.length} total)
|
|
639
639
|
|
|
640
640
|
${o.join(`
|
|
641
|
-
`)}`}]}}))}c(
|
|
642
|
-
**${
|
|
641
|
+
`)}`}]}}))}c(Ds,"registerFileTools");ht();tr();import{z as v}from"zod";var Ks=[{name:"sk-\u2026 token",re:/\bsk-[A-Za-z0-9_-]{16,}/},{name:"GitHub PAT",re:/\bghp_[A-Za-z0-9]{30,}/},{name:"GitHub server PAT",re:/\bghs_[A-Za-z0-9]{30,}/},{name:"AWS access key",re:/\bAKIA[0-9A-Z]{16}\b/},{name:"Slack token",re:/\bxox[abps]-[A-Za-z0-9-]{10,}/},{name:"bearer JWT-ish",re:/\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}],ad=Ks.map(n=>n.name);function Vs(n){let t=[];for(let{name:e,re:r}of Ks)r.test(n)&&t.push(e);return t}c(Vs,"scanForSecrets");var Qs=`Base types: ${Js.join(", ")}. Any lowercase identifier is accepted (e.g. "recipe", "okr").`;function Zs(n){let t=n;t.tool("prjct_mem_save",`Save a memory entry. ${Qs} Secret-like content is refused unless force=true.`,{projectPath:v.string().describe("Project directory path"),type:v.string().describe("Memory type (fact/decision/learning/... or user-defined)"),content:v.string().describe("The memory content. Freeform text."),tags:v.record(v.string(),v.string()).optional().describe('Key:value tags (e.g. {domain: "auth"})'),source:v.string().optional().describe("Task id this memory came from, if any"),force:v.boolean().optional().describe("Bypass the secret-like-content refusal. Default false.")},S("prjct_mem_save",async e=>{await x(e.projectPath);let r=e.type.toLowerCase().trim();if(!r||!/^[a-z][a-z0-9-]*$/.test(r))return{content:[{type:"text",text:`Invalid type '${e.type}'. Lowercase letters + dashes only. ${Qs}`}]};let s=Vs(e.content);if(s.length>0&&!e.force)return{content:[{type:"text",text:`Refused \u2014 content looks like a secret (${s.join(", ")}). Re-call with force=true if intentional.`}]};let i=Fs(e.content);return i.length>0&&!e.force?{content:[{type:"text",text:`Refused \u2014 content looks like prompt injection (${i.join(", ")}). Memory entries are inlined into LLM context. Re-call with force=true if intentional.`}]}:(await C.remember(e.projectPath,{type:r,content:e.content,tags:e.tags??{},source:e.source}),{content:[{type:"text",text:`Saved ${r}: ${e.content.slice(0,80)}`}]})})),t.tool("prjct_mem_list","Recall memory entries. Optional filters: topic (keyword across content + tag values), types, tags, limit.",{projectPath:v.string().describe("Project directory path"),topic:v.string().optional().describe("Keyword to match over content + tag values"),types:v.array(v.string()).optional().describe("Restrict to these types"),tags:v.record(v.string(),v.string()).optional().describe("Require exact match on these k:v pairs"),limit:v.number().optional().default(25).describe("Max entries (default 25)")},S("prjct_mem_list",async e=>{let r=await x(e.projectPath),s=C.recall(r,{topic:e.topic,types:e.types,tags:e.tags,limit:e.limit});return{content:[{type:"text",text:ft(s,{boundary:"llm"})}]}})),t.tool("prjct_mem_similar","Find memory entries similar to a free-text description. Keyword-based, best-effort.",{projectPath:v.string().describe("Project directory path"),description:v.string().describe("Free-text description to find similar memories for"),limit:v.number().optional().default(10).describe("Max results (default 10)")},S("prjct_mem_similar",async e=>{let r=await x(e.projectPath),s=C.similar(r,e.description,e.limit);return s.length===0?{content:[{type:"text",text:"No similar memories found."}]}:{content:[{type:"text",text:ft(s,{boundary:"llm"})}]}})),t.tool("prjct_guard","Anticipation: before editing a file, get the preventive memory recorded against it \u2014 gotchas, anti-patterns, recurring bugs only. Empty result means clear to edit. Pull this instead of guessing what might break.",{projectPath:v.string().describe("Project directory path"),file:v.string().describe("File to check (absolute or repo-relative)"),limit:v.number().optional().default(3).describe("Max preventive entries (default 3)")},S("prjct_guard",async e=>{let r=await x(e.projectPath),s=C.recallForFile(r,e.file,e.limit??3);return s.length===0?{content:[{type:"text",text:`No preventive memory for ${e.file.split("/").pop()??e.file} \u2014 clear to edit.`}]}:{content:[{type:"text",text:ft(s,{boundary:"llm"})}]}})),t.tool("prjct_mem_forget","Remove a memory entry by id. Ids are stable \u2014 pull them from `prjct_mem_list`.",{projectPath:v.string().describe("Project directory path"),id:v.string().describe('Memory id (e.g. "mem_42" or "ship_7")')},S("prjct_mem_forget",async e=>{let r=await x(e.projectPath);return{content:[{type:"text",text:C.forget(r,e.id)?`\u2713 forgot ${e.id} \u2014 removed from recall, search, and embeddings.`:`_No memory entry with id ${e.id} (already gone, or not a remember entry)._`}]}}))}c(Zs,"registerMemoryTools");ht();import{z as cr}from"zod";N();j();var ir=class{static{c(this,"LLMAnalysisStorage")}save(t,e){let r=k.getDb(t),s=f();r.transaction(()=>{r.prepare("UPDATE llm_analysis SET status = 'superseded', superseded_at = ? WHERE status = 'active'").run(s),r.prepare("INSERT INTO llm_analysis (commit_hash, status, analysis, analyzed_at) VALUES (?, ?, ?, ?)").run(e.commitHash??null,"active",JSON.stringify(e),e.analyzedAt)})()}getActive(t){let e=k.get(t,"SELECT analysis FROM llm_analysis WHERE status = 'active' LIMIT 1");return e?JSON.parse(e.analysis):null}getActiveSummary(t){let e=this.getActive(t);return e?{commitHash:e.commitHash,architectureStyle:e.architecture.style,patternCount:e.patterns.length,antiPatternCount:e.antiPatterns.length,analyzedAt:e.analyzedAt}:null}isCurrent(t,e){return e?k.get(t,"SELECT commit_hash FROM llm_analysis WHERE status = 'active' LIMIT 1")?.commit_hash===e:!1}getAllFull(t){return k.query(t,"SELECT id, commit_hash, status, analyzed_at, superseded_at, analysis FROM llm_analysis ORDER BY id DESC").map(r=>({id:r.id,status:r.status,commitHash:r.commit_hash,analyzedAt:r.analyzed_at,supersededAt:r.superseded_at,analysis:JSON.parse(r.analysis)}))}getHistory(t,e=10){return k.query(t,"SELECT id, commit_hash, status, analyzed_at, analysis FROM llm_analysis ORDER BY id DESC LIMIT ?",e).map(s=>{let i=JSON.parse(s.analysis);return{id:s.id,commitHash:s.commit_hash,status:s.status,analyzedAt:s.analyzed_at,patternCount:i.patterns.length}})}},ba=new ir,ti=ba;ar();function ii(n){let t=n;t.tool("prjct_task_status","Current task, duration, subtasks, and queue",{projectPath:cr.string().describe("Project directory path")},S("prjct_task_status",async e=>{let r=await x(e.projectPath),s=await dt.getCurrentTask(r),i=await At.getActiveTasks(r),o=[];if(s?(o.push(`## Active Task
|
|
642
|
+
**${s.description}**`),s.branch&&o.push(`Branch: ${s.branch}`),o.push(`Started: ${s.startedAt}`)):o.push("No active task."),i.length>0){o.push(`
|
|
643
643
|
## Queue (${i.length} tasks)`);for(let a of i.slice(0,10))o.push(`- ${a.description} [${a.priority||"medium"}]`)}return{content:[{type:"text",text:o.join(`
|
|
644
|
-
`)}]}})),t.tool("prjct_analysis","LLM analysis: stack, patterns, anti-patterns, conventions",{projectPath:
|
|
645
|
-
### Stack`),
|
|
646
|
-
### Patterns (${
|
|
647
|
-
### Anti-Patterns (${
|
|
648
|
-
### Conventions (${
|
|
649
|
-
`)}]}})),t.tool("prjct_patterns","Project memory grouped by type (decision / pattern / anti-pattern / gotcha). Powered by projectMemory \u2014 same source the CLI memory verbs read.",{projectPath:
|
|
650
|
-
|
|
651
|
-
Goal: ${a.content.goal}`,tags:{...e.tags??{},spec_id:a.id,status:a.status},source:a.id,provenance:"declared"}),a}async get(t,e){let r=await this.requireProjectId(t);return P.get(r,e)}async list(t,e={}){let r=await this.requireProjectId(t);return P.list(r,e)}async setStatus(t,e,r){let
|
|
652
|
-
`)}]}})),t.tool("prjct_spec_list","List specs in this project. Use to check what specs exist before drafting a new one (avoid duplicates) or to find the right spec to link a task to.",{projectPath:y.string().describe("Project directory path"),status:y.enum(
|
|
644
|
+
`)}]}})),t.tool("prjct_analysis","LLM analysis: stack, patterns, anti-patterns, conventions",{projectPath:cr.string().describe("Project directory path")},S("prjct_analysis",async e=>{let r=await x(e.projectPath),s=ti.getActive(r);if(!s)return{content:[{type:"text",text:"No analysis available. Run `prjct sync`."}]};let i=["## Project Analysis"];if(s.stack&&(i.push(`
|
|
645
|
+
### Stack`),s.stack.languages?.length&&i.push(`Languages: ${s.stack.languages.join(", ")}`),s.stack.frameworks?.length&&i.push(`Frameworks: ${s.stack.frameworks.join(", ")}`),s.stack.packageManager&&i.push(`Package Manager: ${s.stack.packageManager}`)),s.patterns?.length){i.push(`
|
|
646
|
+
### Patterns (${s.patterns.length})`);for(let o of s.patterns)i.push(`- **${o.name}**: ${o.description}`)}if(s.antiPatterns?.length){i.push(`
|
|
647
|
+
### Anti-Patterns (${s.antiPatterns.length})`);for(let o of s.antiPatterns)i.push(`- **${o.issue}**: ${o.suggestion}`)}if(s.conventions?.length){i.push(`
|
|
648
|
+
### Conventions (${s.conventions.length})`);for(let o of s.conventions)i.push(`- [${o.category}] ${o.rule}`)}return{content:[{type:"text",text:i.join(`
|
|
649
|
+
`)}]}})),t.tool("prjct_patterns","Project memory grouped by type (decision / pattern / anti-pattern / gotcha). Powered by projectMemory \u2014 same source the CLI memory verbs read.",{projectPath:cr.string().describe("Project directory path")},S("prjct_patterns",async e=>{let r=await x(e.projectPath),s=C.recall(r,{types:["decision","pattern","anti-pattern","gotcha"],limit:50});return s.length===0?{content:[{type:"text",text:"No decisions or patterns captured yet."}]}:{content:[{type:"text",text:ft(s)}]}}))}c(ii,"registerProjectTools");import{z as y}from"zod";bt();ht();re();ee();N();rt();async function Da(n){try{let{stdout:t}=await Or("git",["rev-parse","HEAD"],{cwd:n}),e=t.trim();return/^[0-9a-f]{7,40}$/.test(e)?e:null}catch{return null}}c(Da,"readGitHead");var dr=class{static{c(this,"SpecService")}async create(t,e){let r=await this.requireProjectId(t),s=e.content.notes??"";if(e.autoContext!==!1&&!s.trim()){let{inferSpecContext:u,warnNoContextMatch:l}=await Promise.resolve().then(()=>(ci(),ai)),d=await u(e.title,r,t);d.empty?l(e.title):s=d.notesBlock}let o=Y.parse({goal:e.content.goal,eli10:e.content.eli10??"",stakes:e.content.stakes??"",acceptance_criteria:e.content.acceptance_criteria??[],scope:e.content.scope??[],out_of_scope:e.content.out_of_scope??[],risks:e.content.risks??[],test_plan:e.content.test_plan??[],reviews:e.content.reviews,linked_tasks:e.content.linked_tasks??[],notes:s}),a=P.create(r,{title:e.title,content:o,tags:e.tags});return await C.remember(t,{type:"spec",content:`${a.title}
|
|
650
|
+
|
|
651
|
+
Goal: ${a.content.goal}`,tags:{...e.tags??{},spec_id:a.id,status:a.status},source:a.id,provenance:"declared"}),a}async get(t,e){let r=await this.requireProjectId(t);return P.get(r,e)}async list(t,e={}){let r=await this.requireProjectId(t);return P.list(r,e)}async setStatus(t,e,r){let s=await this.requireProjectId(t),i=P.setStatus(s,e,r);return i&&await C.remember(t,{type:"spec",content:`Spec status \u2192 ${r}: ${i.title}`,tags:{spec_id:e,status:r,event:"status_change"},source:e}),i}async update(t,e,r){let s=await this.requireProjectId(t);return P.updateContent(s,e,r)}async recordReview(t,e,r,s){let i=await this.requireProjectId(t),o=3,a=50,u=0,l=!1,d=null;for(;u<o;){let p=P.get(i,e);if(!p)return null;let g={...s,ts:f()},T={...p.content,reviews:{...p.content.reviews??{},[r]:g}};if(P.casUpdate(i,e,T,p.updatedAt)){l=!0,d=P.get(i,e);break}u++,u<o&&await new Promise(z=>setTimeout(z,a))}if(!l)throw new Error(`SPEC_RECORD_REVIEW_CONFLICT_RETRY_EXHAUSTED: ${o} retries failed for spec ${e}`);if(d&&this.allReviewsPass(d.content)&&d.status==="draft"){let p=P.setStatus(i,e,"reviewed");if(p){let{breakdownSpecToTasks:g}=await Promise.resolve().then(()=>(li(),ui));return await g(i,t,p),P.get(i,e)}return p}return d}async linkTask(t,e,r){let s=await this.requireProjectId(t);return P.linkTask(s,e,r)}async ship(t,e,r){let s=await this.requireProjectId(t);r!==void 0&&P.setShippedPr(s,e,r);let i=await Da(t);return i&&P.setShippedSha(s,e,i),P.setStatus(s,e,"shipped")}unmetCriteria(t,e=new Set){return t.content.acceptance_criteria.filter(r=>!e.has(r))}allReviewsPass(t){let e=t.reviews;return e?e.strategic?.verdict==="pass"&&e.architecture?.verdict==="pass"&&e.design?.verdict==="pass":!1}async requireProjectId(t){let e=await B.readConfig(t);if(!e?.projectId)throw new Error("not a prjct project (run `prjct init` first)");return e.projectId}},J=new dr;re();ee();function pi(n){let t=n;t.tool("prjct_spec_create",'Draft a spec when the user frames a feature/fix/initiative WITH goals or stakes (e.g. "rate limiting on auth", "fix onboarding"). Fields default empty \u2014 fill them via `prjct_spec_update`. Skip for routine work (single-file fix, doc tweak, capture); use `prjct_capture` instead.',{projectPath:y.string().describe("Project directory path"),title:y.string().describe("One-line title (what you'd say to a coworker walking by)"),goal:y.string().describe("What success looks like, 1-3 sentences. Concrete, observable."),eli10:y.string().optional().describe("Plain English a 16-year-old follows, 2-4 sentences"),stakes:y.string().optional().describe("What breaks if we ship the wrong thing"),acceptance_criteria:y.array(y.string()).optional().describe("Testable, observable list. Each item ends in a verifiable claim."),scope:y.array(y.string()).optional().describe("What's IN \u2014 file paths, modules, surfaces"),out_of_scope:y.array(y.string()).optional().describe("What's OUT \u2014 anti-creep shield"),risks:y.array(y.object({risk:y.string(),mitigation:y.string()})).optional().describe("Each risk has a mitigation; a risk without one is just a complaint"),test_plan:y.array(y.string()).optional().describe("How you prove acceptance criteria"),tags:y.record(y.string(),y.string()).optional().describe('Key:value tags (e.g. {domain: "auth", priority: "high"})')},S("prjct_spec_create",async e=>{let r=await J.create(e.projectPath,{title:e.title,content:{goal:e.goal,eli10:e.eli10,stakes:e.stakes,acceptance_criteria:e.acceptance_criteria,scope:e.scope,out_of_scope:e.out_of_scope,risks:e.risks,test_plan:e.test_plan},tags:e.tags});return{content:[{type:"text",text:[`\u2713 spec drafted: ${r.title}`,"",`id: ${r.id}`,`status: ${r.status}`,`goal: ${r.content.goal}`,"","Next: `prjct_spec_audit` to dispatch the three review subagents (strategic / architecture / design) in parallel."].join(`
|
|
652
|
+
`)}]}})),t.tool("prjct_spec_list","List specs in this project. Use to check what specs exist before drafting a new one (avoid duplicates) or to find the right spec to link a task to.",{projectPath:y.string().describe("Project directory path"),status:y.enum(yt).optional().describe("Filter by status: draft|reviewed|in_progress|shipped|archived"),includeArchived:y.boolean().optional().describe("Include archived specs (default: false)")},S("prjct_spec_list",async e=>{let r=await x(e.projectPath),s=P.list(r,{status:e.status,includeArchived:e.includeArchived});if(s.length===0)return{content:[{type:"text",text:"_No specs match. Start one with `prjct_spec_create`._"}]};let i=["# Specs",""];for(let o of s){let a=o.content.acceptance_criteria.length,u=o.content.linked_tasks.length;i.push(`## ${o.title}
|
|
653
653
|
- id: \`${o.id}\`
|
|
654
654
|
- status: ${o.status}
|
|
655
655
|
- acceptance criteria: ${a}
|
|
656
656
|
- linked tasks: ${u}
|
|
657
657
|
- created: ${o.createdAt}`),i.push("")}return{content:[{type:"text",text:i.join(`
|
|
658
|
-
`)}]}})),t.tool("prjct_spec_get","Fetch one spec by id, including all structured fields (goal, acceptance criteria, scope, risks, reviews, linked tasks).",{projectPath:y.string().describe("Project directory path"),id:y.string().describe("Spec id")},S("prjct_spec_get",async e=>{let r=await J.get(e.projectPath,e.id);return r?{content:[{type:"text",text:
|
|
659
|
-
`)}c(
|
|
660
|
-
`)}c(
|
|
661
|
-
VALUES (?, ?, ?, ?, 0, 1, ?)`,e.name,e.description??null,r,r,e.metadata?JSON.stringify(e.metadata):null);let
|
|
662
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,e.type,e.command,e.position,e.action,e.description??null,e.enabled?1:0,e.timeoutMs,e.createdAt,
|
|
658
|
+
`)}]}})),t.tool("prjct_spec_get","Fetch one spec by id, including all structured fields (goal, acceptance criteria, scope, risks, reviews, linked tasks).",{projectPath:y.string().describe("Project directory path"),id:y.string().describe("Spec id")},S("prjct_spec_get",async e=>{let r=await J.get(e.projectPath,e.id);return r?{content:[{type:"text",text:Oa(r)}]}:{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]}})),t.tool("prjct_spec_update","Replace a spec's structured content. Pass the FULL content object (this is a replace, not a merge) \u2014 when filling in acceptance_criteria for the first time, fetch with `prjct_spec_get` first and merge in your changes.",{projectPath:y.string().describe("Project directory path"),id:y.string().describe("Spec id"),content:y.object({goal:y.string(),eli10:y.string().optional(),stakes:y.string().optional(),acceptance_criteria:y.array(y.string()).optional(),scope:y.array(y.string()).optional(),out_of_scope:y.array(y.string()).optional(),risks:y.array(y.object({risk:y.string(),mitigation:y.string()})).optional(),test_plan:y.array(y.string()).optional(),notes:y.string().optional(),linked_tasks:y.array(y.string()).optional()}).describe("Full SpecContent shape \u2014 Zod-validated server-side")},S("prjct_spec_update",async e=>{let r=Y.parse(e.content),s=await J.update(e.projectPath,e.id,r);return s?{content:[{type:"text",text:`\u2713 spec updated: ${s.title}`}]}:{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]}})),t.tool("prjct_spec_set_status","Promote/demote a spec lifecycle state: `in_progress` when work starts, `archived` when superseded. (draft \u2192 reviewed auto-promotes when reviewers pass; for first ship use `prjct_spec_ship` so the PR is recorded.)",{projectPath:y.string().describe("Project directory path"),id:y.string().describe("Spec id"),status:y.enum(yt).describe("Target status")},S("prjct_spec_set_status",async e=>await J.setStatus(e.projectPath,e.id,e.status)?{content:[{type:"text",text:`\u2713 spec ${e.id} \u2192 ${e.status}`}]}:{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]})),t.tool("prjct_spec_audit","Call before implementing a spec. Returns a dispatch prompt for THREE review subagents (strategic / architecture / design) \u2014 run ALL THREE IN PARALLEL (one Agent block per reviewer, same message). Persist each verdict via `prjct_spec_record_review`; all three pass \u2192 spec auto-promotes draft \u2192 reviewed.",{projectPath:y.string().describe("Project directory path"),id:y.string().describe("Spec id to audit")},S("prjct_spec_audit",async e=>{let r=await J.get(e.projectPath,e.id);return r?{content:[{type:"text",text:Ma(r.id,r.title,r.content)}]}:{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]}})),t.tool("prjct_spec_record_review","Persist one reviewer's verdict from `prjct_spec_audit` dispatch. Call once per reviewer (strategic, architecture, design). When all three are recorded with verdict=pass, the spec auto-promotes draft \u2192 reviewed.",{projectPath:y.string().describe("Project directory path"),id:y.string().describe("Spec id"),reviewer:y.enum(lr).describe("Which reviewer"),verdict:y.enum(["pass","fail"]).describe("Verdict"),notes:y.string().describe("2-4 sentence notes from the subagent")},S("prjct_spec_record_review",async e=>{let r=await J.recordReview(e.projectPath,e.id,e.reviewer,{verdict:e.verdict,notes:e.notes});if(!r)return{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]};let s=r.status==="reviewed"?" (all reviewers passed \u2192 status: reviewed)":"";return{content:[{type:"text",text:`\u2713 ${e.reviewer} \u2192 ${e.verdict}${s}`}]}})),t.tool("prjct_spec_link_task","Link a task to its spec (call after starting the task) so `prjct_ship` knows which spec to gate against. Idempotent.",{projectPath:y.string().describe("Project directory path"),specId:y.string().describe("Spec id"),taskId:y.string().describe("Task id (from `prjct_session_start_task` or stateStorage)")},S("prjct_spec_link_task",async e=>await J.linkTask(e.projectPath,e.specId,e.taskId)?{content:[{type:"text",text:`\u2713 linked task ${e.taskId} to spec ${e.specId}`}]}:{content:[{type:"text",text:`_Spec not found: ${e.specId}_`}]})),t.tool("prjct_spec_ship","Mark a spec as shipped (after the linked PR merges). Records the PR number on the spec for provenance.",{projectPath:y.string().describe("Project directory path"),id:y.string().describe("Spec id"),pr:y.number().optional().describe("PR / MR number that delivered the spec")},S("prjct_spec_ship",async e=>{let r=await J.ship(e.projectPath,e.id,e.pr);return r?{content:[{type:"text",text:`\u2713 spec shipped: ${r.title}${e.pr?` (PR #${e.pr})`:""}`}]}:{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]}}))}c(pi,"registerSpecTools");function Oa(n){let t=n.content,e=[`# ${n.title}`,"",`**id:** \`${n.id}\` \xB7 **status:** ${n.status} \xB7 **created:** ${n.createdAt}`,"","## Goal",t.goal];if(t.eli10&&e.push("","## ELI10",t.eli10),t.stakes&&e.push("","## Stakes",t.stakes),t.acceptance_criteria.length>0){e.push("","## Acceptance criteria");for(let r of t.acceptance_criteria)e.push(`- [ ] ${r}`)}if(t.scope.length>0){e.push("","## Scope");for(let r of t.scope)e.push(`- ${r}`)}if(t.out_of_scope.length>0){e.push("","## Out of scope");for(let r of t.out_of_scope)e.push(`- ${r}`)}if(t.risks.length>0){e.push("","## Risks");for(let r of t.risks)e.push(`- **${r.risk}** \u2014 ${r.mitigation}`)}if(t.test_plan.length>0){e.push("","## Test plan");for(let r of t.test_plan)e.push(`- ${r}`)}if(t.reviews){e.push("","## Reviews");for(let r of lr){let s=t.reviews[r];s&&e.push(`- **${r}:** ${s.verdict} \u2014 ${s.notes} _(${s.ts})_`)}}return t.linked_tasks.length>0&&e.push("","## Linked tasks",...t.linked_tasks.map(r=>`- ${r}`)),t.notes&&e.push("","## Notes",t.notes),e.join(`
|
|
659
|
+
`)}c(Oa,"renderSpecMarkdown");function Ma(n,t,e){let r=JSON.stringify(e);return[`# audit-spec dispatch \u2014 ${t}`,"",`Spec id: \`${n}\``,"","Run three review subagents IN PARALLEL via your Agent / Task tool \u2014 one tool-use block per reviewer, all in the SAME message so they run concurrently. Each subagent reads the spec body and applies its rubric, then returns a structured verdict (pass | fail + 2-4 sentence notes).","","## Reviewer A \u2014 strategic (scope sanity)",'Subagent prompt: "Review this spec for strategic soundness. Does it solve a real problem? Is the goal worth the cost? Is out_of_scope coherent with goal? Is the spec OVER- or UNDER-scoped? Return verdict (pass|fail) and 2-4 sentence notes."',"","## Reviewer B \u2014 architecture (eng feasibility)",'Subagent prompt: "Review this spec for engineering feasibility. Can this be built? Is the data flow / state machine implicit in the acceptance criteria coherent? What failure modes / dependencies / edge cases are missing? Include a short ASCII diagram of the proposed architecture in notes if applicable. Return verdict (pass|fail) and 2-4 sentence notes."',"","## Reviewer C \u2014 design (UX/DX)",'Subagent prompt: "Review this spec for design quality. Rate 0-10 across {clarity, ergonomics, consistency, accessibility} for the user-facing or developer-facing surface this spec defines. Note the lowest-scoring dimension and why. Return verdict (pass if all dimensions \u22656, fail otherwise) and notes including the four scores."',"","## Spec body (verbatim, pass to each reviewer)","```json",r,"```","","## After dispatch","For each reviewer that returns:",` Call \`prjct_spec_record_review\` with id="${n}", reviewer=<strategic|architecture|design>, verdict=<pass|fail>, notes="<their notes>"`,"","When all three are recorded with verdict=pass, the spec auto-promotes from `draft` \u2192 `reviewed`."].join(`
|
|
660
|
+
`)}c(Ma,"renderAuditDispatch");import{z as se}from"zod";xt();j();var mr=class{static{c(this,"CustomWorkflowStorage")}createWorkflow(t,e){let r=new Date().toISOString();h.run(t,`INSERT INTO custom_workflows (name, description, created_at, updated_at, is_builtin, enabled, metadata)
|
|
661
|
+
VALUES (?, ?, ?, ?, 0, 1, ?)`,e.name,e.description??null,r,r,e.metadata?JSON.stringify(e.metadata):null);let s=h.get(t,"SELECT id FROM custom_workflows WHERE name = ?",e.name);if(!s)throw new Error(`Failed to create workflow: ${e.name}`);return q({projectId:t,entityType:"custom_workflows",entityId:String(s.id),eventType:"upsert",data:{id:s.id,name:e.name,description:e.description??null,metadata:e.metadata??null,created_at:r,updated_at:r,is_builtin:0,enabled:1}}),s.id}getWorkflow(t,e){let r=h.get(t,"SELECT * FROM custom_workflows WHERE name = ?",e);return r?this.rowToWorkflow(r):null}getAllWorkflows(t,e=!1){let r=e?"SELECT * FROM custom_workflows ORDER BY is_builtin DESC, name ASC":"SELECT * FROM custom_workflows WHERE enabled = 1 ORDER BY is_builtin DESC, name ASC";return h.query(t,r).map(i=>this.rowToWorkflow(i))}updateWorkflow(t,e,r){if(!this.getWorkflow(t,e))return!1;let i=new Date().toISOString(),o=[],a=[];if(r.description!==void 0&&(o.push("description = ?"),a.push(r.description)),r.enabled!==void 0&&(o.push("enabled = ?"),a.push(r.enabled?1:0)),r.metadata!==void 0&&(o.push("metadata = ?"),a.push(JSON.stringify(r.metadata))),o.length===0)return!1;o.push("updated_at = ?"),a.push(i),a.push(e),h.run(t,`UPDATE custom_workflows SET ${o.join(", ")} WHERE name = ?`,...a);let u=this.getWorkflow(t,e);return u&&q({projectId:t,entityType:"custom_workflows",entityId:String(u.id),eventType:"upsert",data:{id:u.id,name:u.name,description:u.description??null,enabled:u.enabled?1:0,metadata:u.metadata??null,updated_at:i}}),!0}deleteWorkflow(t,e){let r=this.getWorkflow(t,e);if(!r)return!1;if(r.isBuiltin)throw new Error(`Cannot delete built-in workflow: ${e}`);return h.run(t,"UPDATE custom_workflows SET enabled = 0 WHERE name = ?",e),q({projectId:t,entityType:"custom_workflows",entityId:String(r.id),eventType:"delete",data:{id:r.id,name:e}}),!0}isBuiltin(t,e){return this.getWorkflow(t,e)?.isBuiltin??!1}isReservedName(t){let e=["task","done","ship","sync"],r=["add","rm","gate","list","create","delete","run","help","reset","init"];return e.includes(t)||r.includes(t)}isValidName(t){return/^[a-z0-9-]+$/.test(t)}rowToWorkflow(t){return{id:t.id,name:t.name,description:t.description,createdAt:t.created_at,updatedAt:t.updated_at,isBuiltin:t.is_builtin===1,enabled:t.enabled===1,metadata:t.metadata?JSON.parse(t.metadata):null}}},ne=new mr;xt();j();var ja=["hook","gate","step","instruction"];function gr(n){let t=n.trust_source==="imported"?"imported":"local",e=ja.includes(n.type)?n.type:"step";return{id:n.id,type:e,command:n.command,position:n.position,action:n.action,description:n.description,enabled:n.enabled===1,timeoutMs:n.timeout_ms,createdAt:n.created_at,sortOrder:n.sort_order,whenExpr:n.when_expr??null,parallel:n.parallel===null?!0:n.parallel===1,trustSource:t}}c(gr,"rowToRule");var fr=class{static{c(this,"WorkflowRuleStorage")}addRule(t,e){let r=k.get(t,"SELECT MAX(sort_order) as m FROM workflow_rules WHERE command = ?",e.command),s=e.sortOrder||(r?.m??-1)+1;k.run(t,`INSERT INTO workflow_rules (type, command, position, action, description, enabled, timeout_ms, created_at, sort_order, when_expr, parallel, trust_source)
|
|
662
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,e.type,e.command,e.position,e.action,e.description??null,e.enabled?1:0,e.timeoutMs,e.createdAt,s,e.whenExpr??null,e.parallel===!1?0:1,e.trustSource??"local");let o=k.get(t,"SELECT last_insert_rowid() as id")?.id??0;return o>0&&q({projectId:t,entityType:"workflow_rules",entityId:String(o),eventType:"upsert",data:{id:o,type:e.type,command:e.command,position:e.position,action:e.action,description:e.description??null,enabled:e.enabled?1:0,timeout_ms:e.timeoutMs,sort_order:s,when_expr:e.whenExpr??null,parallel:e.parallel===!1?0:1,trust_source:e.trustSource??"local",created_at:e.createdAt}}),o}removeRule(t,e){return k.get(t,"SELECT id FROM workflow_rules WHERE id = ?",e)?(k.run(t,"DELETE FROM workflow_rules WHERE id = ?",e),q({projectId:t,entityType:"workflow_rules",entityId:String(e),eventType:"delete",data:{id:e}}),!0):!1}updateRule(t,e,r){if(!k.get(t,"SELECT id FROM workflow_rules WHERE id = ?",e))return!1;let i={type:{column:"type"},command:{column:"command"},position:{column:"position"},action:{column:"action"},description:{column:"description"},enabled:{column:"enabled",transform:c(u=>u?1:0,"transform")},timeoutMs:{column:"timeout_ms"},createdAt:{column:"created_at"},sortOrder:{column:"sort_order"},whenExpr:{column:"when_expr"},parallel:{column:"parallel",transform:c(u=>u===!1?0:1,"transform")},trustSource:{column:"trust_source"}},o=[],a=[];for(let[u,l]of Object.entries(r)){let d=i[u];if(!d)continue;o.push(`${d.column} = ?`);let p=l;a.push(d.transform?d.transform(p):p)}return o.length===0||(a.push(e),k.run(t,`UPDATE workflow_rules SET ${o.join(", ")} WHERE id = ?`,...a)),!0}getRuleById(t,e){let r=k.get(t,"SELECT * FROM workflow_rules WHERE id = ?",e);return r?gr(r):null}getRulesForCommand(t,e){let r=ne.getWorkflow(t,e);return!r||!r.enabled?[]:k.query(t,"SELECT * FROM workflow_rules WHERE command = ? AND enabled = 1 ORDER BY sort_order ASC",e).map(gr)}getAllRules(t){return k.query(t,"SELECT * FROM workflow_rules ORDER BY command ASC, sort_order ASC").map(gr)}resetRules(t){let e=k.get(t,"SELECT COUNT(*) as c FROM workflow_rules");return k.run(t,"DELETE FROM workflow_rules"),e?.c??0}},hr=new fr;function di(n){let t=n;t.tool("prjct_workflow_rules","Get workflow rules for a command (gates, hooks, steps, instructions)",{projectPath:se.string().describe("Project directory path"),command:se.string().describe("Command name (task, done, ship, sync, etc.)")},S("prjct_workflow_rules",async e=>{let r=await x(e.projectPath),s=hr.getRulesForCommand(r,e.command);if(s.length===0)return{content:[{type:"text",text:`No workflow rules for \`${e.command}\`.`}]};let i={};for(let a of s){let u=`${a.type}:${a.position}`;i[u]||(i[u]=[]),i[u].push(a)}let o=[`## Workflow Rules for \`${e.command}\``];for(let[a,u]of Object.entries(i)){o.push(`
|
|
663
663
|
### ${a}`);for(let l of u){let d=l.enabled?"":" (disabled)";o.push(`- ${l.action}${l.description?` \u2014 ${l.description}`:""}${d}`)}}return{content:[{type:"text",text:o.join(`
|
|
664
|
-
`)}]}})),t.tool("prjct_workflow_list","List all workflows for this project (built-in + custom)",{projectPath:
|
|
664
|
+
`)}]}})),t.tool("prjct_workflow_list","List all workflows for this project (built-in + custom)",{projectPath:se.string().describe("Project directory path")},S("prjct_workflow_list",async e=>{let r=await x(e.projectPath),s=ne.getAllWorkflows(r);if(s.length===0)return{content:[{type:"text",text:"No workflows configured."}]};let i=s.map(o=>{let a=o.isBuiltin?"(built-in)":"(custom)",u=o.enabled?"":" [disabled]";return`- **${o.name}** ${a}${u}${o.description?`: ${o.description}`:""}`});return{content:[{type:"text",text:`## Workflows (${s.length})
|
|
665
665
|
|
|
666
666
|
${i.join(`
|
|
667
|
-
`)}`}]}})),t.tool("prjct_workflow_status","Current workflow execution state + active rules",{projectPath:
|
|
668
|
-
Active task: **${
|
|
667
|
+
`)}`}]}})),t.tool("prjct_workflow_status","Current workflow execution state + active rules",{projectPath:se.string().describe("Project directory path")},S("prjct_workflow_status",async e=>{let r=await x(e.projectPath),s=await dt.getCurrentTask(r),i=hr.getAllRules(r),o=["## Workflow Status"];s?(o.push(`
|
|
668
|
+
Active task: **${s.description}**`),o.push(`Started: ${s.startedAt}`)):o.push(`
|
|
669
669
|
No active task.`);let a=i.filter(u=>u.enabled);if(a.length>0){o.push(`
|
|
670
670
|
### Active Rules (${a.length})`);for(let u of a)o.push(`- [${u.type}] ${u.command}:${u.position} \u2192 ${u.action}`)}else o.push(`
|
|
671
671
|
No active workflow rules.`);return{content:[{type:"text",text:o.join(`
|
|
672
|
-
`)}]}}))}c(
|
|
672
|
+
`)}]}}))}c(di,"registerWorkflowTools");var Ua=`# prjct \u2014 Spec-Driven Development + project memory
|
|
673
673
|
|
|
674
674
|
Use when the user describes work, asks for project memory, or wants to run a registered workflow. **Recognize intent \u2014 don't wait for the user to type prjct commands.**
|
|
675
675
|
|
|
@@ -704,4 +704,4 @@ Skip the SDD flow only for: routine captures, single-file fixes, doc tweaks, con
|
|
|
704
704
|
- Topic keys are free-form strings; don't invent new vocabularies when existing ones fit.
|
|
705
705
|
- Not every project defines every memory type \u2014 if one is empty, that's fine.
|
|
706
706
|
- Saving a secret-looking string is refused by default. Re-save with a scrubbed version.
|
|
707
|
-
- A spec without acceptance_criteria is just an inbox item \u2014 fill them.`;function
|
|
707
|
+
- A spec without acceptance_criteria is just an inbox item \u2014 fill them.`;function mi(){let n=new Fa({name:"prjct",version:"1.0.0"},{instructions:Ua});return Zs(n),ii(n),Ds(n),di(n),Pn(n),pi(n),n}c(mi,"createServer");async function Xa(){let n=mi(),t=new $a;await n.connect(t)}c(Xa,"main");Xa().catch(n=>{console.error("prjct MCP server failed:",n),process.exit(1)});
|