prjct-cli 2.18.0 → 2.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/bin/prjct-core.mjs +356 -344
- package/dist/daemon/entry.mjs +176 -164
- package/dist/mcp/server.mjs +65 -57
- package/package.json +1 -1
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 _t=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var Yn=Object.prototype.hasOwnProperty;var
|
|
9
|
-
`;await Q.writeFile(r,n,"utf-8")}async function A(r){try{return await Q.access(r),!0}catch(t){if(L(t))return!1;throw t}}async function ee(r){try{return(await Q.stat(r)).isDirectory()}catch(t){if(L(t))return!1;throw t}}async function U(r){await Q.mkdir(r,{recursive:!0})}var X=k(()=>{"use strict";Zt();ys();V();
|
|
10
|
-
`).map(o=>o.replace(/^\s*-\s*['"]?|['"]?\s*$/g,"")).filter(Boolean))}else if(t==="npm"||t==="lerna"){let n=I.join(r,"package.json"),i=JSON.parse(await et.readFile(n,"utf-8"));if(Array.isArray(i.workspaces)?s=i.workspaces:i.workspaces?.packages&&(s=i.workspaces.packages),t==="lerna"){let o=I.join(r,"lerna.json");if(await A(o)){let
|
|
8
|
+
var _t=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var Yn=Object.prototype.hasOwnProperty;var a=(r,t)=>_t(r,"name",{value:t,configurable:!0}),os=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var k=(r,t)=>()=>(r&&(t=r(r=0)),t);var K=(r,t)=>{for(var e in t)_t(r,e,{get:t[e],enumerable:!0})},Jn=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Gn(t))!Yn.call(r,n)&&n!==e&&_t(r,n,{get:()=>t[n],enumerable:!(s=qn(t,n))||s.enumerable});return r};var Qt=r=>Jn(_t({},"__esModule",{value:!0}),r);var as,cs,us,Zt=k(()=>{"use strict";as=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"]),cs=["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"],us=/(?:import|from)\s+['"]([^'"]+)['"]/g});import{formatDistanceToNowStrict as ca}from"date-fns";function ls(r){return{year:r.getFullYear().toString(),month:(r.getMonth()+1).toString().padStart(2,"0"),day:r.getDate().toString().padStart(2,"0")}}function g(){return new Date().toISOString()}function ps(r){let t=new Date;return t.setDate(t.getDate()-r),t}var C=k(()=>{"use strict";a(ls,"getYearMonthDay");a(g,"getTimestamp");a(ps,"getDaysAgo")});function Kn(r){return r instanceof Error&&"code"in r}function L(r){return Kn(r)&&r.code==="ENOENT"}function ds(r){return r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var V=k(()=>{"use strict";a(Kn,"isNodeError");a(L,"isNotFoundError");a(ds,"getErrorMessage")});import fs from"node:fs/promises";async function hs(r,t){let e;try{e=await fs.readFile(r,"utf-8")}catch(i){if(L(i))return null;throw i}let s;try{s=JSON.parse(e)}catch{return await ms(r,e),gs(r,"Malformed JSON"),null}let n=t.safeParse(s);return n.success?s:(await ms(r,e),gs(r,Vn(n.error)),null)}async function ms(r,t){let e=`${r}.backup`;try{await fs.writeFile(e,t,"utf-8")}catch{}}function gs(r,t){console.error(`[prjct] Warning: Corrupted storage file: ${r}`),console.error(`[prjct] Reason: ${t}`),console.error("[prjct] A .backup file has been created. Returning defaults.")}function Vn(r){return r.issues.slice(0,3).map(t=>`${t.path.join(".")}: ${t.message}`).join("; ")}var ys=k(()=>{"use strict";V();a(hs,"safeRead");a(ms,"createBackup");a(gs,"logCorruption");a(Vn,"formatZodError")});import Q from"node:fs/promises";import te from"node:path";async function Ts(r,t={}){let e=[],s=t.maxFiles??1/0,n=t.dotfileAllowlist?new Set(t.dotfileAllowlist):null;async function i(o){if(e.length>=s)return;let c=await Q.readdir(o,{withFileTypes:!0}).catch(()=>[]);for(let u of c){if(e.length>=s)break;let p=String(u.name);if(as.has(p)||t.skipDotfiles&&p.startsWith(".")&&(!n||!n.has(p)))continue;let m=te.join(o,p);u.isDirectory()?await i(m):u.isFile()&&e.push(te.relative(r,m))}}return a(i,"walk"),await i(r),e}async function ks(r,t,e){let s=[];for(let n=0;n<r.length;n+=t){let i=await Promise.all(r.slice(n,n+t).map(e));for(let o of i)o!==null&&s.push(o)}return s}async function vt(r,t=null,e){if(e)return await hs(r,e)??t;try{let s=await Q.readFile(r,"utf-8");return JSON.parse(s)}catch(s){if(L(s))return t;throw s}}async function F(r,t,e=2){let s=te.dirname(r);await Q.mkdir(s,{recursive:!0});let n=`${JSON.stringify(t,null,e)}
|
|
9
|
+
`;await Q.writeFile(r,n,"utf-8")}async function A(r){try{return await Q.access(r),!0}catch(t){if(L(t))return!1;throw t}}async function ee(r){try{return(await Q.stat(r)).isDirectory()}catch(t){if(L(t))return!1;throw t}}async function U(r){await Q.mkdir(r,{recursive:!0})}var X=k(()=>{"use strict";Zt();ys();V();a(Ts,"walkDir");a(ks,"batchProcess");a(vt,"readJson");a(F,"writeJson");a(A,"fileExists");a(ee,"dirExists");a(U,"ensureDir")});import et from"node:fs/promises";import I from"node:path";import{globSync as Qn}from"glob";async function se(r){let t={isMonorepo:!1,type:null,rootPath:r,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 s of e)if(await A(I.join(r,s.file))){t.isMonorepo=!0,t.type=s.type;break}if(!t.isMonorepo){let s=I.join(r,"package.json");if(await A(s))try{JSON.parse(await et.readFile(s,"utf-8")).workspaces&&(t.isMonorepo=!0,t.type="npm")}catch{}}return t.isMonorepo&&(t.packages=await re(r,t.type)),t}async function re(r,t){let e=[],s=[];try{if(t==="pnpm"){let i=(await et.readFile(I.join(r,"pnpm-workspace.yaml"),"utf-8")).match(/packages:\s*\n((?:\s*-\s*.+\n?)+)/);i&&(s=i[1].split(`
|
|
10
|
+
`).map(o=>o.replace(/^\s*-\s*['"]?|['"]?\s*$/g,"")).filter(Boolean))}else if(t==="npm"||t==="lerna"){let n=I.join(r,"package.json"),i=JSON.parse(await et.readFile(n,"utf-8"));if(Array.isArray(i.workspaces)?s=i.workspaces:i.workspaces?.packages&&(s=i.workspaces.packages),t==="lerna"){let o=I.join(r,"lerna.json");if(await A(o)){let c=JSON.parse(await et.readFile(o,"utf-8"));c.packages&&(s=c.packages)}}}else if(t==="nx")s=["apps/*","libs/*","packages/*"];else if(t==="turborepo"){let n=I.join(r,"package.json"),i=JSON.parse(await et.readFile(n,"utf-8"));Array.isArray(i.workspaces)&&(s=i.workspaces)}s.length===0&&(s=["packages/*","apps/*","libs/*"]);for(let n of s){if(n.startsWith("!"))continue;let i=Qn(n,{cwd:r,absolute:!1});for(let o of i){let c=I.join(r,o),u=I.join(c,"package.json");if(await A(u))try{let p=JSON.parse(await et.readFile(u,"utf-8")),m=I.join(c,"PRJCT.md");e.push({name:p.name||I.basename(o),path:c,relativePath:o,hasPrjctMd:await A(m)})}catch{}}}}catch{}return e}async function Es(r,t){if(!t.isMonorepo)return null;let e=I.resolve(r);for(let s of t.packages){let n=I.resolve(s.path);if(e.startsWith(n))return s}return null}async function Ss(r){let t=I.resolve(r),e=I.parse(t).root;for(;t!==e;){if((await se(t)).isMonorepo)return t;t=I.dirname(t)}return null}var ws=k(()=>{"use strict";X();a(se,"detectMonorepo");a(re,"discoverMonorepoPackages");a(Es,"findContainingPackage");a(Ss,"findMonorepoRoot")});import{exec as Zn,execFile as ti}from"node:child_process";import{promisify as bs}from"node:util";var b,Aa,st=k(()=>{"use strict";b=bs(Zn),Aa=bs(ti)});var oe={};K(oe,{default:()=>ei,worktreeService:()=>vs});import ne from"node:fs/promises";import $ from"node:path";var _s,ie,vs,ei,ae=k(()=>{"use strict";st();X();_s=".worktrees",ie=class{static{a(this,"WorktreeService")}async create(t,e,s={}){let n=await this.getMainWorktree(t),i=$.join(n,_s,e),o=s.branch||`feat/${e}`;await ne.mkdir($.join(n,_s),{recursive:!0});let c=s.baseBranch?` ${s.baseBranch}`:"";await b(`git worktree add "${i}" -b "${o}"${c}`,{cwd:n});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 s=await this.getMainWorktree(t),n;if(e)try{let{stdout:i}=await b("git rev-parse --abbrev-ref HEAD",{cwd:t});n=i.trim()}catch{}if(await b(`git worktree remove "${t}" --force`,{cwd:s}),e&&n&&n!=="main"&&n!=="master")try{await b(`git branch -D "${n}"`,{cwd:s})}catch{}}async list(t){let e=await this.getMainWorktree(t),{stdout:s}=await b("git worktree list --porcelain",{cwd:e});return this.parsePorcelainOutput(s,e)}async detect(t){try{let{stdout:e}=await b("git rev-parse --git-common-dir",{cwd:t}),{stdout:s}=await b("git rev-parse --git-dir",{cwd:t}),n=$.resolve(t,e.trim()),i=$.resolve(t,s.trim());if(n!==i){let{stdout:o}=await b("git rev-parse --abbrev-ref HEAD",{cwd:t}),{stdout:c}=await b("git rev-parse HEAD",{cwd:t}),{stdout:u}=await b("git rev-parse --show-toplevel",{cwd:t}),p=u.trim(),m=$.basename(p);return{path:p,branch:o.trim(),commit:c.trim(),isMain:!1,slug:m}}return null}catch{return null}}async getMainWorktree(t){try{let{stdout:s}=await b("git worktree list --porcelain",{cwd:t}),n=s.split(`
|
|
11
11
|
`)[0];if(n?.startsWith("worktree "))return n.replace("worktree ","").trim()}catch{}let{stdout:e}=await b("git rev-parse --show-toplevel",{cwd:t});return e.trim()}async setup(t,e){let s=$.join(e,".env");await A(s)&&await ne.copyFile(s,$.join(t,".env"));let n=$.join(e,".prjct"),i=$.join(t,".prjct");await A(n)&&!await A(i)&&await ne.symlink(n,i,"dir")}async teardown(t){}async clean(t){let e=await this.list(t),s=[],n=await this.getMainWorktree(t);await b("git worktree prune",{cwd:n});for(let i of e)i.isMain||await A(i.path)||s.push(i.slug);return s}parsePorcelainOutput(t,e){let s=[],n=t.trim().split(`
|
|
12
12
|
|
|
13
13
|
`);for(let i of n){if(!i.trim())continue;let o=i.trim().split(`
|
|
14
|
-
`),a="",u="",p="",m=!1;for(let d of o)d.startsWith("worktree ")?a=d.replace("worktree ","").trim():d.startsWith("HEAD ")?u=d.replace("HEAD ","").trim():d.startsWith("branch ")?p=d.replace("branch refs/heads/","").trim():d==="bare"?m=!0:d==="detached"&&(p="(detached)");if(a){let d=a===e||m;s.push({path:a,branch:p,commit:u,isMain:d,slug:d?"main":$.basename(a)})}}return s}},vs=new ie,ei=vs});import ce from"node:os";import W from"node:path";async function xs(r,t){if(t&&t.trim().length>0)return ri(r,t);let e=await si(r),n=W.basename(W.resolve(e)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project";return W.join(ce.homedir(),"Documents","prjct",n)}function Ps(r,t){let s=W.basename(W.resolve(r)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project",n=t.replace(/-/g,"").slice(0,8);return W.join(ce.homedir(),"Documents","prjct",`${s}-${n}`)}function Rs(r){return W.join(r,".prjct","wiki")}async function si(r){try{let{worktreeService:t}=await Promise.resolve().then(()=>(ae(),oe));return await t.detect(r)&&await t.getMainWorktree(r)||r}catch{return r}}function ri(r,t){let e=t.trim();return(e.startsWith("~/")||e==="~")&&(e=W.join(ce.homedir(),e.slice(1))),W.isAbsolute(e)||(e=W.resolve(r,e)),e}var As=k(()=>{"use strict";c(xs,"getWikiPath");c(Ps,"getWikiPathWithProjectHash");c(Rs,"getLegacyWikiPath");c(si,"resolveProjectRootPath");c(ri,"resolveVaultOverride")});var Cs=k(()=>{"use strict"});import{z as dt}from"zod";function Ns(r,t){let e=r.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<3;n++){let i=e[n]??0,o=s[n]??0;if(i<o)return-1;if(i>o)return 1}return 0}var ue,le=k(()=>{"use strict";ue=dt.object({provider:dt.string(),model:dt.string(),cliVersion:dt.string().optional(),recordedAt:dt.string()});c(Ns,"compareSemver")});function Is(r,t){let e=typeof r=="string"?new Date(r).getTime():r;return Date.now()-e>t}var Pt,pe=k(()=>{"use strict";c(Is,"isExpired");Pt=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((s,n)=>s[1].timestamp-n[1].timestamp).slice(0,this.cache.size-this.maxSize);for(let[s]of e)this.cache.delete(s)}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 ni from"node:fs/promises";import ii from"node:os";import Ds from"node:path";async function Os(){try{let r=await ni.readFile(Ls,"utf-8"),t=JSON.parse(r);return!t.timestamp||!t.detection||!t.detection.claude||!t.detection.gemini||!t.detection.codex||Is(t.timestamp,ai)?null:t.detection}catch{return null}}async function js(r){let t={timestamp:new Date().toISOString(),detection:r};await F(Ls,t)}var oi,Ls,ai,Ms=k(()=>{"use strict";pe();X();oi=Ds.join(ii.homedir(),".prjct-cli","cache"),Ls=Ds.join(oi,"providers.json"),ai=10*60*1e3;c(Os,"readProviderCache");c(js,"writeProviderCache")});var At={};K(At,{ClaudeProvider:()=>Rt,CursorProvider:()=>Xs,GeminiProvider:()=>me,Providers:()=>mt,detectAllProviders:()=>ge,detectAntigravity:()=>di,detectCodex:()=>Hs,detectProvider:()=>de,getActiveProvider:()=>li,getProviderBranding:()=>pi,selectProvider:()=>mi,validateCliVersion:()=>Bs});import J from"node:os";import B from"node:path";async function Ws(r){try{let{stdout:t}=await b(`which ${r}`,{timeout:2e3});return t.trim()}catch{return null}}async function ui(r){try{let{stdout:t}=await b(`${r} --version`,{timeout:2e3}),e=t.match(/\d+\.\d+\.\d+/);return e?e[0]:t.trim()}catch{return null}}async function de(r){let t=mt[r];if(!t.cliCommand)return{installed:!1};let e=await Ws(t.cliCommand);if(!e)return{installed:!1};let s=await ui(t.cliCommand),n=Bs(r,s||void 0);return{installed:!0,version:s||void 0,path:e,versionWarning:n||void 0}}function Bs(r,t){let e=mt[r];return!e.minCliVersion||!t?null:Ns(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 ge(r=!1){if(!r){let o=await Os();if(o)return o}let[t,e,s]=await Promise.all([de("claude"),de("gemini"),Hs()]),n={installed:s.installed},i={claude:t,gemini:e,codex:n};return await js(i).catch(()=>{}),i}async function li(r){if(r&&mt[r])return mt[r];let t=await ge();return t.claude.installed&&!t.gemini.installed?Rt:t.gemini.installed&&!t.claude.installed?me:Rt}function pi(r){return{commitFooter:"Generated with [p/](https://www.prjct.app/)",signature:{claude:"\u26A1 prjct + Claude",gemini:"\u26A1 prjct + Gemini",cursor:"\u26A1 prjct + Cursor",antigravity:"\u26A1 prjct + Antigravity",windsurf:"\u26A1 prjct + Windsurf",codex:"\u26A1 prjct + Codex"}[r]||"\u26A1 prjct"}}async function di(){let r=Us.configDir;if(!r)return{installed:!1,skillInstalled:!1};let t=B.join(r,"skills","prjct","SKILL.md"),[e,s]=await Promise.all([A(r),A(t)]);return{installed:e,skillInstalled:s,configPath:e?r:void 0}}async function Hs(){let r=$s.configDir;if(!r)return{installed:!1,skillInstalled:!1};let t=await Ws("codex"),e=B.join(r,"skills","prjct","SKILL.md"),s=await A(e),n=!!t;return{installed:n,skillInstalled:s,configPath:n?r:void 0}}async function mi(){let r=await ge(),t=r.claude.installed,e=r.gemini.installed;return!t&&!e?{provider:"claude",userSelected:!1,detection:r}:t&&!e?{provider:"claude",userSelected:!1,detection:r}:e&&!t?{provider:"gemini",userSelected:!1,detection:r}:{provider:"claude",userSelected:!0,detection:r}}var Rt,me,Us,Xs,ci,$s,mt,Ct=k(()=>{"use strict";Cs();le();st();X();Ms();Rt={name:"claude",displayName:"Claude Code",cliCommand:"claude",configDir:B.join(J.homedir(),".claude"),contextFile:"CLAUDE.md",skillsDir:B.join(J.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"},me={name:"gemini",displayName:"Gemini CLI",cliCommand:"gemini",configDir:B.join(J.homedir(),".gemini"),contextFile:"GEMINI.md",skillsDir:B.join(J.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"},Us={name:"antigravity",displayName:"Google Antigravity",cliCommand:null,configDir:B.join(J.homedir(),".gemini","antigravity"),contextFile:"ANTIGRAVITY.md",skillsDir:B.join(J.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"},Xs={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"},ci={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"},$s={name:"codex",displayName:"OpenAI Codex",cliCommand:"codex",configDir:B.join(J.homedir(),".codex"),contextFile:"AGENTS.md",skillsDir:B.join(J.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"},mt={claude:Rt,gemini:me,cursor:Xs,antigravity:Us,windsurf:ci,codex:$s};c(Ws,"whichCommand");c(ui,"getCliVersion");c(de,"detectProvider");c(Bs,"validateCliVersion");c(ge,"detectAllProviders");c(li,"getActiveProvider");c(pi,"getProviderBranding");c(di,"detectAntigravity");c(Hs,"detectCodex");c(mi,"selectProvider")});import gi from"node:crypto";import Nt from"node:fs/promises";import fe from"node:os";import w from"node:path";var he,fi,v,gt=k(()=>{"use strict";C();X();ws();As();he=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(fe.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 gi.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 ee(this.getLegacyPrjctPath(t))}async hasConfig(t){return await A(this.getLocalConfigPath(t))}async ensureGlobalStructure(){await U(this.globalBaseDir),await U(this.globalProjectsDir),await U(this.globalConfigDir)}async ensureProjectStructure(t){await this.ensureGlobalStructure();let e=this.getGlobalProjectPath(t),s=["core","progress","planning","analysis","memory"];for(let n of s)await U(w.join(e,n));return await U(w.join(e,"planning","tasks")),await U(w.join(e,"sessions")),e}getSessionPath(t,e=new Date){let{year:s,month:n,day:i}=ls(e);return w.join(this.getGlobalProjectPath(t),"sessions",s,n,i)}getCurrentSessionPath(t){return this.getSessionPath(t,new Date)}async ensureSessionPath(t,e=new Date){let s=this.getSessionPath(t,e);return await U(s),s}async listSessions(t,e=null,s=null){let n=w.join(this.getGlobalProjectPath(t),"sessions"),i=[];try{let o=await Nt.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),p=await Nt.readdir(u,{withFileTypes:!0});for(let m of p){if(!m.isDirectory()||s&&m.name!==s.toString().padStart(2,"0"))continue;let d=w.join(u,m.name),h=await Nt.readdir(d,{withFileTypes:!0});for(let y of h)y.isDirectory()&&i.push({year:a.name,month:m.name,day:y.name,path:w.join(d,y.name),date:new Date(`${a.name}-${m.name}-${y.name}`)})}}return i.sort((a,u)=>u.date.getTime()-a.date.getTime()),i}catch{return[]}}async getSessionsInRange(t,e,s=new Date){return(await this.listSessions(t)).filter(i=>i.date>=e&&i.date<=s)}getFilePath(t,e,s){return w.join(this.getGlobalProjectPath(t),e,s)}async listProjects(){try{return await this.ensureGlobalStructure(),(await Nt.readdir(this.globalProjectsDir,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async projectExists(t){return await ee(this.getGlobalProjectPath(t))}getDisplayPath(t){let e=fe.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")}async getAgentDir(){return(await(Ct(),Qt(At)).getActiveProvider()).configDir}async getAgentSettingsPath(){let t=await(Ct(),Qt(At)).getActiveProvider();return(Ct(),Qt(At)).getGlobalSettingsPath(t.name)}getClaudeDir(){return w.join(fe.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 xs(t,e)}getWikiPathWithProjectHash(t,e){return Ps(t,e)}getLegacyWikiPath(t){return Rs(t)}async detectMonorepo(t){return se(t)}async discoverMonorepoPackages(t,e){return re(t,e)}async findContainingPackage(t,e){return Es(t,e)}async findMonorepoRoot(t){return Ss(t)}},fi=new he,v=fi});var qs,Gs=k(()=>{"use strict";qs=`
|
|
14
|
+
`),c="",u="",p="",m=!1;for(let d of o)d.startsWith("worktree ")?c=d.replace("worktree ","").trim():d.startsWith("HEAD ")?u=d.replace("HEAD ","").trim():d.startsWith("branch ")?p=d.replace("branch refs/heads/","").trim():d==="bare"?m=!0:d==="detached"&&(p="(detached)");if(c){let d=c===e||m;s.push({path:c,branch:p,commit:u,isMain:d,slug:d?"main":$.basename(c)})}}return s}},vs=new ie,ei=vs});import ce from"node:os";import W from"node:path";async function xs(r,t){if(t&&t.trim().length>0)return ri(r,t);let e=await si(r),n=W.basename(W.resolve(e)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project";return W.join(ce.homedir(),"Documents","prjct",n)}function Ps(r,t){let s=W.basename(W.resolve(r)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project",n=t.replace(/-/g,"").slice(0,8);return W.join(ce.homedir(),"Documents","prjct",`${s}-${n}`)}function Rs(r){return W.join(r,".prjct","wiki")}async function si(r){try{let{worktreeService:t}=await Promise.resolve().then(()=>(ae(),oe));return await t.detect(r)&&await t.getMainWorktree(r)||r}catch{return r}}function ri(r,t){let e=t.trim();return(e.startsWith("~/")||e==="~")&&(e=W.join(ce.homedir(),e.slice(1))),W.isAbsolute(e)||(e=W.resolve(r,e)),e}var As=k(()=>{"use strict";a(xs,"getWikiPath");a(Ps,"getWikiPathWithProjectHash");a(Rs,"getLegacyWikiPath");a(si,"resolveProjectRootPath");a(ri,"resolveVaultOverride")});var Cs=k(()=>{"use strict"});import{z as dt}from"zod";function Ns(r,t){let e=r.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<3;n++){let i=e[n]??0,o=s[n]??0;if(i<o)return-1;if(i>o)return 1}return 0}var ue,le=k(()=>{"use strict";ue=dt.object({provider:dt.string(),model:dt.string(),cliVersion:dt.string().optional(),recordedAt:dt.string()});a(Ns,"compareSemver")});function Is(r,t){let e=typeof r=="string"?new Date(r).getTime():r;return Date.now()-e>t}var Pt,pe=k(()=>{"use strict";a(Is,"isExpired");Pt=class{static{a(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((s,n)=>s[1].timestamp-n[1].timestamp).slice(0,this.cache.size-this.maxSize);for(let[s]of e)this.cache.delete(s)}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 ni from"node:fs/promises";import ii from"node:os";import Ds from"node:path";async function Os(){try{let r=await ni.readFile(Ls,"utf-8"),t=JSON.parse(r);return!t.timestamp||!t.detection||!t.detection.claude||!t.detection.gemini||!t.detection.codex||Is(t.timestamp,ai)?null:t.detection}catch{return null}}async function js(r){let t={timestamp:new Date().toISOString(),detection:r};await F(Ls,t)}var oi,Ls,ai,Ms=k(()=>{"use strict";pe();X();oi=Ds.join(ii.homedir(),".prjct-cli","cache"),Ls=Ds.join(oi,"providers.json"),ai=10*60*1e3;a(Os,"readProviderCache");a(js,"writeProviderCache")});var At={};K(At,{ClaudeProvider:()=>Rt,CursorProvider:()=>Xs,GeminiProvider:()=>me,Providers:()=>mt,detectAllProviders:()=>ge,detectAntigravity:()=>di,detectCodex:()=>Hs,detectProvider:()=>de,getActiveProvider:()=>li,getProviderBranding:()=>pi,selectProvider:()=>mi,validateCliVersion:()=>Bs});import J from"node:os";import B from"node:path";async function Ws(r){try{let{stdout:t}=await b(`which ${r}`,{timeout:2e3});return t.trim()}catch{return null}}async function ui(r){try{let{stdout:t}=await b(`${r} --version`,{timeout:2e3}),e=t.match(/\d+\.\d+\.\d+/);return e?e[0]:t.trim()}catch{return null}}async function de(r){let t=mt[r];if(!t.cliCommand)return{installed:!1};let e=await Ws(t.cliCommand);if(!e)return{installed:!1};let s=await ui(t.cliCommand),n=Bs(r,s||void 0);return{installed:!0,version:s||void 0,path:e,versionWarning:n||void 0}}function Bs(r,t){let e=mt[r];return!e.minCliVersion||!t?null:Ns(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 ge(r=!1){if(!r){let o=await Os();if(o)return o}let[t,e,s]=await Promise.all([de("claude"),de("gemini"),Hs()]),n={installed:s.installed},i={claude:t,gemini:e,codex:n};return await js(i).catch(()=>{}),i}async function li(r){if(r&&mt[r])return mt[r];let t=await ge();return t.claude.installed&&!t.gemini.installed?Rt:t.gemini.installed&&!t.claude.installed?me:Rt}function pi(r){return{commitFooter:"Generated with [p/](https://www.prjct.app/)",signature:{claude:"\u26A1 prjct + Claude",gemini:"\u26A1 prjct + Gemini",cursor:"\u26A1 prjct + Cursor",antigravity:"\u26A1 prjct + Antigravity",windsurf:"\u26A1 prjct + Windsurf",codex:"\u26A1 prjct + Codex"}[r]||"\u26A1 prjct"}}async function di(){let r=Us.configDir;if(!r)return{installed:!1,skillInstalled:!1};let t=B.join(r,"skills","prjct","SKILL.md"),[e,s]=await Promise.all([A(r),A(t)]);return{installed:e,skillInstalled:s,configPath:e?r:void 0}}async function Hs(){let r=$s.configDir;if(!r)return{installed:!1,skillInstalled:!1};let t=await Ws("codex"),e=B.join(r,"skills","prjct","SKILL.md"),s=await A(e),n=!!t;return{installed:n,skillInstalled:s,configPath:n?r:void 0}}async function mi(){let r=await ge(),t=r.claude.installed,e=r.gemini.installed;return!t&&!e?{provider:"claude",userSelected:!1,detection:r}:t&&!e?{provider:"claude",userSelected:!1,detection:r}:e&&!t?{provider:"gemini",userSelected:!1,detection:r}:{provider:"claude",userSelected:!0,detection:r}}var Rt,me,Us,Xs,ci,$s,mt,Ct=k(()=>{"use strict";Cs();le();st();X();Ms();Rt={name:"claude",displayName:"Claude Code",cliCommand:"claude",configDir:B.join(J.homedir(),".claude"),contextFile:"CLAUDE.md",skillsDir:B.join(J.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"},me={name:"gemini",displayName:"Gemini CLI",cliCommand:"gemini",configDir:B.join(J.homedir(),".gemini"),contextFile:"GEMINI.md",skillsDir:B.join(J.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"},Us={name:"antigravity",displayName:"Google Antigravity",cliCommand:null,configDir:B.join(J.homedir(),".gemini","antigravity"),contextFile:"ANTIGRAVITY.md",skillsDir:B.join(J.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"},Xs={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"},ci={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"},$s={name:"codex",displayName:"OpenAI Codex",cliCommand:"codex",configDir:B.join(J.homedir(),".codex"),contextFile:"AGENTS.md",skillsDir:B.join(J.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"},mt={claude:Rt,gemini:me,cursor:Xs,antigravity:Us,windsurf:ci,codex:$s};a(Ws,"whichCommand");a(ui,"getCliVersion");a(de,"detectProvider");a(Bs,"validateCliVersion");a(ge,"detectAllProviders");a(li,"getActiveProvider");a(pi,"getProviderBranding");a(di,"detectAntigravity");a(Hs,"detectCodex");a(mi,"selectProvider")});import gi from"node:crypto";import Nt from"node:fs/promises";import fe from"node:os";import w from"node:path";var he,fi,v,gt=k(()=>{"use strict";C();X();ws();As();he=class{static{a(this,"PathManager")}globalBaseDir;globalProjectsDir;globalConfigDir;constructor(){let t=process.env.PRJCT_CLI_HOME?.trim();this.globalBaseDir=t?w.resolve(t):w.join(fe.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 gi.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 ee(this.getLegacyPrjctPath(t))}async hasConfig(t){return await A(this.getLocalConfigPath(t))}async ensureGlobalStructure(){await U(this.globalBaseDir),await U(this.globalProjectsDir),await U(this.globalConfigDir)}async ensureProjectStructure(t){await this.ensureGlobalStructure();let e=this.getGlobalProjectPath(t),s=["core","progress","planning","analysis","memory"];for(let n of s)await U(w.join(e,n));return await U(w.join(e,"planning","tasks")),await U(w.join(e,"sessions")),e}getSessionPath(t,e=new Date){let{year:s,month:n,day:i}=ls(e);return w.join(this.getGlobalProjectPath(t),"sessions",s,n,i)}getCurrentSessionPath(t){return this.getSessionPath(t,new Date)}async ensureSessionPath(t,e=new Date){let s=this.getSessionPath(t,e);return await U(s),s}async listSessions(t,e=null,s=null){let n=w.join(this.getGlobalProjectPath(t),"sessions"),i=[];try{let o=await Nt.readdir(n,{withFileTypes:!0});for(let c of o){if(!c.isDirectory()||e&&c.name!==e.toString())continue;let u=w.join(n,c.name),p=await Nt.readdir(u,{withFileTypes:!0});for(let m of p){if(!m.isDirectory()||s&&m.name!==s.toString().padStart(2,"0"))continue;let d=w.join(u,m.name),h=await Nt.readdir(d,{withFileTypes:!0});for(let y of h)y.isDirectory()&&i.push({year:c.name,month:m.name,day:y.name,path:w.join(d,y.name),date:new Date(`${c.name}-${m.name}-${y.name}`)})}}return i.sort((c,u)=>u.date.getTime()-c.date.getTime()),i}catch{return[]}}async getSessionsInRange(t,e,s=new Date){return(await this.listSessions(t)).filter(i=>i.date>=e&&i.date<=s)}getFilePath(t,e,s){return w.join(this.getGlobalProjectPath(t),e,s)}async listProjects(){try{return await this.ensureGlobalStructure(),(await Nt.readdir(this.globalProjectsDir,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async projectExists(t){return await ee(this.getGlobalProjectPath(t))}getDisplayPath(t){let e=fe.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")}async getAgentDir(){return(await(Ct(),Qt(At)).getActiveProvider()).configDir}async getAgentSettingsPath(){let t=await(Ct(),Qt(At)).getActiveProvider();return(Ct(),Qt(At)).getGlobalSettingsPath(t.name)}getClaudeDir(){return w.join(fe.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 xs(t,e)}getWikiPathWithProjectHash(t,e){return Ps(t,e)}getLegacyWikiPath(t){return Rs(t)}async detectMonorepo(t){return se(t)}async discoverMonorepoPackages(t,e){return re(t,e)}async findContainingPackage(t,e){return Es(t,e)}async findMonorepoRoot(t){return Ss(t)}},fi=new he,v=fi});var qs,Gs=k(()=>{"use strict";qs=`
|
|
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 Ys,Js=k(()=>{"use strict";Gs();Ys=[{version:1,name:"initial-schema",up:
|
|
228
|
+
`});var Ys,Js=k(()=>{"use strict";Gs();Ys=[{version:1,name:"initial-schema",up:a(r=>{r.run(qs)},"up")},{version:2,name:"archives-table",up:a(r=>{r.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:
|
|
245
|
+
`)},"up")},{version:3,name:"workflow-rules-table",up:a(r=>{r.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:
|
|
263
|
+
`)},"up")},{version:4,name:"custom-workflows-table",up:a(r=>{r.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:
|
|
288
|
+
`)},"up")},{version:5,name:"llm-analysis-table",up:a(r=>{r.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:
|
|
304
|
+
`)},"up")},{version:6,name:"context-feedback-table",up:a(r=>{r.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:
|
|
322
|
+
`)},"up")},{version:7,name:"sessions-table",up:a(r=>{r.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:
|
|
342
|
+
`)},"up")},{version:8,name:"task-token-tracking",up:a(r=>{r.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:
|
|
348
|
+
`)},"up")},{version:9,name:"context-health-tables",up:a(r=>{r.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:
|
|
378
|
+
`)},"up")},{version:10,name:"fts5-memories",up:a(r=>{r.run(`
|
|
379
379
|
-- =======================================================================
|
|
380
380
|
-- Memories: Tagged, searchable memory store (replaces memories.json)
|
|
381
381
|
-- =======================================================================
|
|
@@ -428,7 +428,7 @@ CREATE TABLE velocity_sprints (
|
|
|
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 n of e.memories)s.run(n.id,"_migrated",n.title,n.content,(n.tags||[]).join(","),null,n.userTriggered?1:0,n.confidence??null,n.observationCount??0,n.createdAt,n.updatedAt)}}}catch{}},"up")},{version:11,name:"agent-sessions",up:
|
|
431
|
+
`);for(let n of e.memories)s.run(n.id,"_migrated",n.title,n.content,(n.tags||[]).join(","),null,n.userTriggered?1:0,n.confidence??null,n.observationCount??0,n.createdAt,n.updatedAt)}}}catch{}},"up")},{version:11,name:"agent-sessions",up:a(r=>{r.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{r.run("ALTER TABLE memories ADD COLUMN session_id TEXT")}catch{}},"up")},{version:12,name:"task-body-and-comments",up:
|
|
464
|
+
`);try{r.run("ALTER TABLE memories ADD COLUMN session_id TEXT")}catch{}},"up")},{version:12,name:"task-body-and-comments",up:a(r=>{try{r.run("ALTER TABLE queue_tasks ADD COLUMN body TEXT")}catch{}r.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:
|
|
475
|
+
`)},"up")},{version:13,name:"workflow-rules-v2",up:a(r=>{try{r.run("ALTER TABLE workflow_rules ADD COLUMN when_expr TEXT")}catch{}try{r.run("ALTER TABLE workflow_rules ADD COLUMN parallel INTEGER NOT NULL DEFAULT 1")}catch{}r.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:
|
|
485
|
+
`)},"up")},{version:14,name:"workflow-rules-trust-source",up:a(r=>{try{r.run("ALTER TABLE workflow_rules ADD COLUMN trust_source TEXT NOT NULL DEFAULT 'local'")}catch{}},"up")},{version:15,name:"disable-orphan-workflow-rules",up:a(r=>{let e=["pause","resume","reopen","next","dash","bug","idea","linear","jira","tokens","velocity","plan"].map(s=>`'${s}'`).join(",");r.run(`UPDATE workflow_rules SET enabled = 0 WHERE command IN (${e}) AND enabled = 1`)},"up")},{version:16,name:"specs-and-task-linkage",up:a(r=>{r.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{r.run("ALTER TABLE tasks ADD COLUMN linked_spec_id TEXT"),r.run("CREATE INDEX IF NOT EXISTS idx_tasks_spec ON tasks(linked_spec_id)")}catch{}},"up")},{version:17,name:"sync-engine-wire-format",up:
|
|
501
|
+
`);try{r.run("ALTER TABLE tasks ADD COLUMN linked_spec_id TEXT"),r.run("CREATE INDEX IF NOT EXISTS idx_tasks_spec ON tasks(linked_spec_id)")}catch{}},"up")},{version:17,name:"sync-engine-wire-format",up:a(r=>{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,s]of t)try{r.run(`ALTER TABLE events ADD COLUMN ${e} ${s}`)}catch{}try{r.run("CREATE INDEX IF NOT EXISTS idx_events_server_id ON events(server_event_id)"),r.run("CREATE INDEX IF NOT EXISTS idx_events_entity ON events(entity_type, entity_id)"),r.run("CREATE INDEX IF NOT EXISTS idx_events_device ON events(device_id)")}catch{}r.run(`
|
|
502
502
|
CREATE TABLE IF NOT EXISTS sync_pending (
|
|
503
503
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
504
504
|
project_id TEXT NOT NULL,
|
|
@@ -523,86 +523,94 @@ 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:
|
|
526
|
+
`)},"up")},{version:18,name:"specs-shipped-sha",up:a(r=>{try{r.run("ALTER TABLE specs ADD COLUMN shipped_sha TEXT")}catch{}},"up")},{version:19,name:"sync-applied-hashes",up:a(r=>{r.run(`
|
|
527
|
+
CREATE TABLE IF NOT EXISTS sync_applied_hashes (
|
|
528
|
+
entity_type TEXT NOT NULL,
|
|
529
|
+
entity_id TEXT NOT NULL,
|
|
530
|
+
content_hash TEXT NOT NULL,
|
|
531
|
+
applied_at TEXT NOT NULL,
|
|
532
|
+
PRIMARY KEY (entity_type, entity_id)
|
|
533
|
+
);
|
|
534
|
+
`)},"up")}]});function hi(){return typeof globalThis<"u"&&"Bun"in globalThis?"bun":"node"}function zs(){return hi()==="bun"}var Ks=k(()=>{"use strict";a(hi,"detectRuntime");a(zs,"isBun")});function Vs(r){if(zs()){let{Database:n}=os("bun:sqlite");return new n(r,{create:!0})}let t=os("better-sqlite3"),e=new t(r),s=e.exec.bind(e);return e.run=n=>s(n),e}var Qs=k(()=>{"use strict";Ks();a(Vs,"openDatabase")});import ye from"node:fs";import Zs from"node:path";var yi,Te,E,T,j=k(()=>{"use strict";gt();Js();Qs();yi=3,Te=class{static{a(this,"PrjctDatabase")}connections=new Map;accessOrder=[];statementCache=new WeakMap;prepareCached(t,e){let s=this.statementCache.get(t);s||(s=new Map,this.statementCache.set(t,s));let n=s.get(e);if(n)return n;let i=t.prepare(e);return s.set(e,i),i}getDbPath(t){return Zs.join(v.getGlobalProjectPath(t),"prjct.db")}getDb(t){let e=this.connections.get(t);if(e)return this.touchAccessOrder(t),e;this.connections.size>=yi&&this.evictLru();let s=this.getDbPath(t),n=Zs.dirname(s);ye.existsSync(n)||ye.mkdirSync(n,{recursive:!0});let i=Vs(s);return i.run("PRAGMA journal_mode = WAL"),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),this.connections.set(t,i),this.touchAccessOrder(t),i}close(t){if(t){let e=this.connections.get(t);e&&(e.close(),this.connections.delete(t),this.accessOrder=this.accessOrder.filter(s=>s!==t))}else this.connections.forEach(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&&(e.close(),this.connections.delete(t))}checkpointAll(){for(let[t,e]of this.connections)try{e.run("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}}exists(t){return ye.existsSync(this.getDbPath(t))}getDoc(t,e){let s=this.getDb(t),n=this.prepareCached(s,"SELECT data FROM kv_store WHERE key = ?").get(e);return n?JSON.parse(n.data):null}setDoc(t,e,s){let n=this.getDb(t),i=JSON.stringify(s),o=new Date().toISOString();this.prepareCached(n,"INSERT OR REPLACE INTO kv_store (key, data, updated_at) VALUES (?, ?, ?)").run(e,i,o)}deleteDoc(t,e){let s=this.getDb(t);this.prepareCached(s,"DELETE FROM kv_store WHERE key = ?").run(e)}hasDoc(t,e){let s=this.getDb(t);return this.prepareCached(s,"SELECT 1 FROM kv_store WHERE key = ?").get(e)!==null}appendEvent(t,e,s,n){let i=this.getDb(t),o=new Date().toISOString();this.prepareCached(i,"INSERT INTO events (type, task_id, data, timestamp) VALUES (?, ?, ?, ?)").run(e,n??null,JSON.stringify(s),o)}getEvents(t,e,s=100){let n=this.getDb(t);return e?this.prepareCached(n,"SELECT * FROM events WHERE type = ? ORDER BY id DESC LIMIT ?").all(e,s):this.prepareCached(n,"SELECT * FROM events ORDER BY id DESC LIMIT ?").all(s)}query(t,e,...s){let n=this.getDb(t);return this.prepareCached(n,e).all(...s)}run(t,e,...s){let n=this.getDb(t);this.prepareCached(n,e).run(...s)}get(t,e,...s){let n=this.getDb(t);return this.prepareCached(n,e).get(...s)??null}transaction(t,e){let s=this.getDb(t);return s.transaction(e)(s)}runMigrations(t){t.run(`
|
|
527
535
|
CREATE TABLE IF NOT EXISTS _migrations (
|
|
528
536
|
version INTEGER PRIMARY KEY,
|
|
529
537
|
name TEXT NOT NULL,
|
|
530
538
|
applied_at TEXT NOT NULL
|
|
531
539
|
)
|
|
532
|
-
`);let e=new Set(t.prepare("SELECT version FROM _migrations").all().map(s=>s.version));for(let s of Ys)e.has(s.version)||t.transaction(()=>{s.up(t),t.prepare("INSERT INTO _migrations (version, name, applied_at) VALUES (?, ?, ?)").run(s.version,s.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}},E=new Te,T=E});function Ri(r){return r instanceof be}function _e(r){return Ri(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var be,cr=k(()=>{"use strict";be=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(Ri,"isPrjctError");c(_e,"getErrorMessage")});import ve from"node:fs";import Lt from"node:path";function ur(){if(ht)return ht;let r=__dirname;for(let t=0;t<5;t++){let e=Lt.join(r,"package.json");if(ve.existsSync(e))try{if(JSON.parse(ve.readFileSync(e,"utf-8")).name==="prjct-cli")return ht=r,r}catch{}r=Lt.dirname(r)}return ht=Lt.join(__dirname,"..","..",".."),ht}function Ai(){if(nt)return nt;let r=process.env.PRJCT_VERSION;if(r&&/^\d+\.\d+\.\d+/.test(r))return nt=r,nt;try{let t=Lt.join(ur(),"package.json");return nt=JSON.parse(ve.readFileSync(t,"utf-8")).version,nt}catch(t){return process.env.PRJCT_DEBUG==="1"&&console.error("Failed to read version from package.json:",ds(t)),"0.0.0"}}var nt,ht,xe,Qc,lr=k(()=>{"use strict";V();nt=null,ht=null;c(ur,"getPackageRoot");c(Ai,"getVersion");xe=Ai(),Qc=ur()});async function Ot(r){try{let{stdout:t}=await b(r,{timeout:5e3});return{success:!0,output:t.trim()}}catch{return{success:!1,output:""}}}async function Ci(){let r=await Ot("gh api user --jq .login");return r.success&&r.output||(r=await Ot("git config --global github.user"),r.success&&r.output)?r.output:null}async function Ni(){let r=await Ot("git config user.name");return r.success&&r.output?r.output:null}async function Ii(){let r=await Ot("git config user.email");return r.success&&r.output?r.output:null}async function pr(){let[r,t,e]=await Promise.all([Ci(),Ni(),Ii()]);return{github:r,email:e,name:t||r||"Unknown"}}var dr=k(()=>{"use strict";st();c(Ot,"execCommand");c(Ci,"detectGitHubUsername");c(Ni,"detectGitName");c(Ii,"detectGitEmail");c(pr,"detect")});var gr={};K(gr,{default:()=>H});import Pe from"node:fs/promises";import Li from"node:path";import*as jt from"jsonc-parser";function mr(r){let t=[],e=jt.parse(r,t,{allowTrailingComma:!0,disallowComments:!1});if(t.length>0){let s=t[0];throw new SyntaxError(`JSON parse error at offset ${s.offset}: ${jt.printParseErrorCode(s.error)}`)}return e}var Re,Oi,H,yt=k(()=>{"use strict";cr();V();C();X();lr();dr();gt();c(mr,"parseJsonc");Re=class{static{c(this,"ConfigManager")}async readConfig(t){try{let e=v.getLocalConfigPath(t),s=await Pe.readFile(e,"utf-8");return mr(s)}catch(e){return L(e)||console.warn(`Warning: Could not read config at ${t}: ${_e(e)}`),null}}async writeConfig(t,e){let s=v.getLocalConfigPath(t);await F(s,e)}async readGlobalConfig(t){try{let e=v.getGlobalProjectConfigPath(t),s=await Pe.readFile(e,"utf-8");return mr(s)}catch(e){return L(e)||console.warn(`Warning: Could not read global config for ${t}: ${_e(e)}`),null}}async writeGlobalConfig(t,e){let s=v.getGlobalProjectConfigPath(t);await F(s,e)}async ensureGlobalConfig(t){let e=await this.readGlobalConfig(t);if(!e){let s=g();e={projectId:t,authors:[],version:xe,lastSync:s},await this.writeGlobalConfig(t,e)}return e}async createConfig(t,e){let s=v.generateProjectId(t),n=v.getGlobalProjectPath(s),i=v.getDisplayPath(n),o=g(),a={projectId:s,dataPath:i,showMetrics:!0};await this.writeConfig(t,a);let u={projectId:s,authors:[{name:e.name||"Unknown",email:e.email||"",github:e.github||"",firstContribution:o,lastActivity:o}],version:xe,created:o,lastSync:o};return await this.writeGlobalConfig(s,u),a}async updateLastSync(t){let e=await this.getProjectId(t),s=await this.readGlobalConfig(e);s&&(s.lastSync=g(),await this.writeGlobalConfig(e,s))}validateConfig(t){return!(!t||!t.projectId||!t.dataPath)}async needsMigration(t){if(!await v.hasLegacyStructure(t))return!1;if(!await v.hasConfig(t))return!0;let n=await this.readConfig(t);if(!n||!n.projectId)return!0;let i=v.getGlobalProjectPath(n.projectId);try{return(await Pe.readdir(Li.join(i,"core"))).length===0}catch(o){return L(o),!0}}async getProjectId(t){let e=await this.readConfig(t);if(e?.projectId)return e.projectId;try{let{worktreeService:s}=await Promise.resolve().then(()=>(ae(),oe));if(await s.detect(t)){let i=await s.getMainWorktree(t);if(i!==t){let o=await this.readConfig(i);if(o?.projectId)return o.projectId}}}catch{}return v.generateProjectId(t)}async findAuthor(t,e){let s=await this.readGlobalConfig(t);return!s||!s.authors?null:s.authors.find(n=>n.github===e)||null}async addAuthor(t,e){let s=await this.ensureGlobalConfig(t);if(s.authors.some(o=>o.github===e.github))return;let i=g();s.authors.push({name:e.name||"Unknown",email:e.email||"",github:e.github||"",firstContribution:i,lastActivity:i}),s.lastSync=i,await this.writeGlobalConfig(t,s)}async updateAuthorActivity(t,e){let s=await this.readGlobalConfig(t);if(!s||!s.authors)return;let n=s.authors.find(i=>i.github===e);n&&(n.lastActivity=g(),s.lastSync=n.lastActivity,await this.writeGlobalConfig(t,s))}async getCurrentAuthor(t){let e=await pr(),s=await this.getProjectId(t);return await this.addAuthor(s,{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 s=await this.readConfig(t);s&&(s.showMetrics=e,await this.writeConfig(t,s))}async getConfigWithDefaults(t){let e=await this.readConfig(t);if(e)return e;let s=v.generateProjectId(t);return{projectId:s,dataPath:v.getDisplayPath(v.getGlobalProjectPath(s))}}},Oi=new Re,H=Oi});import{z as l}from"zod";var Mi,Mt,Fi,Ui,Ae,yr,Tr,kr,Er,hr,Xi,$i,Wi,Sr,Bi,wr,Ft=k(()=>{"use strict";le();Mi=l.enum(["low","medium","high","critical"]),Mt=l.enum(["feature","bug","improvement","chore"]),Fi=l.enum(["active","backlog","previously_active"]),Ui=l.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),Ae=l.object({title:l.string(),description:l.string(),filesChanged:l.array(l.object({path:l.string(),action:l.enum(["created","modified","deleted"])})),whatWasDone:l.array(l.string()).min(1),outputForNextAgent:l.string().min(1),notes:l.string().optional()}),yr=l.object({output:l.string().min(1,"Subtask output is required"),summary:Ae}),Tr=l.object({id:l.string(),description:l.string(),domain:l.string(),agent:l.string(),status:Ui,dependsOn:l.array(l.string()),startedAt:l.string().optional(),completedAt:l.string().optional(),output:l.string().optional(),summary:Ae.optional(),skipReason:l.string().optional(),blockReason:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional()}),kr=l.object({completed:l.number(),total:l.number(),percentage:l.number()}),Er=l.object({id:l.string(),description:l.string(),type:Mt.optional(),startedAt:l.string(),sessionId:l.string(),featureId:l.string().optional(),subtasks:l.array(Tr).optional(),currentSubtaskIndex:l.number().optional(),subtaskProgress:kr.optional(),linearId:l.string().optional(),linearUuid:l.string().optional(),linkedSpecId:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional(),modelMetadata:ue.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional(),parentDescription:l.string().optional(),branch:l.string().optional(),prUrl:l.string().optional()}),hr=l.object({id:l.string(),description:l.string(),status:l.literal("paused"),startedAt:l.string(),pausedAt:l.string(),pauseReason:l.string().optional(),type:Mt.optional(),sessionId:l.string().optional(),featureId:l.string().optional(),subtasks:l.array(Tr).optional(),currentSubtaskIndex:l.number().optional(),subtaskProgress:kr.optional(),linearId:l.string().optional(),linearUuid:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional(),modelMetadata:ue.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional()}),Xi=l.object({stackConfirmed:l.array(l.string()).optional(),patternsDiscovered:l.array(l.string()).optional(),agentAccuracy:l.array(l.object({agent:l.string(),rating:l.enum(["helpful","neutral","inaccurate"]),note:l.string().optional()})).optional(),issuesEncountered:l.array(l.string()).optional()}),$i=l.object({taskId:l.string(),title:l.string(),classification:Mt,startedAt:l.string(),completedAt:l.string(),subtaskCount:l.number(),subtaskSummaries:l.array(Ae),outcome:l.string(),branchName:l.string(),linearId:l.string().optional(),linearUuid:l.string().optional(),prUrl:l.string().optional(),feedback:Xi.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional()}),Wi=Er.extend({workspaceId:l.string(),worktreePath:l.string().optional(),agentSessionId:l.string().optional(),jiraId:l.string().optional(),jiraUuid:l.string().optional(),dispatchedFrom:l.string().optional()}),Sr=l.object({currentTask:Er.nullable(),previousTask:hr.nullable().optional(),pausedTasks:l.array(hr).optional(),taskHistory:l.array($i).optional(),activeTasks:l.array(Wi).optional(),lastUpdated:l.string()}),Bi=l.object({id:l.string(),description:l.string(),body:l.string().optional(),priority:Mi,type:Mt,featureId:l.string().optional(),originFeature:l.string().optional(),completed:l.boolean(),completedAt:l.string().optional(),createdAt:l.string(),section:Fi,agent:l.string().optional(),groupName:l.string().optional(),groupId:l.string().optional()}),wr=l.object({tasks:l.array(Bi),lastUpdated:l.string()})});import Hi from"node:crypto";function q(){return Hi.randomUUID()}var kt=k(()=>{"use strict";c(q,"generateUUID")});var Ie,Z,br=k(()=>{"use strict";C();j();Ie=class{static{c(this,"SyncPendingStorage")}append(t,e){let s=g(),n=JSON.stringify(e);return e.entityType&&e.entityId&&e.contentHash&&T.run(t,`DELETE FROM sync_pending
|
|
540
|
+
`);let e=new Set(t.prepare("SELECT version FROM _migrations").all().map(s=>s.version));for(let s of Ys)e.has(s.version)||t.transaction(()=>{s.up(t),t.prepare("INSERT INTO _migrations (version, name, applied_at) VALUES (?, ?, ?)").run(s.version,s.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}},E=new Te,T=E});function Ri(r){return r instanceof be}function _e(r){return Ri(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var be,cr=k(()=>{"use strict";be=class extends Error{static{a(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)}};a(Ri,"isPrjctError");a(_e,"getErrorMessage")});import ve from"node:fs";import Lt from"node:path";function ur(){if(ht)return ht;let r=__dirname;for(let t=0;t<5;t++){let e=Lt.join(r,"package.json");if(ve.existsSync(e))try{if(JSON.parse(ve.readFileSync(e,"utf-8")).name==="prjct-cli")return ht=r,r}catch{}r=Lt.dirname(r)}return ht=Lt.join(__dirname,"..","..",".."),ht}function Ai(){if(nt)return nt;let r=process.env.PRJCT_VERSION;if(r&&/^\d+\.\d+\.\d+/.test(r))return nt=r,nt;try{let t=Lt.join(ur(),"package.json");return nt=JSON.parse(ve.readFileSync(t,"utf-8")).version,nt}catch(t){return process.env.PRJCT_DEBUG==="1"&&console.error("Failed to read version from package.json:",ds(t)),"0.0.0"}}var nt,ht,xe,Qc,lr=k(()=>{"use strict";V();nt=null,ht=null;a(ur,"getPackageRoot");a(Ai,"getVersion");xe=Ai(),Qc=ur()});async function Ot(r){try{let{stdout:t}=await b(r,{timeout:5e3});return{success:!0,output:t.trim()}}catch{return{success:!1,output:""}}}async function Ci(){let r=await Ot("gh api user --jq .login");return r.success&&r.output||(r=await Ot("git config --global github.user"),r.success&&r.output)?r.output:null}async function Ni(){let r=await Ot("git config user.name");return r.success&&r.output?r.output:null}async function Ii(){let r=await Ot("git config user.email");return r.success&&r.output?r.output:null}async function pr(){let[r,t,e]=await Promise.all([Ci(),Ni(),Ii()]);return{github:r,email:e,name:t||r||"Unknown"}}var dr=k(()=>{"use strict";st();a(Ot,"execCommand");a(Ci,"detectGitHubUsername");a(Ni,"detectGitName");a(Ii,"detectGitEmail");a(pr,"detect")});var gr={};K(gr,{default:()=>H});import Pe from"node:fs/promises";import Li from"node:path";import*as jt from"jsonc-parser";function mr(r){let t=[],e=jt.parse(r,t,{allowTrailingComma:!0,disallowComments:!1});if(t.length>0){let s=t[0];throw new SyntaxError(`JSON parse error at offset ${s.offset}: ${jt.printParseErrorCode(s.error)}`)}return e}var Re,Oi,H,yt=k(()=>{"use strict";cr();V();C();X();lr();dr();gt();a(mr,"parseJsonc");Re=class{static{a(this,"ConfigManager")}async readConfig(t){try{let e=v.getLocalConfigPath(t),s=await Pe.readFile(e,"utf-8");return mr(s)}catch(e){return L(e)||console.warn(`Warning: Could not read config at ${t}: ${_e(e)}`),null}}async writeConfig(t,e){let s=v.getLocalConfigPath(t);await F(s,e)}async readGlobalConfig(t){try{let e=v.getGlobalProjectConfigPath(t),s=await Pe.readFile(e,"utf-8");return mr(s)}catch(e){return L(e)||console.warn(`Warning: Could not read global config for ${t}: ${_e(e)}`),null}}async writeGlobalConfig(t,e){let s=v.getGlobalProjectConfigPath(t);await F(s,e)}async ensureGlobalConfig(t){let e=await this.readGlobalConfig(t);if(!e){let s=g();e={projectId:t,authors:[],version:xe,lastSync:s},await this.writeGlobalConfig(t,e)}return e}async createConfig(t,e){let s=v.generateProjectId(t),n=v.getGlobalProjectPath(s),i=v.getDisplayPath(n),o=g(),c={projectId:s,dataPath:i,showMetrics:!0};await this.writeConfig(t,c);let u={projectId:s,authors:[{name:e.name||"Unknown",email:e.email||"",github:e.github||"",firstContribution:o,lastActivity:o}],version:xe,created:o,lastSync:o};return await this.writeGlobalConfig(s,u),c}async updateLastSync(t){let e=await this.getProjectId(t),s=await this.readGlobalConfig(e);s&&(s.lastSync=g(),await this.writeGlobalConfig(e,s))}validateConfig(t){return!(!t||!t.projectId||!t.dataPath)}async needsMigration(t){if(!await v.hasLegacyStructure(t))return!1;if(!await v.hasConfig(t))return!0;let n=await this.readConfig(t);if(!n||!n.projectId)return!0;let i=v.getGlobalProjectPath(n.projectId);try{return(await Pe.readdir(Li.join(i,"core"))).length===0}catch(o){return L(o),!0}}async getProjectId(t){let e=await this.readConfig(t);if(e?.projectId)return e.projectId;try{let{worktreeService:s}=await Promise.resolve().then(()=>(ae(),oe));if(await s.detect(t)){let i=await s.getMainWorktree(t);if(i!==t){let o=await this.readConfig(i);if(o?.projectId)return o.projectId}}}catch{}return v.generateProjectId(t)}async findAuthor(t,e){let s=await this.readGlobalConfig(t);return!s||!s.authors?null:s.authors.find(n=>n.github===e)||null}async addAuthor(t,e){let s=await this.ensureGlobalConfig(t);if(s.authors.some(o=>o.github===e.github))return;let i=g();s.authors.push({name:e.name||"Unknown",email:e.email||"",github:e.github||"",firstContribution:i,lastActivity:i}),s.lastSync=i,await this.writeGlobalConfig(t,s)}async updateAuthorActivity(t,e){let s=await this.readGlobalConfig(t);if(!s||!s.authors)return;let n=s.authors.find(i=>i.github===e);n&&(n.lastActivity=g(),s.lastSync=n.lastActivity,await this.writeGlobalConfig(t,s))}async getCurrentAuthor(t){let e=await pr(),s=await this.getProjectId(t);return await this.addAuthor(s,{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 s=await this.readConfig(t);s&&(s.showMetrics=e,await this.writeConfig(t,s))}async getConfigWithDefaults(t){let e=await this.readConfig(t);if(e)return e;let s=v.generateProjectId(t);return{projectId:s,dataPath:v.getDisplayPath(v.getGlobalProjectPath(s))}}},Oi=new Re,H=Oi});import{z as l}from"zod";var Mi,Mt,Fi,Ui,Ae,yr,Tr,kr,Er,hr,Xi,$i,Wi,Sr,Bi,wr,Ft=k(()=>{"use strict";le();Mi=l.enum(["low","medium","high","critical"]),Mt=l.enum(["feature","bug","improvement","chore"]),Fi=l.enum(["active","backlog","previously_active"]),Ui=l.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),Ae=l.object({title:l.string(),description:l.string(),filesChanged:l.array(l.object({path:l.string(),action:l.enum(["created","modified","deleted"])})),whatWasDone:l.array(l.string()).min(1),outputForNextAgent:l.string().min(1),notes:l.string().optional()}),yr=l.object({output:l.string().min(1,"Subtask output is required"),summary:Ae}),Tr=l.object({id:l.string(),description:l.string(),domain:l.string(),agent:l.string(),status:Ui,dependsOn:l.array(l.string()),startedAt:l.string().optional(),completedAt:l.string().optional(),output:l.string().optional(),summary:Ae.optional(),skipReason:l.string().optional(),blockReason:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional()}),kr=l.object({completed:l.number(),total:l.number(),percentage:l.number()}),Er=l.object({id:l.string(),description:l.string(),type:Mt.optional(),startedAt:l.string(),sessionId:l.string(),featureId:l.string().optional(),subtasks:l.array(Tr).optional(),currentSubtaskIndex:l.number().optional(),subtaskProgress:kr.optional(),linearId:l.string().optional(),linearUuid:l.string().optional(),linkedSpecId:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional(),modelMetadata:ue.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional(),parentDescription:l.string().optional(),branch:l.string().optional(),prUrl:l.string().optional()}),hr=l.object({id:l.string(),description:l.string(),status:l.literal("paused"),startedAt:l.string(),pausedAt:l.string(),pauseReason:l.string().optional(),type:Mt.optional(),sessionId:l.string().optional(),featureId:l.string().optional(),subtasks:l.array(Tr).optional(),currentSubtaskIndex:l.number().optional(),subtaskProgress:kr.optional(),linearId:l.string().optional(),linearUuid:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional(),modelMetadata:ue.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional()}),Xi=l.object({stackConfirmed:l.array(l.string()).optional(),patternsDiscovered:l.array(l.string()).optional(),agentAccuracy:l.array(l.object({agent:l.string(),rating:l.enum(["helpful","neutral","inaccurate"]),note:l.string().optional()})).optional(),issuesEncountered:l.array(l.string()).optional()}),$i=l.object({taskId:l.string(),title:l.string(),classification:Mt,startedAt:l.string(),completedAt:l.string(),subtaskCount:l.number(),subtaskSummaries:l.array(Ae),outcome:l.string(),branchName:l.string(),linearId:l.string().optional(),linearUuid:l.string().optional(),prUrl:l.string().optional(),feedback:Xi.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional()}),Wi=Er.extend({workspaceId:l.string(),worktreePath:l.string().optional(),agentSessionId:l.string().optional(),jiraId:l.string().optional(),jiraUuid:l.string().optional(),dispatchedFrom:l.string().optional()}),Sr=l.object({currentTask:Er.nullable(),previousTask:hr.nullable().optional(),pausedTasks:l.array(hr).optional(),taskHistory:l.array($i).optional(),activeTasks:l.array(Wi).optional(),lastUpdated:l.string()}),Bi=l.object({id:l.string(),description:l.string(),body:l.string().optional(),priority:Mi,type:Mt,featureId:l.string().optional(),originFeature:l.string().optional(),completed:l.boolean(),completedAt:l.string().optional(),createdAt:l.string(),section:Fi,agent:l.string().optional(),groupName:l.string().optional(),groupId:l.string().optional()}),wr=l.object({tasks:l.array(Bi),lastUpdated:l.string()})});import Hi from"node:crypto";function q(){return Hi.randomUUID()}var kt=k(()=>{"use strict";a(q,"generateUUID")});var Ie,Z,br=k(()=>{"use strict";C();j();Ie=class{static{a(this,"SyncPendingStorage")}append(t,e){let s=g(),n=JSON.stringify(e);return e.entityType&&e.entityId&&e.contentHash&&T.run(t,`DELETE FROM sync_pending
|
|
533
541
|
WHERE project_id = ?
|
|
534
542
|
AND entity_type = ?
|
|
535
543
|
AND entity_id = ?
|
|
536
544
|
AND content_hash = ?`,t,e.entityType,e.entityId,e.contentHash),T.run(t,`INSERT INTO sync_pending
|
|
537
545
|
(project_id, entity_type, entity_id, event_type, content_hash, payload, enqueued_at)
|
|
538
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`,t,e.entityType??null,e.entityId??null,e.eventType??null,e.contentHash??null,n,s),{id:T.get(t,"SELECT last_insert_rowid() AS id")?.id??0,event:e,enqueuedAt:s}}list(t,e){let s=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?T.query(t,s,t,e):T.query(t,s,t)).map(i=>this.rowToEntry(i))}count(t){return T.get(t,"SELECT COUNT(*) AS n FROM sync_pending WHERE project_id = ?",t)?.n??0}clearUpTo(t,e){if(e<=0)return 0;let s=this.count(t);return T.run(t,"DELETE FROM sync_pending WHERE project_id = ? AND id <= ?",t,e),s-this.count(t)}clearAll(t){T.run(t,"DELETE FROM sync_pending WHERE project_id = ?",t)}clearByIds(t,e){if(e.length===0)return;let s=e.map(()=>"?").join(",");T.run(t,`DELETE FROM sync_pending WHERE project_id = ? AND id IN (${s})`,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}}},Z=new Ie});var De,Ut,Le=k(()=>{"use strict";gt();br();C();X();De=class{static{c(this,"SyncEventBus")}async publish(t){Z.append(t.projectId,t)}async getPending(t){return Z.list(t).map(e=>e.event)}async clearPending(t){Z.clearAll(t)}async getPendingEntries(t){return Z.list(t)}async clearPendingUpTo(t,e){return Z.clearUpTo(t,e)}async clearPendingByIds(t,e){Z.clearByIds(t,e)}async updateLastSync(t){let e=v.getLastSyncPath(t),s={timestamp:g(),success:!0};await F(e,s)}async getLastSync(t){let e=v.getLastSyncPath(t);return await vt(e,null)}},Ut=new De});var je={};K(je,{default:()=>Ji});import qi from"node:crypto";import _r from"node:fs/promises";import vr from"node:os";import Gi from"node:path";function Pr(){return qi.randomUUID()}var Rr,xr,Oe,Yi,Ji,Me=k(()=>{"use strict";gt();X();Rr="https://api.prjct.app",xr={apiKey:null,apiUrl:Rr,userId:null,email:null,lastAuth:null};c(Pr,"freshDeviceId");Oe=class{static{c(this,"AuthConfigManager")}configPath;cachedConfig=null;constructor(){this.configPath=v.getAuthConfigPath()}getConfigPath(){return this.configPath}async read(){if(this.cachedConfig)return this.cachedConfig;let t=await vt(this.configPath),e=t??{...xr},s=!1;if(e.deviceId||(e.deviceId=Pr(),s=!0),e.hostname||(e.hostname=vr.hostname(),s=!0),this.cachedConfig=e,s&&t)try{await F(this.configPath,this.cachedConfig),await _r.chmod(this.configPath,384)}catch{}return this.cachedConfig}async getDeviceId(){return(await this.read()).deviceId??Pr()}async getHostname(){return(await this.read()).hostname??vr.hostname()}async write(t){let s={...await this.read(),...t,lastAuth:new Date().toISOString()};await U(Gi.dirname(this.configPath)),await F(this.configPath,s),await _r.chmod(this.configPath,384),this.cachedConfig=s}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||Rr}async saveAuth(t,e,s){await this.write({apiKey:t,userId:e,email:s})}async clearAuth(){this.cachedConfig={...xr},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}},Yi=new Oe,Ji=Yi});var Cr={};K(Cr,{_resetPublishHelperCache:()=>to,publishCRUD:()=>Ar,publishCRUDSync:()=>G});import zi from"node:crypto";function Vi(r){let t=r&&typeof r=="object"&&!Array.isArray(r)?JSON.stringify(Qi(r)):JSON.stringify(r);return zi.createHash("sha256").update(t).digest("hex")}function Qi(r){let t={};for(let e of Object.keys(r).sort())t[e]=r[e];return t}async function Zi(){if(Xt)return Xt;try{let{default:r}=await Promise.resolve().then(()=>(Me(),je)),t=r;if(typeof t.getDeviceId=="function"){let e=await t.getDeviceId();return Xt=e,e}return"unknown-device"}catch{return"unknown-device"}}function to(){Xt=null}async function Ar(r){try{let t=await Zi(),e=Vi(r.data),s={type:`${r.entityType}.${Ki[r.eventType]}`,path:[r.entityType,r.entityId],data:r.data,timestamp:new Date().toISOString(),projectId:r.projectId,entityType:r.entityType,entityId:r.entityId,eventType:r.eventType,contentHash:e,deviceId:t,originDeviceId:r.originDeviceId??t,revisionCount:r.revisionCount??1};await Ut.publish(s)}catch{}}function G(r){Ar(r)}var Ki,Xt,Et=k(()=>{"use strict";Le();Ki={upsert:"updated",delete:"deleted"};c(Vi,"hashPayload");c(Qi,"sortKeys");Xt=null;c(Zi,"resolveDeviceId");c(to,"_resetPublishHelperCache");c(Ar,"publishCRUD");c(G,"publishCRUDSync")});var St,Fe,it,$t=k(()=>{"use strict";kt();Et();C();j();St={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Fe=class{static{c(this,"ArchiveStorage")}archive(t,e){let s=q(),n=g();return E.run(t,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",s,e.entityType,e.entityId,JSON.stringify(e.entityData),e.summary??null,n,e.reason),G({projectId:t,entityType:"archives",entityId:s,eventType:"upsert",data:{id:s,entity_type:e.entityType,entity_id:e.entityId,summary:e.summary??null,reason:e.reason,archived_at:n}}),s}archiveMany(t,e){if(e.length===0)return 0;let s=g();return E.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(q(),o.entityType,o.entityId,JSON.stringify(o.entityData),o.summary??null,s,o.reason)}),e.length}getArchived(t,e,s=50){return e?E.query(t,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",e,s):E.query(t,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",s)}getStats(t){let e=E.query(t,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),s={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 s&&(s[i]=n.count),s.total+=n.count}return s}restore(t,e){let s=E.get(t,"SELECT * FROM archives WHERE id = ?",e);return s?(E.run(t,"DELETE FROM archives WHERE id = ?",e),JSON.parse(s.entity_data)):null}pruneOldArchives(t,e){let s=new Date(Date.now()-e*24*60*60*1e3).toISOString(),n=this.getTotalCount(t);E.run(t,"DELETE FROM archives WHERE archived_at < ?",s);let i=this.getTotalCount(t);return n-i}getTotalCount(t){return E.get(t,"SELECT COUNT(*) as count FROM archives")?.count??0}},it=new Fe});import io from"node:crypto";function oo(r){let[t,e]=r.split(".");return t?{entityType:t.endsWith("s")?t:`${t}s`,eventType:e==="deleted"||e==="archived"||e==="removed"?"delete":"upsert"}:{}}function ao(r){if(!r||typeof r!="object")return;let t=r;for(let e of["taskId","task_id","id","feature_id","featureId","specId","spec_id"]){let s=t[e];if(typeof s=="string"&&s.length>0)return s}}function co(r){let t=r&&typeof r=="object"&&!Array.isArray(r)?JSON.stringify(uo(r)):JSON.stringify(r);return io.createHash("sha256").update(t).digest("hex")}function uo(r){let t={};for(let e of Object.keys(r).sort())t[e]=r[e];return t}async function lo(){if(Wt)return Wt;try{let{default:r}=await Promise.resolve().then(()=>(Me(),je)),t=r;return typeof t.getDeviceId=="function"?(Wt=await t.getDeviceId(),Wt):"unknown-device"}catch{return"unknown-device"}}var Wt,ot,$e=k(()=>{"use strict";Le();pe();C();j();c(oo,"deriveEntityShape");c(ao,"entityIdOf");c(co,"hashPayload");c(uo,"sortKeys");Wt=null;c(lo,"_resolveDeviceId");ot=class{static{c(this,"StorageManager")}filename;cache;constructor(t,e){this.filename=t,this.cache=new Pt({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(t){let e=this.cache.get(t);if(e!==null)return e;try{let s=E.getDoc(t,this.getStoreKey());if(s!==null)return this.cache.set(t,s),s}catch{}return this.getDefault()}async write(t,e){E.setDoc(t,this.getStoreKey(),e),this.cache.set(t,e)}async update(t,e){let s=await this.read(t),n=e(s);return await this.write(t,n),n}async publishEvent(t,e,s){let n=oo(e),i={type:e,path:[this.filename.replace(".json","")],data:s,timestamp:g(),projectId:t,entityType:n.entityType,entityId:ao(s),eventType:n.eventType,contentHash:co(s),deviceId:await lo(),revisionCount:1};await Ut.publish(i)}async publishEntityEvent(t,e,s,n){let i=`${e}.${s}`,o={...n,timestamp:g()};await this.publishEvent(t,i,o)}async exists(t){try{return E.hasDoc(t,this.getStoreKey())}catch{return!1}}clearCache(t){t?this.cache.delete(t):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});var cn,un,ln,pn,dn=k(()=>{"use strict";cn={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"]},un=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".swift",".rb",".php",".c",".cpp",".h",".hpp",".cs",".vue",".svelte"]),ln=new Set(["node_modules",".git","dist","build",".next",".nuxt",".output","coverage",".cache","__pycache__",".pytest_cache","vendor","target",".turbo",".vercel"]),pn=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 po from"node:fs/promises";import Bt from"node:path";async function Ht(r,t,e={}){let s=Date.now(),n=e.maxFiles??30,i=e.minScore??.1,o=e.includeTests??!1,a=mo(r),u=await go(t),p=await fo(t),m=[];for(let h of u){if(!o&&yo(h))continue;let y=ho(h,a,p,e.historicalBoosts);y.score>=i&&m.push(y)}m.sort((h,y)=>y.score-h.score);let d=m.slice(0,n);return{files:d,metrics:{filesScanned:u.length,filesReturned:d.length,scanDuration:Date.now()-s}}}function mo(r){return r.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).filter(e=>!pn.has(e)&&e.length>2)}async function go(r){let t=[];async function e(s,n=""){try{let i=await po.readdir(s,{withFileTypes:!0});for(let o of i){let a=Bt.join(s,o.name),u=Bt.join(n,o.name);if(o.isDirectory()){if(ln.has(o.name)||o.name.startsWith("."))continue;await e(a,u)}else if(o.isFile()){let p=Bt.extname(o.name).toLowerCase();un.has(p)&&t.push(u)}}}catch(i){L(i)}}return c(e,"walk"),await e(r),t}async function fo(r){let t=new Map;try{let{stdout:e}=await b(`git log -30 --pretty=format:"%H %ct" --name-only | awk '
|
|
546
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,t,e.entityType??null,e.entityId??null,e.eventType??null,e.contentHash??null,n,s),{id:T.get(t,"SELECT last_insert_rowid() AS id")?.id??0,event:e,enqueuedAt:s}}list(t,e){let s=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?T.query(t,s,t,e):T.query(t,s,t)).map(i=>this.rowToEntry(i))}count(t){return T.get(t,"SELECT COUNT(*) AS n FROM sync_pending WHERE project_id = ?",t)?.n??0}clearUpTo(t,e){if(e<=0)return 0;let s=this.count(t);return T.run(t,"DELETE FROM sync_pending WHERE project_id = ? AND id <= ?",t,e),s-this.count(t)}clearAll(t){T.run(t,"DELETE FROM sync_pending WHERE project_id = ?",t)}clearByIds(t,e){if(e.length===0)return;let s=e.map(()=>"?").join(",");T.run(t,`DELETE FROM sync_pending WHERE project_id = ? AND id IN (${s})`,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}}},Z=new Ie});var De,Ut,Le=k(()=>{"use strict";gt();br();C();X();De=class{static{a(this,"SyncEventBus")}async publish(t){Z.append(t.projectId,t)}async getPending(t){return Z.list(t).map(e=>e.event)}async clearPending(t){Z.clearAll(t)}async getPendingEntries(t){return Z.list(t)}async clearPendingUpTo(t,e){return Z.clearUpTo(t,e)}async clearPendingByIds(t,e){Z.clearByIds(t,e)}async updateLastSync(t){let e=v.getLastSyncPath(t),s={timestamp:g(),success:!0};await F(e,s)}async getLastSync(t){let e=v.getLastSyncPath(t);return await vt(e,null)}},Ut=new De});var je={};K(je,{default:()=>Ji});import qi from"node:crypto";import _r from"node:fs/promises";import vr from"node:os";import Gi from"node:path";function Pr(){return qi.randomUUID()}var Rr,xr,Oe,Yi,Ji,Me=k(()=>{"use strict";gt();X();Rr="https://api.prjct.app",xr={apiKey:null,apiUrl:Rr,userId:null,email:null,lastAuth:null};a(Pr,"freshDeviceId");Oe=class{static{a(this,"AuthConfigManager")}configPath;cachedConfig=null;constructor(){this.configPath=v.getAuthConfigPath()}getConfigPath(){return this.configPath}async read(){if(this.cachedConfig)return this.cachedConfig;let t=await vt(this.configPath),e=t??{...xr},s=!1;if(e.deviceId||(e.deviceId=Pr(),s=!0),e.hostname||(e.hostname=vr.hostname(),s=!0),this.cachedConfig=e,s&&t)try{await F(this.configPath,this.cachedConfig),await _r.chmod(this.configPath,384)}catch{}return this.cachedConfig}async getDeviceId(){return(await this.read()).deviceId??Pr()}async getHostname(){return(await this.read()).hostname??vr.hostname()}async write(t){let s={...await this.read(),...t,lastAuth:new Date().toISOString()};await U(Gi.dirname(this.configPath)),await F(this.configPath,s),await _r.chmod(this.configPath,384),this.cachedConfig=s}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||Rr}async saveAuth(t,e,s){await this.write({apiKey:t,userId:e,email:s})}async clearAuth(){this.cachedConfig={...xr},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}},Yi=new Oe,Ji=Yi});var Cr={};K(Cr,{_resetPublishHelperCache:()=>to,publishCRUD:()=>Ar,publishCRUDSync:()=>G});import zi from"node:crypto";function Vi(r){let t=r&&typeof r=="object"&&!Array.isArray(r)?JSON.stringify(Qi(r)):JSON.stringify(r);return zi.createHash("sha256").update(t).digest("hex")}function Qi(r){let t={};for(let e of Object.keys(r).sort())t[e]=r[e];return t}async function Zi(){if(Xt)return Xt;try{let{default:r}=await Promise.resolve().then(()=>(Me(),je)),t=r;if(typeof t.getDeviceId=="function"){let e=await t.getDeviceId();return Xt=e,e}return"unknown-device"}catch{return"unknown-device"}}function to(){Xt=null}async function Ar(r){try{let t=await Zi(),e=Vi(r.data),s={type:`${r.entityType}.${Ki[r.eventType]}`,path:[r.entityType,r.entityId],data:r.data,timestamp:new Date().toISOString(),projectId:r.projectId,entityType:r.entityType,entityId:r.entityId,eventType:r.eventType,contentHash:e,deviceId:t,originDeviceId:r.originDeviceId??t,revisionCount:r.revisionCount??1};await Ut.publish(s)}catch{}}function G(r){Ar(r)}var Ki,Xt,Et=k(()=>{"use strict";Le();Ki={upsert:"updated",delete:"deleted"};a(Vi,"hashPayload");a(Qi,"sortKeys");Xt=null;a(Zi,"resolveDeviceId");a(to,"_resetPublishHelperCache");a(Ar,"publishCRUD");a(G,"publishCRUDSync")});var St,Fe,it,$t=k(()=>{"use strict";kt();Et();C();j();St={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Fe=class{static{a(this,"ArchiveStorage")}archive(t,e){let s=q(),n=g();return E.run(t,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",s,e.entityType,e.entityId,JSON.stringify(e.entityData),e.summary??null,n,e.reason),G({projectId:t,entityType:"archives",entityId:s,eventType:"upsert",data:{id:s,entity_type:e.entityType,entity_id:e.entityId,summary:e.summary??null,reason:e.reason,archived_at:n}}),s}archiveMany(t,e){if(e.length===0)return 0;let s=g();return E.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(q(),o.entityType,o.entityId,JSON.stringify(o.entityData),o.summary??null,s,o.reason)}),e.length}getArchived(t,e,s=50){return e?E.query(t,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",e,s):E.query(t,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",s)}getStats(t){let e=E.query(t,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),s={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 s&&(s[i]=n.count),s.total+=n.count}return s}restore(t,e){let s=E.get(t,"SELECT * FROM archives WHERE id = ?",e);return s?(E.run(t,"DELETE FROM archives WHERE id = ?",e),JSON.parse(s.entity_data)):null}pruneOldArchives(t,e){let s=new Date(Date.now()-e*24*60*60*1e3).toISOString(),n=this.getTotalCount(t);E.run(t,"DELETE FROM archives WHERE archived_at < ?",s);let i=this.getTotalCount(t);return n-i}getTotalCount(t){return E.get(t,"SELECT COUNT(*) as count FROM archives")?.count??0}},it=new Fe});import io from"node:crypto";function oo(r){let[t,e]=r.split(".");return t?{entityType:t.endsWith("s")?t:`${t}s`,eventType:e==="deleted"||e==="archived"||e==="removed"?"delete":"upsert"}:{}}function ao(r){if(!r||typeof r!="object")return;let t=r;for(let e of["taskId","task_id","id","feature_id","featureId","specId","spec_id"]){let s=t[e];if(typeof s=="string"&&s.length>0)return s}}function co(r){let t=r&&typeof r=="object"&&!Array.isArray(r)?JSON.stringify(uo(r)):JSON.stringify(r);return io.createHash("sha256").update(t).digest("hex")}function uo(r){let t={};for(let e of Object.keys(r).sort())t[e]=r[e];return t}async function lo(){if(Wt)return Wt;try{let{default:r}=await Promise.resolve().then(()=>(Me(),je)),t=r;return typeof t.getDeviceId=="function"?(Wt=await t.getDeviceId(),Wt):"unknown-device"}catch{return"unknown-device"}}var Wt,ot,$e=k(()=>{"use strict";Le();pe();C();j();a(oo,"deriveEntityShape");a(ao,"entityIdOf");a(co,"hashPayload");a(uo,"sortKeys");Wt=null;a(lo,"_resolveDeviceId");ot=class{static{a(this,"StorageManager")}filename;cache;constructor(t,e){this.filename=t,this.cache=new Pt({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(t){let e=this.cache.get(t);if(e!==null)return e;try{let s=E.getDoc(t,this.getStoreKey());if(s!==null)return this.cache.set(t,s),s}catch{}return this.getDefault()}async write(t,e){E.setDoc(t,this.getStoreKey(),e),this.cache.set(t,e)}async update(t,e){let s=await this.read(t),n=e(s);return await this.write(t,n),n}async publishEvent(t,e,s){let n=oo(e),i={type:e,path:[this.filename.replace(".json","")],data:s,timestamp:g(),projectId:t,entityType:n.entityType,entityId:ao(s),eventType:n.eventType,contentHash:co(s),deviceId:await lo(),revisionCount:1};await Ut.publish(i)}async publishEntityEvent(t,e,s,n){let i=`${e}.${s}`,o={...n,timestamp:g()};await this.publishEvent(t,i,o)}async exists(t){try{return E.hasDoc(t,this.getStoreKey())}catch{return!1}}clearCache(t){t?this.cache.delete(t):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});var cn,un,ln,pn,dn=k(()=>{"use strict";cn={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"]},un=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".swift",".rb",".php",".c",".cpp",".h",".hpp",".cs",".vue",".svelte"]),ln=new Set(["node_modules",".git","dist","build",".next",".nuxt",".output","coverage",".cache","__pycache__",".pytest_cache","vendor","target",".turbo",".vercel"]),pn=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 po from"node:fs/promises";import Bt from"node:path";async function Ht(r,t,e={}){let s=Date.now(),n=e.maxFiles??30,i=e.minScore??.1,o=e.includeTests??!1,c=mo(r),u=await go(t),p=await fo(t),m=[];for(let h of u){if(!o&&yo(h))continue;let y=ho(h,c,p,e.historicalBoosts);y.score>=i&&m.push(y)}m.sort((h,y)=>y.score-h.score);let d=m.slice(0,n);return{files:d,metrics:{filesScanned:u.length,filesReturned:d.length,scanDuration:Date.now()-s}}}function mo(r){return r.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).filter(e=>!pn.has(e)&&e.length>2)}async function go(r){let t=[];async function e(s,n=""){try{let i=await po.readdir(s,{withFileTypes:!0});for(let o of i){let c=Bt.join(s,o.name),u=Bt.join(n,o.name);if(o.isDirectory()){if(ln.has(o.name)||o.name.startsWith("."))continue;await e(c,u)}else if(o.isFile()){let p=Bt.extname(o.name).toLowerCase();un.has(p)&&t.push(u)}}}catch(i){L(i)}}return a(e,"walk"),await e(r),t}async function fo(r){let t=new Map;try{let{stdout:e}=await b(`git log -30 --pretty=format:"%H %ct" --name-only | awk '
|
|
539
547
|
/^[a-f0-9]{40}/ { commit=$1; timestamp=$2; next }
|
|
540
548
|
NF { files[$0]++; if (!lastmod[$0]) lastmod[$0]=timestamp }
|
|
541
549
|
END { for (f in files) print files[f], lastmod[f], f }
|
|
542
550
|
'`,{cwd:r,maxBuffer:10485760}),s=Math.floor(Date.now()/1e3),n=e.trim().split(`
|
|
543
|
-
`).filter(Boolean);for(let i of n){let o=i.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(o){let
|
|
544
|
-
`).trim()}var _n,Co,No,Io,O,ut=k(()=>{"use strict";Sn();j();bn();_n=["fact","decision","learning","gotcha","pattern","anti-pattern","shipped","inbox","todo","idea","insight","question","source","person","spec"],Co=25,No=4,Io=100;
|
|
545
|
-
VALUES (?, ?, 'draft', ?, ?, ?, ?)`,s,e.title,JSON.stringify(i),e.tags?JSON.stringify(e.tags):null,n,n),{id:s,title:e.title,status:"draft",content:i,tags:e.tags??{},createdAt:n,updatedAt:n,shippedAt:null,shippedPr:null,shippedSha:null,archivedAt:null}}get(t,e){let s=T.get(t,"SELECT * FROM specs WHERE id = ?",e);return s?this.rowToSpec(s):null}list(t,e={}){let s="SELECT * FROM specs WHERE 1=1",n=[];return e.status&&(s+=" AND status = ?",n.push(e.status)),!e.includeArchived&&!e.status&&(s+=" AND status != 'archived'"),s+=" ORDER BY created_at DESC",T.query(t,s,...n).map(o=>this.rowToSpec(o))}search(t,e){let s=`%${e}%`;return T.query(t,"SELECT * FROM specs WHERE title LIKE ? OR content LIKE ? ORDER BY created_at DESC",s,s).map(i=>this.rowToSpec(i))}updateContent(t,e,s){let n=z.parse(s),i=g();return T.run(t,"UPDATE specs SET content = ?, updated_at = ? WHERE id = ?",JSON.stringify(n),i,e),this.get(t,e)}setStatus(t,e,s){if(!lt.includes(s))throw new Error(`invalid spec status: ${s}`);let n=g(),i=[],o=[s,n];s==="shipped"&&(i.push("shipped_at = ?"),o.push(n)),s==="archived"&&(i.push("archived_at = ?"),o.push(n));let
|
|
551
|
+
`).filter(Boolean);for(let i of n){let o=i.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(o){let c=parseInt(o[1],10),u=parseInt(o[2],10),p=o[3],m=Math.floor((s-u)/86400);t.set(p,{commits:c,daysAgo:m})}}}catch{}return t}function ho(r,t,e,s){let n=[],i=0,o=0,c=0,u=0,p=0,m=r.toLowerCase(),d=m.split("/").join(" ").split(/[^a-z0-9]+/);for(let N of t){m.includes(N)&&(i+=.3,n.push(`keyword:${N}`));for(let pt of d)if(pt.includes(N)||N.includes(pt)){i+=.15;break}}i=Math.min(1,i);for(let[N,pt]of Object.entries(cn))for(let Hn of pt)if(m.includes(Hn)&&t.some(Vt=>pt.includes(Vt)||Vt.includes(N)||N.includes(Vt))){o+=.4,n.push(`domain:${N}`);break}o=Math.min(1,o);let h=e.get(r);h&&(h.daysAgo<=1?(c=1,n.push("recent:1d")):h.daysAgo<=3?(c=.8,n.push("recent:3d")):h.daysAgo<=7?(c=.6,n.push("recent:1w")):h.daysAgo<=30&&(c=.3,n.push("recent:1m")),h.commits>=5&&(c=Math.min(1,c+.2)));let y=Bt.basename(r).toLowerCase();if((y.includes("index")||y.includes("main")||y.includes("app")||y.includes("entry"))&&(u=.5,n.push("import:0")),(m.includes("/core/")||m.includes("/shared/")||m.includes("/lib/"))&&(u=Math.max(u,.3),n.some(N=>N.startsWith("import:"))||n.push("import:1")),s){let N=s.get(r);N!==void 0&&(p=(N+1)/2,N>0?n.push("history:boosted"):N<0&&n.push("history:penalized"))}let bt=s&&s.size>0?i*.54+o*.18+c*.13+u*.05+p*.1:i*.6+o*.2+c*.15+u*.05;return{path:r,score:Math.min(1,bt),reasons:[...new Set(n)]}}function yo(r){let t=r.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 Be=k(()=>{"use strict";V();st();dn();a(Ht,"findRelevantFiles");a(mo,"extractKeywords");a(go,"getAllCodeFiles");a(fo,"getGitRecency");a(ho,"scoreFile");a(yo,"isTestFile")});var qe,En,Sn=k(()=>{"use strict";yt();$t();j();qe=class{static{a(this,"MemoryService")}async log(t,e,s,n){try{let i=await H.getProjectId(t);if(!i)return;T.appendEvent(i,`memory.${e}`,{...s,author:n})}catch(i){console.error(`Memory log error: ${i instanceof Error?i.message:String(i)}`)}}async getRecent(t,e=100){try{let s=await H.getProjectId(t);return s?T.query(s,"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:c,...u}=o;return{timestamp:i.timestamp,action:i.type.replace("memory.",""),data:u,author:c}}):[]}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async search(t,e,s=50){let n=await this.getRecent(t,1e3),i=e.toLowerCase();return n.filter(o=>{let c=o.action.toLowerCase().includes(i),u=JSON.stringify(o.data).toLowerCase().includes(i);return c||u}).slice(-s)}async getByAction(t,e,s=50){try{let n=await H.getProjectId(t);return n?T.query(n,"SELECT type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`memory.${e}`,s).reverse().map(o=>{let c=JSON.parse(o.data),{author:u,...p}=c;return{timestamp:o.timestamp,action:o.type.replace("memory.",""),data:p,author:u}}):[]}catch(n){return console.error(`Memory read error: ${n instanceof Error?n.message:String(n)}`),[]}}async clear(t){try{let e=await H.getProjectId(t);if(!e)return;T.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 T.query(t,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",e).reverse().map(n=>{let i=JSON.parse(n.data);return{timestamp:n.timestamp,action:n.type.replace("memory.",""),...i}})}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async capEntries(t){try{let s=T.get(t,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(s<=St.MEMORY_MAX_ENTRIES)return 0;let n=s-St.MEMORY_MAX_ENTRIES,i=T.query(t,"SELECT id, type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?",n);it.archiveMany(t,i.map((c,u)=>({entityType:"memory_entry",entityId:`memory-${c.timestamp||u}`,entityData:{type:c.type,data:JSON.parse(c.data),timestamp:c.timestamp},summary:c.type.replace("memory.",""),reason:"overflow"})));let o=i[i.length-1]?.id;return o!==void 0&&T.run(t,"DELETE FROM events WHERE type LIKE 'memory.%' AND id <= ?",o),n}catch(e){return console.error(`Memory cap error: ${e instanceof Error?e.message:String(e)}`),0}}},En=new qe});var wn,Ge,Ye,ip,bn=k(()=>{"use strict";wn="memory.",Ge="remember.",Ye=`${wn}${Ge}`,ip=`${wn}task.tagged`});function vn(r,t){try{return JSON.parse(r)}catch{return t}}function Do(r){let t=r.type.slice(Ye.length),e=vn(r.data,{});return{id:`mem_${r.id}`,type:t,content:e.content??"",tags:e.tags??{},rememberedAt:r.timestamp,source:e.source,provenance:e.provenance??"declared"}}function Lo(r){let t=r.data?vn(r.data,{}):{},e=t.tags??{};return r.type&&(e.type=r.type),{id:`ship_${r.id}`,type:"shipped",content:r.name,tags:e,rememberedAt:r.shipped_at,source:t.taskId,provenance:"extracted"}}function Oo(r,t){let e=t.toLowerCase();if(r.content.toLowerCase().includes(e))return!0;for(let s of Object.values(r.tags))if(s.toLowerCase().includes(e))return!0;return!1}function jo(r,t){for(let[e,s]of Object.entries(t))if(r.tags[e]!==s)return!1;return!0}function Mo(r){let t=new Set,e=[];for(let s of r){let n=s.tags.key;if(!n){e.push(s);continue}let i=`${s.type}::${n}`;t.has(i)||(t.add(i),e.push(s))}return e}function wt(r){if(r.length===0)return"> No matching memory entries.";let t=new Map;for(let c of r){let u=t.get(c.type)??[];u.push(c),t.set(c.type,u)}let e=["decision","learning","anti-pattern","gotcha","pattern","fact","inbox","todo","idea","insight","question","source","person","shipped"],s=[],n={declared:"DECL",extracted:"EXTR",inferred:"INFR",ambiguous:"AMBG"},i=a((c,u)=>{if(u.length!==0){s.push(`### ${c.toUpperCase()}`);for(let p of u){let m=Object.entries(p.tags).map(([y,M])=>`${y}=${M}`).join(" "),d=m?` _(${m})_`:"",h=n[p.provenance];s.push(`- \`${h}\` [${p.id}] ${p.content}${d}`)}s.push("")}},"renderGroup"),o=new Set;for(let c of e){let u=t.get(c);!u||u.length===0||(i(c,u),o.add(c))}for(let[c,u]of t)o.has(c)||i(c,u);return s.join(`
|
|
552
|
+
`).trim()}var _n,Co,No,Io,O,ut=k(()=>{"use strict";Sn();j();bn();_n=["fact","decision","learning","gotcha","pattern","anti-pattern","shipped","inbox","todo","idea","insight","question","source","person","spec"],Co=25,No=4,Io=100;a(vn,"safeJson");a(Do,"rowToEntry");a(Lo,"shippedRowToEntry");a(Oo,"matchesTopic");a(jo,"matchesTags");a(Mo,"dedupeLatestByKey");O={async remember(r,t){await En.log(r,`${Ge}${t.type}`,{content:t.content,tags:t.tags??{},source:t.source,provenance:t.provenance??"declared"});try{let{default:e}=await Promise.resolve().then(()=>(yt(),gr)),n=(await e.readConfig(r))?.projectId;if(!n)return;let{publishCRUD:i}=await Promise.resolve().then(()=>(Et(),Cr)),o=t.tags?.spec_id??t.tags?.task_id??t.tags?.id??t.source??`mem-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await i({projectId:n,entityType:"memories",entityId:o,eventType:"upsert",data:{id:o,type:t.type,content:t.content,tags:t.tags??{},source:t.source??null,provenance:t.provenance??"declared",rememberedAt:new Date().toISOString()}})}catch{}},recall(r,t={}){let e=t.limit??Co,s=Math.max(e*No,Io),n=T.query(r,"SELECT id, type, data, timestamp FROM events WHERE type LIKE ? ORDER BY id DESC LIMIT ?",`${Ye}%`,s),i=T.query(r,"SELECT id, name, type, shipped_at, data FROM shipped_features ORDER BY shipped_at DESC LIMIT ?",s),o=[...n.map(Do),...i.map(Lo)];if(t.types&&t.types.length>0){let c=new Set(t.types);o=o.filter(u=>c.has(u.type))}return t.tags&&(o=o.filter(c=>jo(c,t.tags??{}))),t.topic&&(o=o.filter(c=>Oo(c,t.topic))),o.sort((c,u)=>u.rememberedAt.localeCompare(c.rememberedAt)),t.dedupeByKey!==!1&&(o=Mo(o)),o.slice(0,e)},similar(r,t,e=10){let s=t.toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>3);return s.length===0?[]:O.recall(r,{limit:200}).map(o=>{let c=`${o.content} ${Object.values(o.tags).join(" ")}`.toLowerCase(),u=s.reduce((p,m)=>c.includes(m)?p+1:p,0);return{entry:o,hits:u}}).filter(o=>o.hits>0).sort((o,c)=>c.hits-o.hits).slice(0,e).map(o=>o.entry)}};a(wt,"formatMemoryMd")});function Dn(r){return[...r].sort((t,e)=>{let s=In[t.section]-In[e.section];return s!==0?s:Nn[t.priority]-Nn[e.priority]})}var Nn,In,Ln=k(()=>{"use strict";Nn={critical:0,high:1,medium:2,low:3},In={active:0,previously_active:1,backlog:2};a(Dn,"sortBySectionAndPriority")});var ze,Gt,Ke=k(()=>{"use strict";kt();Ft();Ln();C();$t();$e();ze=class extends ot{static{a(this,"QueueStorage")}constructor(){super("queue.json",wr)}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(s=>s.section==="active"&&!s.completed)}async getBacklog(t){return(await this.read(t)).tasks.filter(s=>s.section==="backlog"&&!s.completed)}async getNextTask(t){let e=await this.getActiveTasks(t);return Dn(e)[0]||null}async addTask(t,e){let s={...e,id:q(),createdAt:g(),completed:!1};return await this.update(t,n=>({tasks:[...n.tasks,s],lastUpdated:g()})),await this.publishEvent(t,"queue.task_added",{taskId:s.id,description:s.description,priority:s.priority,section:s.section}),s}async addTasks(t,e){let s=g(),n=e.map(i=>({...i,id:q(),createdAt:s,completed:!1}));return await this.update(t,i=>({tasks:[...i.tasks,...n],lastUpdated:s})),await this.publishEvent(t,"queue.tasks_added",{count:n.length,tasks:n.map(i=>({id:i.id,description:i.description}))}),n}async removeTask(t,e){await this.update(t,s=>({tasks:s.tasks.filter(n=>n.id!==e),lastUpdated:g()})),await this.publishEvent(t,"queue.task_removed",{taskId:e})}async completeTask(t,e){let s=null;if(await this.update(t,n=>({tasks:n.tasks.map(o=>o.id===e?(s={...o,completed:!0,completedAt:g()},s):o),lastUpdated:g()})),s){let n=s;await this.publishEvent(t,"queue.task_completed",{taskId:e,description:n.description,completedAt:n.completedAt})}return s}async moveToSection(t,e,s){await this.update(t,n=>({tasks:n.tasks.map(i=>i.id===e?{...i,section:s}:i),lastUpdated:g()}))}async setPriority(t,e,s){await this.update(t,n=>({tasks:n.tasks.map(i=>i.id===e?{...i,priority:s}:i),lastUpdated:g()}))}async getTask(t,e){return(await this.read(t)).tasks.find(n=>n.id===e)||null}async updateTask(t,e,s){let n=null;return await this.update(t,i=>({tasks:i.tasks.map(o=>o.id===e?(n={...o,...s},n):o),lastUpdated:g()})),n&&await this.publishEvent(t,"queue.task_updated",{taskId:e}),n}async clearCompleted(t){let s=(await this.read(t)).tasks.filter(n=>n.completed).length;return await this.update(t,n=>({tasks:n.tasks.filter(i=>!i.completed),lastUpdated:g()})),s}async removeStaleCompleted(t){let e=await this.read(t),s=ps(St.QUEUE_COMPLETED_DAYS),n=e.tasks.filter(o=>o.completed&&o.completedAt&&new Date(o.completedAt)<s);if(n.length===0)return 0;it.archiveMany(t,n.map(o=>({entityType:"queue_task",entityId:o.id,entityData:o,summary:o.description,reason:"age"})));let i=new Set(n.map(o=>o.id));return await this.update(t,o=>({tasks:o.tasks.filter(c=>!i.has(c.id)),lastUpdated:g()})),await this.publishEvent(t,"queue.stale_removed",{count:n.length}),n.length}},Gt=new ze});import{z as _}from"zod";var lt,Ze,Qe,Uo,z,Yt=k(()=>{"use strict";lt=["draft","reviewed","in_progress","shipped","archived"],Ze=["strategic","architecture","design"],Qe=_.object({verdict:_.enum(["pass","fail"]),notes:_.string(),ts:_.string()}),Uo=_.object({risk:_.string().min(1),mitigation:_.string().min(1)}),z=_.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(Uo).default([]),test_plan:_.array(_.string()).default([]),reviews:_.object({strategic:Qe.optional(),architecture:Qe.optional(),design:Qe.optional()}).optional(),linked_tasks:_.array(_.string()).default([]),notes:_.string().default("")})});var ts,R,Jt=k(()=>{"use strict";kt();Yt();C();j();ts=class{static{a(this,"SpecStorage")}create(t,e){let s=q(),n=g(),i=z.parse(e.content);return T.run(t,`INSERT INTO specs (id, title, status, content, tags, created_at, updated_at)
|
|
553
|
+
VALUES (?, ?, 'draft', ?, ?, ?, ?)`,s,e.title,JSON.stringify(i),e.tags?JSON.stringify(e.tags):null,n,n),{id:s,title:e.title,status:"draft",content:i,tags:e.tags??{},createdAt:n,updatedAt:n,shippedAt:null,shippedPr:null,shippedSha:null,archivedAt:null}}get(t,e){let s=T.get(t,"SELECT * FROM specs WHERE id = ?",e);return s?this.rowToSpec(s):null}list(t,e={}){let s="SELECT * FROM specs WHERE 1=1",n=[];return e.status&&(s+=" AND status = ?",n.push(e.status)),!e.includeArchived&&!e.status&&(s+=" AND status != 'archived'"),s+=" ORDER BY created_at DESC",T.query(t,s,...n).map(o=>this.rowToSpec(o))}search(t,e){let s=`%${e}%`;return T.query(t,"SELECT * FROM specs WHERE title LIKE ? OR content LIKE ? ORDER BY created_at DESC",s,s).map(i=>this.rowToSpec(i))}updateContent(t,e,s){let n=z.parse(s),i=g();return T.run(t,"UPDATE specs SET content = ?, updated_at = ? WHERE id = ?",JSON.stringify(n),i,e),this.get(t,e)}setStatus(t,e,s){if(!lt.includes(s))throw new Error(`invalid spec status: ${s}`);let n=g(),i=[],o=[s,n];s==="shipped"&&(i.push("shipped_at = ?"),o.push(n)),s==="archived"&&(i.push("archived_at = ?"),o.push(n));let c=["status = ?","updated_at = ?",...i].join(", ");return o.push(e),T.run(t,`UPDATE specs SET ${c} WHERE id = ?`,...o),this.get(t,e)}setShippedPr(t,e,s){return T.run(t,"UPDATE specs SET shipped_pr = ?, updated_at = ? WHERE id = ?",s,g(),e),this.get(t,e)}setShippedSha(t,e,s){return T.run(t,"UPDATE specs SET shipped_sha = ?, updated_at = ? WHERE id = ?",s,g(),e),this.get(t,e)}linkTask(t,e,s){let n=this.get(t,e);if(!n)return null;if(n.content.linked_tasks.includes(s))return n;let i={...n.content,linked_tasks:[...n.content.linked_tasks,s]};return this.updateContent(t,e,i)}delete(t,e){return this.get(t,e)?(T.run(t,"DELETE FROM specs WHERE id = ?",e),!0):!1}count(t){let e=T.query(t,"SELECT status, COUNT(*) AS n FROM specs GROUP BY status"),s={total:0,draft:0,shipped:0};for(let n of e)s.total+=n.n,n.status==="draft"&&(s.draft=n.n),n.status==="shipped"&&(s.shipped=n.n);return s}rowToSpec(t){return{id:t.id,title:t.title,status:lt.includes(t.status)?t.status:"draft",content:z.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}}},R=new ts});var Mn={};K(Mn,{inferSpecContext:()=>Wo,warnNoContextMatch:()=>qo});async function Wo(r,t,e){let[s,n]=await Promise.all([Ht(r,e,{maxFiles:jn*4,minScore:$o}).catch(()=>({files:[]})),Promise.resolve(O.recall(t,{topic:r,limit:Xo})).catch(()=>[])]),i=Bo(s.files.map(u=>u.path),jn);return i.length===0&&n.length===0?{notesBlock:"",paths:[],memoryHits:0,empty:!0}:{notesBlock:Ho(r,i,n),paths:i,memoryHits:n.length,empty:!1}}function Bo(r,t){let e=new Set,s=[];for(let n of r){let i=n.split("/").slice(0,2).join("/");if(!e.has(i)&&(e.add(i),s.push(n),s.length>=t))break}return s}function Ho(r,t,e){let s=[];if(s.push("<!-- auto-context:tentative -->"),s.push("## Existing context (auto-inferred)"),s.push(""),s.push(`_Inferred from title "${r}". Validate before audit \u2014 entries tagged tentative._`),s.push(""),t.length>0){s.push("### Likely paths");for(let n of t)s.push(`- \`${n}\``);s.push("")}if(e.length>0){s.push("### Relevant prior memory");for(let n of e){let i=n.content.length>140?`${n.content.slice(0,137)}\u2026`:n.content,o=Object.entries(n.tags).map(([c,u])=>`${c}:${u}`).join(" ");s.push(`- **${n.type}**${o?` _(${o})_`:""} \u2014 ${i}`)}s.push("")}return s.push("<!-- /auto-context -->"),s.join(`
|
|
546
554
|
`)}function qo(r,t){let e={level:"warn",code:"no_context_match",message:`No codebase or memory context matched "${r}"`,suggestion:t??"Fill spec.notes manually or run with `--skip-context` next time."};process.stderr.write(`${JSON.stringify(e)}
|
|
547
|
-
`)}var jn,Xo,$o,Fn=k(()=>{"use strict";ut();Be();jn=5,Xo=8,$o=.15;
|
|
548
|
-
`)){let o=i.trim();o==="---COMMIT---"?(n&&n.size>0&&n.size<=30&&s.push(n),n=new Set):o&&n&&_i(o)&&n.add(o)}return n&&n.size>0&&n.size<=30&&s.push(n),s}catch{return[]}}
|
|
549
|
-
### Directly Changed (${i.directlyChanged.length})`);for(let u of i.directlyChanged)
|
|
550
|
-
### Affected via Imports (${i.affectedByImports.length})`);for(let u of i.affectedByImports)
|
|
551
|
-
### Affected Domains`),
|
|
552
|
-
Total affected: ${i.allAffected.length} files`),{content:[{type:"text",text:
|
|
553
|
-
`)}]}})),t.tool("prjct_import_graph","Import graph stats + file neighbors (imports/importers). Pass a file for its neighbors, omit for graph stats.",{projectPath:D.string().describe("Project directory path"),file:D.string().optional().describe("File path to get neighbors for (omit for graph stats)"),rebuild:D.boolean().optional().default(!1).describe("Force rebuild the import graph")},S("prjct_import_graph",async e=>{let s=await x(e.projectPath),n=e.rebuild?null:ft(s);if(n||(n=await sr(e.projectPath,s)),e.file){let o=n.forward[e.file]||[],
|
|
555
|
+
`)}var jn,Xo,$o,Fn=k(()=>{"use strict";ut();Be();jn=5,Xo=8,$o=.15;a(Wo,"inferSpecContext");a(Bo,"dedupeTopDirs");a(Ho,"buildNotesBlock");a(qo,"warnNoContextMatch")});var Un={};K(Un,{breakdownSpecToTasks:()=>Go});async function Go(r,t,e){let s=e.content.acceptance_criteria;if(s.length===0)return{taskIds:[],skippedReason:"no_acceptance_criteria"};if(e.content.linked_tasks.length>0)return{taskIds:[],skippedReason:"already_broken_down"};let n=await Gt.addTasks(r,s.map(i=>({description:Yo(i),body:i,priority:"medium",type:"feature",section:"backlog",featureId:e.id,groupId:e.id,groupName:e.title})));for(let i of n)R.linkTask(r,e.id,i.id);return await O.remember(t,{type:"spec",content:`Auto-breakdown: ${n.length} tasks created from ${e.title}`,tags:{spec_id:e.id,event:"auto_breakdown",task_count:String(n.length)},source:e.id}),{taskIds:n.map(i=>i.id)}}function Yo(r){let t=r.replace(/\s+/g," ").trim();return t.length<=140?t:`${t.slice(0,137)}\u2026`}var Xn=k(()=>{"use strict";ut();Ke();Jt();a(Go,"breakdownSpecToTasks");a(Yo,"truncateForDescription")});import{StdioServerTransport as sa}from"@modelcontextprotocol/sdk/server/stdio.js";import{McpServer as ta}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as D}from"zod";Zt();j();X();import tr from"node:fs/promises";import rt from"node:path";function Ti(r){let t=[],e,s=new RegExp(us.source,"g");for(;(e=s.exec(r))!==null;){let n=e[1];(n.startsWith(".")||n.startsWith("@/"))&&t.push(n)}return t}a(Ti,"extractImportSources");async function ki(r,t,e){let s;if(r.startsWith("@/"))s=rt.join(e,"src",r.slice(2));else{let n=rt.dirname(rt.join(e,t));s=rt.resolve(n,r)}for(let n of cs){let i=s+n;try{if((await tr.stat(i)).isFile())return rt.relative(e,i)}catch{}}return null}a(ki,"resolveImport");async function Ei(r){let t=await Ts(r),e={},s={},n=0,i=await ks(t,50,async o=>{try{let c=await tr.readFile(rt.join(r,o),"utf-8"),u=Ti(c),p=[];for(let m of u){let d=await ki(m,o,r);d&&d!==o&&p.push(d)}return p.length>0?{filePath:o,imports:p}:null}catch{return null}});for(let{filePath:o,imports:c}of i){e[o]=c,n+=c.length;for(let u of c)s[u]||(s[u]=[]),s[u].push(o)}return{forward:e,reverse:s,fileCount:t.length,edgeCount:n,builtAt:new Date().toISOString()}}a(Ei,"buildGraph");function er(r,t,e=2){let s=new Set(r),n=new Map,i=[];for(let o of r){let c=t.forward[o]||[],u=t.reverse[o]||[];for(let p of[...c,...u])s.has(p)||i.push({file:p,depth:1})}for(;i.length>0;){let{file:o,depth:c}=i.shift();if(c>e)continue;let u=1/(c+1),p=n.get(o);if(p){u>p.score&&n.set(o,{score:u,depth:c});continue}if(n.set(o,{score:u,depth:c}),c<e){let m=t.forward[o]||[],d=t.reverse[o]||[];for(let h of[...m,...d])!s.has(h)&&!n.has(h)&&i.push({file:h,depth:c+1})}}return Array.from(n.entries()).map(([o,{score:c,depth:u}])=>({path:o,score:c,depth:u})).sort((o,c)=>c.score-o.score)}a(er,"scoreFromSeeds");var ke="import-graph",It=new Map;function Si(r,t){T.setDoc(r,ke,t),It.delete(r)}a(Si,"saveGraph");function ft(r){let t=T.get(r,"SELECT updated_at FROM kv_store WHERE key = ?",ke);if(!t)return It.delete(r),null;let e=It.get(r);if(e&&e.updatedAt===t.updated_at)return e.graph;let s=T.getDoc(r,ke);return s&&It.set(r,{graph:s,updatedAt:t.updated_at}),s}a(ft,"loadGraph");async function sr(r,t){let e=await Ei(r);return Si(t,e),e}a(sr,"indexImports");function rr(r,t){let e=[...r.added,...r.modified],s=new Set(e),n=new Set,i=ft(t);if(i)for(let u of e){let p=i.reverse[u];if(p)for(let m of p)s.has(m)||n.add(m)}let o=Array.from(n),c=[...e,...o];return{directlyChanged:e,affectedByImports:o,deleted:r.deleted,allAffected:c}}a(rr,"propagateChanges");function nr(r){let t=new Set;for(let e of r){let s=e.toLowerCase();(s.endsWith(".tsx")||s.endsWith(".jsx")||s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".vue")||s.endsWith(".svelte")||s.includes("/components/")||s.includes("/pages/")||s.includes("/app/"))&&(t.add("frontend"),t.add("uxui")),(s.includes(".test.")||s.includes(".spec.")||s.includes("__tests__")||s.includes("/test/"))&&t.add("testing"),(s.includes("dockerfile")||s.includes("docker-compose")||s.includes(".dockerignore")||s.includes(".github/")||s.includes("ci/")||s.includes("cd/"))&&t.add("devops"),(s.endsWith(".sql")||s.includes("prisma")||s.includes("drizzle")||s.includes("migration")||s.includes("/db/"))&&t.add("database"),(s.endsWith(".ts")||s.endsWith(".js"))&&!s.includes(".test.")&&!s.includes(".spec.")&&!s.endsWith(".d.ts")&&t.add("backend")}return t}a(nr,"affectedDomains");j();st();async function bi(r,t=100){try{let{stdout:e}=await b(`git log --name-only --pretty=format:'---COMMIT---' -${t}`,{cwd:r,maxBuffer:10485760}),s=[],n=null;for(let i of e.split(`
|
|
556
|
+
`)){let o=i.trim();o==="---COMMIT---"?(n&&n.size>0&&n.size<=30&&s.push(n),n=new Set):o&&n&&_i(o)&&n.add(o)}return n&&n.size>0&&n.size<=30&&s.push(n),s}catch{return[]}}a(bi,"parseGitLog");function _i(r){return/\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|cs|rb|php|vue|svelte)$/i.test(r)&&!r.includes("node_modules/")}a(_i,"isSourceFile");async function vi(r,t=100){let e=await bi(r,t),s=new Map,n=new Map;for(let o of e){let c=Array.from(o);for(let u of c)s.set(u,(s.get(u)||0)+1);for(let u=0;u<c.length;u++)for(let p=u+1;p<c.length;p++){let m=xi(c[u],c[p]);n.set(m,(n.get(m)||0)+1)}}let i={};for(let[o,c]of n){let[u,p]=o.split("\0"),m=s.get(u)||0,d=s.get(p)||0;if(m<2||d<2)continue;let h=m+d-c,y=h>0?c/h:0;y<.1||(i[u]||(i[u]={}),i[p]||(i[p]={}),i[u][p]=y,i[p][u]=y)}return{matrix:i,commitsAnalyzed:e.length,filesAnalyzed:s.size,builtAt:new Date().toISOString()}}a(vi,"buildMatrix");function xi(r,t){return r<t?`${r}\0${t}`:`${t}\0${r}`}a(xi,"pairKey");function Se(r,t){let e=new Set(r),s=new Map;for(let n of r){let i=t.matrix[n];if(i)for(let[o,c]of Object.entries(i)){if(e.has(o))continue;let u=s.get(o)||0;c>u&&s.set(o,c)}}return Array.from(s.entries()).map(([n,i])=>({path:n,score:i})).sort((n,i)=>i.score-n.score)}a(Se,"scoreFromSeeds");var Ee="cochange-index",Dt=new Map;function Pi(r,t){T.setDoc(r,Ee,t),Dt.delete(r)}a(Pi,"saveMatrix");function we(r){let t=T.get(r,"SELECT updated_at FROM kv_store WHERE key = ?",Ee);if(!t)return Dt.delete(r),null;let e=Dt.get(r);if(e&&e.updatedAt===t.updated_at)return e.matrix;let s=T.getDoc(r,Ee);return s&&Dt.set(r,{matrix:s,updatedAt:t.updated_at}),s}a(we,"loadMatrix");async function ar(r,t,e=100){let s=await vi(r,e);return Pi(t,s),s}a(ar,"indexCoChanges");yt();async function x(r){return H.getProjectId(r)}a(x,"resolveProjectId");function S(r,t){return async e=>{try{return await t(e)}catch(s){return ji(s,r)}}}a(S,"safeMcpCall");function ji(r,t){let e=r instanceof Error?r.message:String(r);return{content:[{type:"text",text:`[${t}] Error: ${e}`}],isError:!0}}a(ji,"mcpError");function fr(r){let t=r;t.tool("prjct_impact_analysis","Given changed files, find affected files via import graph + affected domains",{projectPath:D.string().describe("Project directory path"),changedFiles:D.array(D.string()).describe("List of changed file paths (relative to project root)")},S("prjct_impact_analysis",async e=>{let s=await x(e.projectPath),n={added:[],modified:e.changedFiles,deleted:[],unchanged:[]},i=rr(n,s),o=nr(i.allAffected),c=["## Impact Analysis"];c.push(`
|
|
557
|
+
### Directly Changed (${i.directlyChanged.length})`);for(let u of i.directlyChanged)c.push(`- ${u}`);if(i.affectedByImports.length>0){c.push(`
|
|
558
|
+
### Affected via Imports (${i.affectedByImports.length})`);for(let u of i.affectedByImports)c.push(`- ${u}`)}return c.push(`
|
|
559
|
+
### Affected Domains`),c.push(o.size>0?Array.from(o).join(", "):"none detected"),c.push(`
|
|
560
|
+
Total affected: ${i.allAffected.length} files`),{content:[{type:"text",text:c.join(`
|
|
561
|
+
`)}]}})),t.tool("prjct_import_graph","Import graph stats + file neighbors (imports/importers). Pass a file for its neighbors, omit for graph stats.",{projectPath:D.string().describe("Project directory path"),file:D.string().optional().describe("File path to get neighbors for (omit for graph stats)"),rebuild:D.boolean().optional().default(!1).describe("Force rebuild the import graph")},S("prjct_import_graph",async e=>{let s=await x(e.projectPath),n=e.rebuild?null:ft(s);if(n||(n=await sr(e.projectPath,s)),e.file){let o=n.forward[e.file]||[],c=n.reverse[e.file]||[];return{content:[{type:"text",text:[`## Import Neighbors: ${e.file}`,`
|
|
554
562
|
### Imports (${o.length})`,...o.map(p=>`- ${p}`),`
|
|
555
|
-
### Imported By (${
|
|
563
|
+
### Imported By (${c.length})`,...c.map(p=>`- ${p}`)].join(`
|
|
556
564
|
`)}]}}return{content:[{type:"text",text:["## Import Graph Stats",`Files: ${n.fileCount}`,`Edges: ${n.edgeCount}`,`Built: ${n.builtAt}`].join(`
|
|
557
|
-
`)}]}})),t.tool("prjct_cochange","Files that historically change together (Jaccard similarity from git history)",{projectPath:D.string().describe("Project directory path"),seedFiles:D.array(D.string()).describe("Seed files to find co-change partners for"),rebuild:D.boolean().optional().default(!1).describe("Force rebuild the co-change matrix"),maxResults:D.number().optional().default(10).describe("Max results (default 10)")},S("prjct_cochange",async e=>{let s=await x(e.projectPath),n=e.rebuild?null:we(s);n||(n=await ar(e.projectPath,s));let i=Se(e.seedFiles,n).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: ${n.commitsAnalyzed}`,""];for(let
|
|
558
|
-
`)}]}})),t.tool("prjct_related_context","Combined: import neighbors + co-change partners for seed files",{projectPath:D.string().describe("Project directory path"),seedFiles:D.array(D.string()).describe("Seed files to find related context for"),maxResults:D.number().optional().default(15).describe("Max results (default 15)")},S("prjct_related_context",async e=>{let s=await x(e.projectPath),n=ft(s),i=n?er(e.seedFiles,n):[],o=we(s),
|
|
559
|
-
`)}]}}))}
|
|
565
|
+
`)}]}})),t.tool("prjct_cochange","Files that historically change together (Jaccard similarity from git history)",{projectPath:D.string().describe("Project directory path"),seedFiles:D.array(D.string()).describe("Seed files to find co-change partners for"),rebuild:D.boolean().optional().default(!1).describe("Force rebuild the co-change matrix"),maxResults:D.number().optional().default(10).describe("Max results (default 10)")},S("prjct_cochange",async e=>{let s=await x(e.projectPath),n=e.rebuild?null:we(s);n||(n=await ar(e.projectPath,s));let i=Se(e.seedFiles,n).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: ${n.commitsAnalyzed}`,""];for(let c of i)o.push(`- ${c.path} (similarity: ${Math.round(c.score*100)}%)`);return{content:[{type:"text",text:o.join(`
|
|
566
|
+
`)}]}})),t.tool("prjct_related_context","Combined: import neighbors + co-change partners for seed files",{projectPath:D.string().describe("Project directory path"),seedFiles:D.array(D.string()).describe("Seed files to find related context for"),maxResults:D.number().optional().default(15).describe("Max results (default 15)")},S("prjct_related_context",async e=>{let s=await x(e.projectPath),n=ft(s),i=n?er(e.seedFiles,n):[],o=we(s),c=o?Se(e.seedFiles,o):[],u=new Map;for(let d of i)u.set(d.path,{importScore:d.score,cochangeScore:0});for(let d of c){let h=u.get(d.path);h?h.cochangeScore=d.score:u.set(d.path,{importScore:0,cochangeScore:d.score})}let p=Array.from(u.entries()).map(([d,h])=>({path:d,combined:h.importScore*.6+h.cochangeScore*.4,importScore:h.importScore,cochangeScore:h.cochangeScore})).sort((d,h)=>h.combined-d.combined).slice(0,e.maxResults);if(p.length===0)return{content:[{type:"text",text:"No related files found. Run `prjct sync` to build indexes."}]};let m=["## Related Context",`Seeds: ${e.seedFiles.join(", ")}`,""];for(let d of p){let h=[];d.importScore>0&&h.push(`import: ${d.importScore.toFixed(2)}`),d.cochangeScore>0&&h.push(`cochange: ${Math.round(d.cochangeScore*100)}%`),m.push(`- ${d.path} (${h.join(", ")})`)}return{content:[{type:"text",text:m.join(`
|
|
567
|
+
`)}]}}))}a(fr,"registerCodeIntelTools");import{z as tt}from"zod";Ft();C();var Tt={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"}},Ce=class{static{a(this,"WorkflowStateMachine")}getCurrentState(t,e){let s=null;if(e&&t?.activeTasks?.length&&(s=t.activeTasks.find(i=>i.workspaceId===e)),s||(s=t?.currentTask),!s)return(t?.pausedTasks?.length||0)>0||t?.previousTask?.status==="paused"?"paused":"idle";switch((typeof s.status=="string"?s.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 s?"working":"idle"}}canTransition(t,e){if(Tt[t].transitions.includes(e))return{valid:!0};let n=this.formatNextSteps(t).join(" | ");return{valid:!1,error:`Cannot transition to '${e}' from '${t}' state`,suggestion:`Valid next steps: ${n}`}}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 Tt[t]}getPrompt(t){return Tt[t].prompt}getValidCommands(t){return Tt[t].transitions}formatNextSteps(t){return Tt[t].transitions.map(s=>{switch(s){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 ${s}`}})}},Ne=new Ce;kt();C();$t();async function Nr(r,t,e){let s=await r.read(t);if(!s.currentTask)return null;r.validateTransition(s,"pause");let n={...s.currentTask,status:"paused",pausedAt:g(),pauseReason:e},i=r.getPausedTasksFromState(s),o=[n,...i].slice(0,r.maxPausedTasks);return await r.update(t,c=>({...c,currentTask:null,previousTask:null,pausedTasks:o,lastUpdated:g()})),await r.publish(t,"task.paused",{taskId:n.id,description:n.description,pausedAt:n.pausedAt,reason:e,pausedCount:o.length}),n}a(Nr,"pauseTask");async function Ir(r,t,e){let s=await r.read(t),n=r.getPausedTasksFromState(s);if(n.length===0)return null;r.validateTransition(s,"resume");let i=0;if(e&&(i=n.findIndex(y=>y.id===e),i===-1))return null;let o=n[i],c=n.filter((y,M)=>M!==i),{status:u,pausedAt:p,pauseReason:m,...d}=o,h={...d,startedAt:g(),sessionId:o.sessionId??q()};return await r.update(t,y=>({...y,currentTask:h,previousTask:null,pausedTasks:c,lastUpdated:g()})),await r.publish(t,"task.resumed",{taskId:h.id,description:h.description,resumedAt:h.startedAt,remainingPaused:c.length}),h}a(Ir,"resumeTask");async function Dr(r,t){let e=await r.read(t),s=r.getPausedTasksFromState(e),n=Date.now()-r.stalenessThresholdDays*24*60*60*1e3;return s.filter(i=>new Date(i.pausedAt).getTime()<n)}a(Dr,"getStalePausedTasks");async function Lr(r,t){let e=await r.read(t),s=r.getPausedTasksFromState(e),n=Date.now()-r.stalenessThresholdDays*24*60*60*1e3,i=s.filter(c=>new Date(c.pausedAt).getTime()<n),o=s.filter(c=>new Date(c.pausedAt).getTime()>=n);if(i.length===0)return[];it.archiveMany(t,i.map(c=>({entityType:"paused_task",entityId:c.id,entityData:c,summary:c.description,reason:"staleness"}))),await r.update(t,c=>({...c,pausedTasks:o,previousTask:null,lastUpdated:g()}));for(let c of i)await r.publish(t,"task.archived",{taskId:c.id,description:c.description,pausedAt:c.pausedAt,reason:"staleness"});return i}a(Lr,"archiveStalePausedTasks");C();async function Or(r,t){await r.update(t,()=>({currentTask:null,previousTask:null,pausedTasks:[],activeTasks:[],lastUpdated:g()}))}a(Or,"clearTask");async function jr(r,t){let e=await r.read(t),s=r.getPausedTasksFromState(e);return e.currentTask!==null||s.length>0}a(jr,"hasTask");async function Mr(r,t){let e=await r.read(t);return r.getPausedTasksFromState(e)[0]||null}a(Mr,"getPausedTask");async function Fr(r,t){let e=await r.read(t);return r.getPausedTasksFromState(e)}a(Fr,"getAllPausedTasks");async function Ue(r,t){let e=await r.read(t);return r.getTaskHistoryFromState(e)}a(Ue,"getTaskHistory");async function Ur(r,t){let e=await r.read(t);return r.getTaskHistoryFromState(e)[0]||null}a(Ur,"getMostRecentTask");async function Xr(r,t,e){let s=await r.read(t);return r.getTaskHistoryFromState(s).filter(i=>i.classification===e)}a(Xr,"getTaskHistoryByType");async function $r(r,t){let s=(await Ue(r,t)).filter(h=>h.feedback),n=[],i=[],o=[],c=[];for(let h of s){let y=h.feedback;Array.isArray(y.stackConfirmed)&&n.push(...y.stackConfirmed),Array.isArray(y.patternsDiscovered)&&i.push(...y.patternsDiscovered),Array.isArray(y.agentAccuracy)&&o.push(...y.agentAccuracy),Array.isArray(y.issuesEncountered)&&c.push(...y.issuesEncountered)}let u=[...new Set(n)],p=[...new Set(i)],m=new Map;for(let h of c)m.set(h,(m.get(h)||0)+1);let d=[...m.entries()].filter(([h,y])=>y>=2).map(([h])=>h);return{stackConfirmed:u,patternsDiscovered:p,agentAccuracy:o,issuesEncountered:[...new Set(c)],knownGotchas:d}}a($r,"getAggregatedFeedback");Ft();C();async function Wr(r,t,e){let s=await r.read(t);if(!s.currentTask)return;let n=e.map((i,o)=>({...i,status:o===0?"in_progress":"pending",startedAt:o===0?g():void 0,dependsOn:i.dependsOn||[]}));await r.update(t,i=>({...i,currentTask:{...i.currentTask,subtasks:n,currentSubtaskIndex:0,subtaskProgress:{completed:0,total:n.length,percentage:0}},lastUpdated:g()})),await r.publish(t,"subtasks.created",{taskId:s.currentTask.id,subtaskCount:n.length,subtasks:n.map(i=>({id:i.id,description:i.description,domain:i.domain}))})}a(Wr,"createSubtasks");async function Br(r,t,e){let s=yr.safeParse(e);if(!s.success){let M=s.error.issues.map(bt=>`${bt.path.join(".")}: ${bt.message}`);throw new Error(`Subtask completion requires handoff data:
|
|
560
568
|
${M.join(`
|
|
561
|
-
`)}`)}let{output:n,summary:i}=s.data,o=await r.read(t);if(!o.currentTask?.subtasks)return null;let a=o.currentTask.currentSubtaskIndex||0,u=o.currentTask.subtasks[a];if(!u)return null;let p=[...o.currentTask.subtasks];p[a]={...u,status:"completed",completedAt:g(),output:n,summary:i};let m=p.filter(M=>M.status==="completed").length,d=p.length,h=Math.round(m/d*100),y=a+1;return y<p.length&&(p[y]={...p[y],status:"in_progress",startedAt:g()}),await r.update(t,M=>({...M,currentTask:{...M.currentTask,subtasks:p,currentSubtaskIndex:y<d?y:a,subtaskProgress:{completed:m,total:d,percentage:h}},lastUpdated:g()})),await r.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:m,total:d,percentage:h}}),y<d?p[y]:null}c(Br,"completeSubtask");async function Hr(r,t){let e=await r.read(t);if(!e.currentTask?.subtasks)return null;let s=e.currentTask.currentSubtaskIndex||0;return e.currentTask.subtasks[s]||null}c(Hr,"getCurrentSubtask");async function qr(r,t){let e=await r.read(t);if(!e.currentTask?.subtasks)return null;let s=(e.currentTask.currentSubtaskIndex||0)+1;return e.currentTask.subtasks[s]||null}c(qr,"getNextSubtask");async function Xe(r,t){let e=await r.read(t);if(!e.currentTask?.subtasks)return null;let s=(e.currentTask.currentSubtaskIndex||0)-1;return s<0?null:e.currentTask.subtasks[s]||null}c(Xe,"getPreviousSubtask");async function Gr(r,t){let e=await Xe(r,t);return e?.summary?.outputForNextAgent?{fromSubtask:e.description,outputForNextAgent:e.summary.outputForNextAgent,filesChanged:e.summary.filesChanged,whatWasDone:e.summary.whatWasDone}:null}c(Gr,"getPreviousHandoff");async function Yr(r,t){return(await r.read(t)).currentTask?.subtasks||[]}c(Yr,"getSubtasks");async function Jr(r,t){return(await r.read(t)).currentTask?.subtaskProgress||null}c(Jr,"getSubtaskProgress");async function zr(r,t){return((await r.read(t)).currentTask?.subtasks?.length||0)>0}c(zr,"hasSubtasks");async function Kr(r,t){let e=await r.read(t);return e.currentTask?.subtasks?e.currentTask.subtasks.every(s=>s.status==="completed"||s.status==="failed"||s.status==="skipped"):!0}c(Kr,"areAllSubtasksComplete");async function Vr(r,t,e){let s=await r.read(t);if(!s.currentTask?.subtasks)return null;let n=s.currentTask.currentSubtaskIndex||0,i=s.currentTask.subtasks[n];if(!i)return null;let o=[...s.currentTask.subtasks];o[n]={...i,status:"failed",completedAt:g(),output:`Failed: ${e}`};let a=n+1,u=o.length;a<u&&(o[a]={...o[a],status:"in_progress",startedAt:g()});let p=o.filter(d=>d.status==="completed"||d.status==="failed"||d.status==="skipped").length,m=Math.round(p/u*100);return await r.update(t,d=>({...d,currentTask:{...d.currentTask,subtasks:o,currentSubtaskIndex:a<u?a:n,subtaskProgress:{completed:p,total:u,percentage:m}},lastUpdated:g()})),await r.publish(t,"subtask.failed",{taskId:s.currentTask.id,subtaskId:i.id,description:i.description,error:e}),a<u?o[a]:null}c(Vr,"failSubtask");async function Qr(r,t,e){let s=await r.read(t);if(!s.currentTask?.subtasks)return null;let n=s.currentTask.currentSubtaskIndex||0,i=s.currentTask.subtasks[n];if(!i)return null;let o=[...s.currentTask.subtasks];o[n]={...i,status:"skipped",completedAt:g(),output:`Skipped: ${e}`,skipReason:e};let a=n+1,u=o.length;a<u&&(o[a]={...o[a],status:"in_progress",startedAt:g()});let p=o.filter(d=>d.status==="completed"||d.status==="failed"||d.status==="skipped").length,m=Math.round(p/u*100);return await r.update(t,d=>({...d,currentTask:{...d.currentTask,subtasks:o,currentSubtaskIndex:a<u?a:n,subtaskProgress:{completed:p,total:u,percentage:m}},lastUpdated:g()})),await r.publish(t,"subtask.skipped",{taskId:s.currentTask.id,subtaskId:i.id,description:i.description,reason:e}),a<u?o[a]:null}c(Qr,"skipSubtask");async function Zr(r,t,e){let s=await r.read(t);if(!s.currentTask?.subtasks)return null;let n=s.currentTask.currentSubtaskIndex||0,i=s.currentTask.subtasks[n];if(!i)return null;let o=[...s.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:g()}),await r.update(t,p=>({...p,currentTask:{...p.currentTask,subtasks:o,currentSubtaskIndex:a<u?a:n},lastUpdated:g()})),await r.publish(t,"subtask.blocked",{taskId:s.currentTask.id,subtaskId:i.id,description:i.description,blocker:e}),a<u?o[a]:null}c(Zr,"blockSubtask");C();async function tn(r,t,e,s){let n={...e,workspaceId:s,startedAt:g()};return await r.update(t,i=>({...i,activeTasks:[...i.activeTasks||[],n],lastUpdated:g()})),await r.publish(t,"task.started",{taskId:n.id,description:n.description,startedAt:n.startedAt,sessionId:n.sessionId,workspaceId:s}),n}c(tn,"startTaskInWorkspace");async function en(r,t,e){return((await r.read(t)).activeTasks||[]).find(n=>n.workspaceId===e)??null}c(en,"getCurrentTaskForWorkspace");async function sn(r,t,e,s){let n=await r.read(t),o=(n.activeTasks||[]).find(d=>d.workspaceId===e);if(!o)return null;let a=g(),u=r.createTaskHistoryEntry(o,a,s),p=r.getTaskHistoryFromState(n),m=[u,...p].slice(0,r.maxTaskHistory);return await r.update(t,d=>({...d,activeTasks:(d.activeTasks||[]).filter(h=>h.workspaceId!==e),taskHistory:m,lastUpdated:a})),await r.publish(t,"task.completed",{taskId:o.id,description:o.description,startedAt:o.startedAt,completedAt:a,workspaceId:e}),o}c(sn,"completeTaskInWorkspace");async function rn(r,t){return(await r.read(t)).activeTasks||[]}c(rn,"getActiveTasks");async function nn(r,t){return((await r.read(t)).activeTasks||[]).length}c(nn,"getActiveTaskCount");async function on(r,t,e,s){let i=(await r.read(t)).activeTasks||[],o=i.findIndex(u=>u.workspaceId===e);if(o===-1)return null;let a={...i[o],...s,workspaceId:e};return await r.update(t,u=>{let p=[...u.activeTasks||[]];return p[o]=a,{...u,activeTasks:p,lastUpdated:g()}}),a}c(on,"updateWorkspaceTask");async function an(r,t,e,s){let n=await r.read(t);if(!n.currentTask)return null;let i=(n.currentTask.tokensIn||0)+e,o=(n.currentTask.tokensOut||0)+s;return await r.update(t,a=>({...a,currentTask:{...a.currentTask,tokensIn:i,tokensOut:o},lastUpdated:g()})),{tokensIn:i,tokensOut:o}}c(an,"addTokens");$e();var We=class extends ot{static{c(this,"StateStorage")}constructor(){super("state.json",Sr)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],activeTasks:[],lastUpdated:""}}getEventType(t){return`state.${t}d`}validateTransition(t,e){let s=Ne.getCurrentState(t),n=Ne.canTransition(s,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 s=await this.read(t);this.validateTransition(s,"task");let n={...e,startedAt:g()};return await this.update(t,i=>({...i,currentTask:n,lastUpdated:g()})),await this.publishEvent(t,"task.started",{taskId:n.id,description:n.description,startedAt:n.startedAt,sessionId:n.sessionId}),n}async updateCurrentTask(t,e){let s=await this.read(t);if(!s.currentTask)return null;let n={...s.currentTask,...e};return await this.update(t,i=>({...i,currentTask:n,lastUpdated:g()})),n}async completeTask(t,e){let s=await this.read(t),n=s.currentTask;if(!n)return null;this.validateTransition(s,"done");let i=g(),o=this.createTaskHistoryEntry(n,i,e),a=this.getTaskHistoryFromState(s),u=[o,...a].slice(0,this.maxTaskHistory);return await this.update(t,p=>({...p,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,s){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 s&&(o.feedback=s),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 Nr(this.lifecycleBackend(),t,e)}async resumeTask(t,e){return Ir(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 Dr(this.lifecycleBackend(),t)}async archiveStalePausedTasks(t){return Lr(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 Or(this.queryBackend(),t)}async hasTask(t){return jr(this.queryBackend(),t)}async getPausedTask(t){return Mr(this.queryBackend(),t)}async getAllPausedTasks(t){return Fr(this.queryBackend(),t)}async getTaskHistory(t){return Ue(this.queryBackend(),t)}async getMostRecentTask(t){return Ur(this.queryBackend(),t)}async getTaskHistoryByType(t,e){return Xr(this.queryBackend(),t,e)}async getAggregatedFeedback(t){return $r(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,s){return tn(this.workspaceBackend(),t,e,s)}async getCurrentTaskForWorkspace(t,e){return en(this.workspaceBackend(),t,e)}async completeTaskInWorkspace(t,e,s){return sn(this.workspaceBackend(),t,e,s)}async getActiveTasks(t){return rn(this.workspaceBackend(),t)}async getActiveTaskCount(t){return nn(this.workspaceBackend(),t)}async updateWorkspaceTask(t,e,s){return on(this.workspaceBackend(),t,e,s)}async addTokens(t,e,s){return an(this.workspaceBackend(),t,e,s)}subtaskBackend(){return{read:this.read.bind(this),update:this.update.bind(this),publish:this.publishEvent.bind(this)}}async createSubtasks(t,e){return Wr(this.subtaskBackend(),t,e)}async completeSubtask(t,e){return Br(this.subtaskBackend(),t,e)}async getCurrentSubtask(t){return Hr(this.subtaskBackend(),t)}async getNextSubtask(t){return qr(this.subtaskBackend(),t)}async getPreviousSubtask(t){return Xe(this.subtaskBackend(),t)}async getPreviousHandoff(t){return Gr(this.subtaskBackend(),t)}async getSubtasks(t){return Yr(this.subtaskBackend(),t)}async getSubtaskProgress(t){return Jr(this.subtaskBackend(),t)}async hasSubtasks(t){return zr(this.subtaskBackend(),t)}async areAllSubtasksComplete(t){return Kr(this.subtaskBackend(),t)}async failSubtask(t,e){return Vr(this.subtaskBackend(),t,e)}async skipSubtask(t,e){return Qr(this.subtaskBackend(),t,e)}async blockSubtask(t,e){return Zr(this.subtaskBackend(),t,e)}},at=new We;Be();V();import wo from"node:fs/promises";import ct from"node:path";var ko={"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}},Eo="claude-sonnet-4.5";function He(r){return!r||r.length===0?0:Math.ceil(r.length/4)}c(He,"countTokens");var gn=["claude-sonnet-4.5","claude-opus-4.5","claude-opus-4-6","gpt-4o","gemini-1.5-pro"];function mn(r,t){let e=ko[t],s=r/1e3*e.input,n=r/1e3*e.output*.3;return{inputSaved:s,outputPotential:n,total:s+n}}c(mn,"calculateModelCost");function So(r){return r<.001?"<$0.01":r<.01?`$${r.toFixed(3)}`:`$${r.toFixed(2)}`}c(So,"formatCostSaved");function fn(r,t){let e=He(r),s=He(t),n=Math.max(0,e-s),i=e>0?(e-s)/e:0,o=mn(n,Eo),a=gn.map(u=>({model:u,...mn(n,u)}));return{tokens:{original:e,filtered:s,saved:n},compression:Math.max(0,Math.min(1,i)),cost:{saved:o.total,formatted:So(o.total),byModel:a}}}c(fn,"measureCompression");function qt(r){let t=He(r);return{tokens:{original:t,filtered:t,saved:0},compression:0,cost:{saved:0,formatted:"$0.00",byModel:gn.map(e=>({model:e,inputSaved:0,outputPotential:0,total:0}))}}}c(qt,"noCompression");var bo={".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"},hn=[{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}],_o=[{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}],vo=[{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}],xo=[{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}],yn=[{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}],Po={typescript:hn,javascript:hn,python:_o,go:vo,rust:xo,java:yn,csharp:yn,php:[],ruby:[],unknown:[]};async function Tn(r,t=process.cwd()){let e=ct.isAbsolute(r)?r:ct.join(t,r),s=ct.resolve(t),n=ct.resolve(e);if(!n.startsWith(s+ct.sep)&&n!==s)return{file:r,language:"unknown",signatures:[],fallback:!0,fallbackReason:"Path traversal denied: file is outside project directory",metrics:qt("")};let i;try{i=await wo.readFile(e,"utf-8")}catch(d){if(L(d))return{file:r,language:"unknown",signatures:[],fallback:!0,fallbackReason:"File not found",metrics:qt("")};throw d}let o=ct.extname(r).toLowerCase(),a=bo[o]||"unknown",u=Po[a];if(!u||u.length===0)return{file:r,language:a,signatures:[],fallback:!0,fallbackReason:`No extraction patterns for ${a}`,metrics:qt(i)};let p=Ro(i,u),m=p.map(d=>`${d.exported?"export ":""}${d.type} ${d.name}: ${d.signature}`).join(`
|
|
562
|
-
`);return{file:r,language:
|
|
563
|
-
`),n=new Set;for(let i of t){i.pattern.lastIndex=0;let o;for(;(o=i.pattern.exec(r))!==null;){let
|
|
564
|
-
`).length,d=o[0].trim(),h;if(m>1){let y=s[m-2]?.trim();(y?.startsWith("/**")||y?.startsWith("///")||y?.startsWith("#"))&&(h=y)}e.push({type:i.type,name:
|
|
569
|
+
`)}`)}let{output:n,summary:i}=s.data,o=await r.read(t);if(!o.currentTask?.subtasks)return null;let c=o.currentTask.currentSubtaskIndex||0,u=o.currentTask.subtasks[c];if(!u)return null;let p=[...o.currentTask.subtasks];p[c]={...u,status:"completed",completedAt:g(),output:n,summary:i};let m=p.filter(M=>M.status==="completed").length,d=p.length,h=Math.round(m/d*100),y=c+1;return y<p.length&&(p[y]={...p[y],status:"in_progress",startedAt:g()}),await r.update(t,M=>({...M,currentTask:{...M.currentTask,subtasks:p,currentSubtaskIndex:y<d?y:c,subtaskProgress:{completed:m,total:d,percentage:h}},lastUpdated:g()})),await r.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:m,total:d,percentage:h}}),y<d?p[y]:null}a(Br,"completeSubtask");async function Hr(r,t){let e=await r.read(t);if(!e.currentTask?.subtasks)return null;let s=e.currentTask.currentSubtaskIndex||0;return e.currentTask.subtasks[s]||null}a(Hr,"getCurrentSubtask");async function qr(r,t){let e=await r.read(t);if(!e.currentTask?.subtasks)return null;let s=(e.currentTask.currentSubtaskIndex||0)+1;return e.currentTask.subtasks[s]||null}a(qr,"getNextSubtask");async function Xe(r,t){let e=await r.read(t);if(!e.currentTask?.subtasks)return null;let s=(e.currentTask.currentSubtaskIndex||0)-1;return s<0?null:e.currentTask.subtasks[s]||null}a(Xe,"getPreviousSubtask");async function Gr(r,t){let e=await Xe(r,t);return e?.summary?.outputForNextAgent?{fromSubtask:e.description,outputForNextAgent:e.summary.outputForNextAgent,filesChanged:e.summary.filesChanged,whatWasDone:e.summary.whatWasDone}:null}a(Gr,"getPreviousHandoff");async function Yr(r,t){return(await r.read(t)).currentTask?.subtasks||[]}a(Yr,"getSubtasks");async function Jr(r,t){return(await r.read(t)).currentTask?.subtaskProgress||null}a(Jr,"getSubtaskProgress");async function zr(r,t){return((await r.read(t)).currentTask?.subtasks?.length||0)>0}a(zr,"hasSubtasks");async function Kr(r,t){let e=await r.read(t);return e.currentTask?.subtasks?e.currentTask.subtasks.every(s=>s.status==="completed"||s.status==="failed"||s.status==="skipped"):!0}a(Kr,"areAllSubtasksComplete");async function Vr(r,t,e){let s=await r.read(t);if(!s.currentTask?.subtasks)return null;let n=s.currentTask.currentSubtaskIndex||0,i=s.currentTask.subtasks[n];if(!i)return null;let o=[...s.currentTask.subtasks];o[n]={...i,status:"failed",completedAt:g(),output:`Failed: ${e}`};let c=n+1,u=o.length;c<u&&(o[c]={...o[c],status:"in_progress",startedAt:g()});let p=o.filter(d=>d.status==="completed"||d.status==="failed"||d.status==="skipped").length,m=Math.round(p/u*100);return await r.update(t,d=>({...d,currentTask:{...d.currentTask,subtasks:o,currentSubtaskIndex:c<u?c:n,subtaskProgress:{completed:p,total:u,percentage:m}},lastUpdated:g()})),await r.publish(t,"subtask.failed",{taskId:s.currentTask.id,subtaskId:i.id,description:i.description,error:e}),c<u?o[c]:null}a(Vr,"failSubtask");async function Qr(r,t,e){let s=await r.read(t);if(!s.currentTask?.subtasks)return null;let n=s.currentTask.currentSubtaskIndex||0,i=s.currentTask.subtasks[n];if(!i)return null;let o=[...s.currentTask.subtasks];o[n]={...i,status:"skipped",completedAt:g(),output:`Skipped: ${e}`,skipReason:e};let c=n+1,u=o.length;c<u&&(o[c]={...o[c],status:"in_progress",startedAt:g()});let p=o.filter(d=>d.status==="completed"||d.status==="failed"||d.status==="skipped").length,m=Math.round(p/u*100);return await r.update(t,d=>({...d,currentTask:{...d.currentTask,subtasks:o,currentSubtaskIndex:c<u?c:n,subtaskProgress:{completed:p,total:u,percentage:m}},lastUpdated:g()})),await r.publish(t,"subtask.skipped",{taskId:s.currentTask.id,subtaskId:i.id,description:i.description,reason:e}),c<u?o[c]:null}a(Qr,"skipSubtask");async function Zr(r,t,e){let s=await r.read(t);if(!s.currentTask?.subtasks)return null;let n=s.currentTask.currentSubtaskIndex||0,i=s.currentTask.subtasks[n];if(!i)return null;let o=[...s.currentTask.subtasks];o[n]={...i,status:"blocked",output:`Blocked: ${e}`,blockReason:e};let c=n+1,u=o.length;return c<u&&(o[c]={...o[c],status:"in_progress",startedAt:g()}),await r.update(t,p=>({...p,currentTask:{...p.currentTask,subtasks:o,currentSubtaskIndex:c<u?c:n},lastUpdated:g()})),await r.publish(t,"subtask.blocked",{taskId:s.currentTask.id,subtaskId:i.id,description:i.description,blocker:e}),c<u?o[c]:null}a(Zr,"blockSubtask");C();async function tn(r,t,e,s){let n={...e,workspaceId:s,startedAt:g()};return await r.update(t,i=>({...i,activeTasks:[...i.activeTasks||[],n],lastUpdated:g()})),await r.publish(t,"task.started",{taskId:n.id,description:n.description,startedAt:n.startedAt,sessionId:n.sessionId,workspaceId:s}),n}a(tn,"startTaskInWorkspace");async function en(r,t,e){return((await r.read(t)).activeTasks||[]).find(n=>n.workspaceId===e)??null}a(en,"getCurrentTaskForWorkspace");async function sn(r,t,e,s){let n=await r.read(t),o=(n.activeTasks||[]).find(d=>d.workspaceId===e);if(!o)return null;let c=g(),u=r.createTaskHistoryEntry(o,c,s),p=r.getTaskHistoryFromState(n),m=[u,...p].slice(0,r.maxTaskHistory);return await r.update(t,d=>({...d,activeTasks:(d.activeTasks||[]).filter(h=>h.workspaceId!==e),taskHistory:m,lastUpdated:c})),await r.publish(t,"task.completed",{taskId:o.id,description:o.description,startedAt:o.startedAt,completedAt:c,workspaceId:e}),o}a(sn,"completeTaskInWorkspace");async function rn(r,t){return(await r.read(t)).activeTasks||[]}a(rn,"getActiveTasks");async function nn(r,t){return((await r.read(t)).activeTasks||[]).length}a(nn,"getActiveTaskCount");async function on(r,t,e,s){let i=(await r.read(t)).activeTasks||[],o=i.findIndex(u=>u.workspaceId===e);if(o===-1)return null;let c={...i[o],...s,workspaceId:e};return await r.update(t,u=>{let p=[...u.activeTasks||[]];return p[o]=c,{...u,activeTasks:p,lastUpdated:g()}}),c}a(on,"updateWorkspaceTask");async function an(r,t,e,s){let n=await r.read(t);if(!n.currentTask)return null;let i=(n.currentTask.tokensIn||0)+e,o=(n.currentTask.tokensOut||0)+s;return await r.update(t,c=>({...c,currentTask:{...c.currentTask,tokensIn:i,tokensOut:o},lastUpdated:g()})),{tokensIn:i,tokensOut:o}}a(an,"addTokens");$e();var We=class extends ot{static{a(this,"StateStorage")}constructor(){super("state.json",Sr)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],activeTasks:[],lastUpdated:""}}getEventType(t){return`state.${t}d`}validateTransition(t,e){let s=Ne.getCurrentState(t),n=Ne.canTransition(s,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 s=await this.read(t);this.validateTransition(s,"task");let n={...e,startedAt:g()};return await this.update(t,i=>({...i,currentTask:n,lastUpdated:g()})),await this.publishEvent(t,"task.started",{taskId:n.id,description:n.description,startedAt:n.startedAt,sessionId:n.sessionId}),n}async updateCurrentTask(t,e){let s=await this.read(t);if(!s.currentTask)return null;let n={...s.currentTask,...e};return await this.update(t,i=>({...i,currentTask:n,lastUpdated:g()})),n}async completeTask(t,e){let s=await this.read(t),n=s.currentTask;if(!n)return null;this.validateTransition(s,"done");let i=g(),o=this.createTaskHistoryEntry(n,i,e),c=this.getTaskHistoryFromState(s),u=[o,...c].slice(0,this.maxTaskHistory);return await this.update(t,p=>({...p,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,s){let n=(t.subtasks||[]).filter(c=>c.status==="completed"&&c.summary).map(c=>c.summary),i=n.length>0?n.map(c=>c.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 s&&(o.feedback=s),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 Nr(this.lifecycleBackend(),t,e)}async resumeTask(t,e){return Ir(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 Dr(this.lifecycleBackend(),t)}async archiveStalePausedTasks(t){return Lr(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 Or(this.queryBackend(),t)}async hasTask(t){return jr(this.queryBackend(),t)}async getPausedTask(t){return Mr(this.queryBackend(),t)}async getAllPausedTasks(t){return Fr(this.queryBackend(),t)}async getTaskHistory(t){return Ue(this.queryBackend(),t)}async getMostRecentTask(t){return Ur(this.queryBackend(),t)}async getTaskHistoryByType(t,e){return Xr(this.queryBackend(),t,e)}async getAggregatedFeedback(t){return $r(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,s){return tn(this.workspaceBackend(),t,e,s)}async getCurrentTaskForWorkspace(t,e){return en(this.workspaceBackend(),t,e)}async completeTaskInWorkspace(t,e,s){return sn(this.workspaceBackend(),t,e,s)}async getActiveTasks(t){return rn(this.workspaceBackend(),t)}async getActiveTaskCount(t){return nn(this.workspaceBackend(),t)}async updateWorkspaceTask(t,e,s){return on(this.workspaceBackend(),t,e,s)}async addTokens(t,e,s){return an(this.workspaceBackend(),t,e,s)}subtaskBackend(){return{read:this.read.bind(this),update:this.update.bind(this),publish:this.publishEvent.bind(this)}}async createSubtasks(t,e){return Wr(this.subtaskBackend(),t,e)}async completeSubtask(t,e){return Br(this.subtaskBackend(),t,e)}async getCurrentSubtask(t){return Hr(this.subtaskBackend(),t)}async getNextSubtask(t){return qr(this.subtaskBackend(),t)}async getPreviousSubtask(t){return Xe(this.subtaskBackend(),t)}async getPreviousHandoff(t){return Gr(this.subtaskBackend(),t)}async getSubtasks(t){return Yr(this.subtaskBackend(),t)}async getSubtaskProgress(t){return Jr(this.subtaskBackend(),t)}async hasSubtasks(t){return zr(this.subtaskBackend(),t)}async areAllSubtasksComplete(t){return Kr(this.subtaskBackend(),t)}async failSubtask(t,e){return Vr(this.subtaskBackend(),t,e)}async skipSubtask(t,e){return Qr(this.subtaskBackend(),t,e)}async blockSubtask(t,e){return Zr(this.subtaskBackend(),t,e)}},at=new We;Be();V();import wo from"node:fs/promises";import ct from"node:path";var ko={"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}},Eo="claude-sonnet-4.5";function He(r){return!r||r.length===0?0:Math.ceil(r.length/4)}a(He,"countTokens");var gn=["claude-sonnet-4.5","claude-opus-4.5","claude-opus-4-6","gpt-4o","gemini-1.5-pro"];function mn(r,t){let e=ko[t],s=r/1e3*e.input,n=r/1e3*e.output*.3;return{inputSaved:s,outputPotential:n,total:s+n}}a(mn,"calculateModelCost");function So(r){return r<.001?"<$0.01":r<.01?`$${r.toFixed(3)}`:`$${r.toFixed(2)}`}a(So,"formatCostSaved");function fn(r,t){let e=He(r),s=He(t),n=Math.max(0,e-s),i=e>0?(e-s)/e:0,o=mn(n,Eo),c=gn.map(u=>({model:u,...mn(n,u)}));return{tokens:{original:e,filtered:s,saved:n},compression:Math.max(0,Math.min(1,i)),cost:{saved:o.total,formatted:So(o.total),byModel:c}}}a(fn,"measureCompression");function qt(r){let t=He(r);return{tokens:{original:t,filtered:t,saved:0},compression:0,cost:{saved:0,formatted:"$0.00",byModel:gn.map(e=>({model:e,inputSaved:0,outputPotential:0,total:0}))}}}a(qt,"noCompression");var bo={".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"},hn=[{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}],_o=[{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}],vo=[{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}],xo=[{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}],yn=[{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}],Po={typescript:hn,javascript:hn,python:_o,go:vo,rust:xo,java:yn,csharp:yn,php:[],ruby:[],unknown:[]};async function Tn(r,t=process.cwd()){let e=ct.isAbsolute(r)?r:ct.join(t,r),s=ct.resolve(t),n=ct.resolve(e);if(!n.startsWith(s+ct.sep)&&n!==s)return{file:r,language:"unknown",signatures:[],fallback:!0,fallbackReason:"Path traversal denied: file is outside project directory",metrics:qt("")};let i;try{i=await wo.readFile(e,"utf-8")}catch(d){if(L(d))return{file:r,language:"unknown",signatures:[],fallback:!0,fallbackReason:"File not found",metrics:qt("")};throw d}let o=ct.extname(r).toLowerCase(),c=bo[o]||"unknown",u=Po[c];if(!u||u.length===0)return{file:r,language:c,signatures:[],fallback:!0,fallbackReason:`No extraction patterns for ${c}`,metrics:qt(i)};let p=Ro(i,u),m=p.map(d=>`${d.exported?"export ":""}${d.type} ${d.name}: ${d.signature}`).join(`
|
|
570
|
+
`);return{file:r,language:c,signatures:p,fallback:!1,metrics:fn(i,m)}}a(Tn,"extractSignatures");function Ro(r,t){let e=[],s=r.split(`
|
|
571
|
+
`),n=new Set;for(let i of t){i.pattern.lastIndex=0;let o;for(;(o=i.pattern.exec(r))!==null;){let c=o[i.nameIndex];if(!c)continue;let u=`${i.type}:${c}`;if(n.has(u))continue;n.add(u);let p=o.index,m=r.substring(0,p).split(`
|
|
572
|
+
`).length,d=o[0].trim(),h;if(m>1){let y=s[m-2]?.trim();(y?.startsWith("/**")||y?.startsWith("///")||y?.startsWith("#"))&&(h=y)}e.push({type:i.type,name:c,signature:Ao(d),exported:i.exported||!1,line:m,docstring:h})}}return e.sort((i,o)=>i.line-o.line)}a(Ro,"extractFromContent");function Ao(r){return r.replace(/\{$/,"").replace(/\s+/g," ").trim()}a(Ao,"cleanSignature");function kn(r){let t=r;t.tool("prjct_relevant_files","BM25-ranked files relevant to a query",{projectPath:tt.string().describe("Project directory path"),query:tt.string().describe("Task or query to find relevant files for"),maxFiles:tt.number().optional().default(10).describe("Max files to return")},S("prjct_relevant_files",async e=>{let s=await Ht(e.query,e.projectPath,{maxFiles:e.maxFiles,minScore:.1});if(s.files.length===0)return{content:[{type:"text",text:"No relevant files found."}]};let n=s.files.map(o=>`- \`${o.path}\` (score: ${Math.round(o.score*100)}%) \u2014 ${o.reasons.join(", ")}`);return{content:[{type:"text",text:`## Relevant Files (${s.files.length}/${s.metrics.filesScanned} scanned)
|
|
565
573
|
|
|
566
574
|
${n.join(`
|
|
567
|
-
`)}`}]}})),t.tool("prjct_signatures","Code signatures from a file (90% token reduction vs full content)",{projectPath:tt.string().describe("Project directory path"),filePath:tt.string().describe("Relative file path to extract signatures from")},S("prjct_signatures",async e=>{let s=await Tn(e.filePath,e.projectPath);if(s.signatures.length===0)return{content:[{type:"text",text:s.fallback?`No signatures extracted: ${s.fallbackReason}`:"No signatures found."}]};let n=s.signatures.map(
|
|
575
|
+
`)}`}]}})),t.tool("prjct_signatures","Code signatures from a file (90% token reduction vs full content)",{projectPath:tt.string().describe("Project directory path"),filePath:tt.string().describe("Relative file path to extract signatures from")},S("prjct_signatures",async e=>{let s=await Tn(e.filePath,e.projectPath);if(s.signatures.length===0)return{content:[{type:"text",text:s.fallback?`No signatures extracted: ${s.fallbackReason}`:"No signatures found."}]};let n=s.signatures.map(c=>`${c.exported?"export ":""}${c.type} ${c.name}: ${c.signature}${c.docstring?` // ${c.docstring}`:""}`),i=s.metrics?.compression?` (${Math.round(s.metrics.compression*100)}% reduction)`:"";return{content:[{type:"text",text:`## ${s.file} (${s.language})
|
|
568
576
|
\`\`\`
|
|
569
577
|
${n.join(`
|
|
570
578
|
`)}
|
|
571
579
|
\`\`\`${i}`}]}})),t.tool("prjct_history","Recent completed tasks with outcomes",{projectPath:tt.string().describe("Project directory path"),limit:tt.number().optional().default(10).describe("Max results")},S("prjct_history",async e=>{let s=await x(e.projectPath),n=await at.getTaskHistory(s);if(n.length===0)return{content:[{type:"text",text:"No task history."}]};let o=n.slice(-e.limit).reverse().map(u=>{let p=[`- **${u.title}**`];return u.completedAt&&p.push(`completed: ${u.completedAt}`),u.classification&&p.push(`type: ${u.classification}`),p.join(" | ")});return{content:[{type:"text",text:`## Task History (${n.length} total)
|
|
572
580
|
|
|
573
581
|
${o.join(`
|
|
574
|
-
`)}`}]}}))}
|
|
582
|
+
`)}`}]}}))}a(kn,"registerFileTools");ut();import{z as P}from"zod";var xn=[{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/}],dp=xn.map(r=>r.name);function Pn(r){let t=[];for(let{name:e,re:s}of xn)s.test(r)&&t.push(e);return t}a(Pn,"scanForSecrets");var Rn=`Base types: ${_n.join(", ")}. Any lowercase identifier is accepted (e.g. "recipe", "okr").`;function An(r){let t=r;t.tool("prjct_mem_save",`Save a memory entry. ${Rn} Secret-like content is refused unless force=true.`,{projectPath:P.string().describe("Project directory path"),type:P.string().describe("Memory type (fact/decision/learning/... or user-defined)"),content:P.string().describe("The memory content. Freeform text."),tags:P.record(P.string(),P.string()).optional().describe('Key:value tags (e.g. {domain: "auth"})'),source:P.string().optional().describe("Task id this memory came from, if any"),force:P.boolean().optional().describe("Bypass the secret-like-content refusal. Default false.")},S("prjct_mem_save",async e=>{await x(e.projectPath);let s=e.type.toLowerCase().trim();if(!s||!/^[a-z][a-z0-9-]*$/.test(s))return{content:[{type:"text",text:`Invalid type '${e.type}'. Lowercase letters + dashes only. ${Rn}`}]};let n=Pn(e.content);return n.length>0&&!e.force?{content:[{type:"text",text:`Refused \u2014 content looks like a secret (${n.join(", ")}). Re-call with force=true if intentional.`}]}:(await O.remember(e.projectPath,{type:s,content:e.content,tags:e.tags??{},source:e.source}),{content:[{type:"text",text:`Saved ${s}: ${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:P.string().describe("Project directory path"),topic:P.string().optional().describe("Keyword to match over content + tag values"),types:P.array(P.string()).optional().describe("Restrict to these types"),tags:P.record(P.string(),P.string()).optional().describe("Require exact match on these k:v pairs"),limit:P.number().optional().default(25).describe("Max entries (default 25)")},S("prjct_mem_list",async e=>{let s=await x(e.projectPath),n=O.recall(s,{topic:e.topic,types:e.types,tags:e.tags,limit:e.limit});return{content:[{type:"text",text:wt(n)}]}})),t.tool("prjct_mem_similar","Find memory entries similar to a free-text description. Keyword-based, best-effort.",{projectPath:P.string().describe("Project directory path"),description:P.string().describe("Free-text description to find similar memories for"),limit:P.number().optional().default(10).describe("Max results (default 10)")},S("prjct_mem_similar",async e=>{let s=await x(e.projectPath),n=O.similar(s,e.description,e.limit);return n.length===0?{content:[{type:"text",text:"No similar memories found."}]}:{content:[{type:"text",text:wt(n)}]}})),t.tool("prjct_mem_forget","Remove a memory entry by id. Ids are stable \u2014 pull them from `prjct_mem_list`.",{projectPath:P.string().describe("Project directory path"),id:P.string().describe('Memory id (e.g. "mem_42" or "ship_7")')},S("prjct_mem_forget",async e=>({content:[{type:"text",text:"Forget is not implemented in the projectMemory API yet. Entries persist event-sourced \u2014 filter them out client-side, or drop the underlying event manually."}]})))}a(An,"registerMemoryTools");ut();import{z as Ve}from"zod";C();j();var Je=class{static{a(this,"LLMAnalysisStorage")}save(t,e){let s=E.getDb(t),n=g();s.transaction(()=>{s.prepare("UPDATE llm_analysis SET status = 'superseded', superseded_at = ? WHERE status = 'active'").run(n),s.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=E.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?E.get(t,"SELECT commit_hash FROM llm_analysis WHERE status = 'active' LIMIT 1")?.commit_hash===e:!1}getAllFull(t){return E.query(t,"SELECT id, commit_hash, status, analyzed_at, superseded_at, analysis FROM llm_analysis ORDER BY id DESC").map(s=>({id:s.id,status:s.status,commitHash:s.commit_hash,analyzedAt:s.analyzed_at,supersededAt:s.superseded_at,analysis:JSON.parse(s.analysis)}))}getHistory(t,e=10){return E.query(t,"SELECT id, commit_hash, status, analyzed_at, analysis FROM llm_analysis ORDER BY id DESC LIMIT ?",e).map(n=>{let i=JSON.parse(n.analysis);return{id:n.id,commitHash:n.commit_hash,status:n.status,analyzedAt:n.analyzed_at,patternCount:i.patterns.length}})}},Fo=new Je,Cn=Fo;Ke();function On(r){let t=r;t.tool("prjct_task_status","Current task, duration, subtasks, and queue",{projectPath:Ve.string().describe("Project directory path")},S("prjct_task_status",async e=>{let s=await x(e.projectPath),n=await at.getCurrentTask(s),i=await Gt.getActiveTasks(s),o=[];if(n?(o.push(`## Active Task
|
|
575
583
|
**${n.description}**`),n.branch&&o.push(`Branch: ${n.branch}`),o.push(`Started: ${n.startedAt}`)):o.push("No active task."),i.length>0){o.push(`
|
|
576
|
-
## Queue (${i.length} tasks)`);for(let
|
|
584
|
+
## Queue (${i.length} tasks)`);for(let c of i.slice(0,10))o.push(`- ${c.description} [${c.priority||"medium"}]`)}return{content:[{type:"text",text:o.join(`
|
|
577
585
|
`)}]}})),t.tool("prjct_analysis","LLM analysis: stack, patterns, anti-patterns, conventions",{projectPath:Ve.string().describe("Project directory path")},S("prjct_analysis",async e=>{let s=await x(e.projectPath),n=Cn.getActive(s);if(!n)return{content:[{type:"text",text:"No analysis available. Run `prjct sync`."}]};let i=["## Project Analysis"];if(n.stack&&(i.push(`
|
|
578
586
|
### Stack`),n.stack.languages?.length&&i.push(`Languages: ${n.stack.languages.join(", ")}`),n.stack.frameworks?.length&&i.push(`Frameworks: ${n.stack.frameworks.join(", ")}`),n.stack.packageManager&&i.push(`Package Manager: ${n.stack.packageManager}`)),n.patterns?.length){i.push(`
|
|
579
587
|
### Patterns (${n.patterns.length})`);for(let o of n.patterns)i.push(`- **${o.name}**: ${o.description}`)}if(n.antiPatterns?.length){i.push(`
|
|
580
588
|
### Anti-Patterns (${n.antiPatterns.length})`);for(let o of n.antiPatterns)i.push(`- **${o.issue}**: ${o.suggestion}`)}if(n.conventions?.length){i.push(`
|
|
581
589
|
### Conventions (${n.conventions.length})`);for(let o of n.conventions)i.push(`- [${o.category}] ${o.rule}`)}return{content:[{type:"text",text:i.join(`
|
|
582
|
-
`)}]}})),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:Ve.string().describe("Project directory path")},S("prjct_patterns",async e=>{let s=await x(e.projectPath),n=O.recall(s,{types:["decision","pattern","anti-pattern","gotcha"],limit:50});return n.length===0?{content:[{type:"text",text:"No decisions or patterns captured yet."}]}:{content:[{type:"text",text:wt(n)}]}}))}
|
|
590
|
+
`)}]}})),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:Ve.string().describe("Project directory path")},S("prjct_patterns",async e=>{let s=await x(e.projectPath),n=O.recall(s,{types:["decision","pattern","anti-pattern","gotcha"],limit:50});return n.length===0?{content:[{type:"text",text:"No decisions or patterns captured yet."}]}:{content:[{type:"text",text:wt(n)}]}}))}a(On,"registerProjectTools");import{z as f}from"zod";yt();ut();Jt();Yt();C();import{execFile as Jo}from"node:child_process";import{promisify as zo}from"node:util";var Ko=zo(Jo);async function Vo(r){try{let{stdout:t}=await Ko("git",["rev-parse","HEAD"],{cwd:r}),e=t.trim();return/^[0-9a-f]{7,40}$/.test(e)?e:null}catch{return null}}a(Vo,"readGitHead");var es=class{static{a(this,"SpecService")}async create(t,e){let s=await this.requireProjectId(t),n=e.content.notes??"";if(e.autoContext!==!1&&!n.trim()){let{inferSpecContext:u,warnNoContextMatch:p}=await Promise.resolve().then(()=>(Fn(),Mn)),m=await u(e.title,s,t);m.empty?p(e.title):n=m.notesBlock}let o=z.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:n}),c=R.create(s,{title:e.title,content:o,tags:e.tags});return await O.remember(t,{type:"spec",content:`${c.title}
|
|
583
591
|
|
|
584
|
-
Goal: ${
|
|
585
|
-
`)}]}})),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:f.string().describe("Project directory path"),status:f.enum(lt).optional().describe("Filter by status: draft|reviewed|in_progress|shipped|archived"),includeArchived:f.boolean().optional().describe("Include archived specs (default: false)")},S("prjct_spec_list",async e=>{let s=await x(e.projectPath),n=R.list(s,{status:e.status,includeArchived:e.includeArchived});if(n.length===0)return{content:[{type:"text",text:"_No specs match. Start one with `prjct_spec_create`._"}]};let i=["# Specs",""];for(let o of n){let
|
|
592
|
+
Goal: ${c.content.goal}`,tags:{...e.tags??{},spec_id:c.id,status:c.status},source:c.id,provenance:"declared"}),c}async get(t,e){let s=await this.requireProjectId(t);return R.get(s,e)}async list(t,e={}){let s=await this.requireProjectId(t);return R.list(s,e)}async setStatus(t,e,s){let n=await this.requireProjectId(t),i=R.setStatus(n,e,s);return i&&await O.remember(t,{type:"spec",content:`Spec status \u2192 ${s}: ${i.title}`,tags:{spec_id:e,status:s,event:"status_change"},source:e}),i}async update(t,e,s){let n=await this.requireProjectId(t);return R.updateContent(n,e,s)}async recordReview(t,e,s,n){let i=await this.requireProjectId(t),o=R.get(i,e);if(!o)return null;let c={...n,ts:g()},u={...o.content,reviews:{...o.content.reviews??{},[s]:c}},p=R.updateContent(i,e,u);if(p&&this.allReviewsPass(p.content)&&p.status==="draft"){let m=R.setStatus(i,e,"reviewed");if(m){let{breakdownSpecToTasks:d}=await Promise.resolve().then(()=>(Xn(),Un));return await d(i,t,m),R.get(i,e)}return m}return p}async linkTask(t,e,s){let n=await this.requireProjectId(t);return R.linkTask(n,e,s)}async ship(t,e,s){let n=await this.requireProjectId(t);s!==void 0&&R.setShippedPr(n,e,s);let i=await Vo(t);return i&&R.setShippedSha(n,e,i),R.setStatus(n,e,"shipped")}unmetCriteria(t,e=new Set){return t.content.acceptance_criteria.filter(s=>!e.has(s))}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 H.readConfig(t);if(!e?.projectId)throw new Error("not a prjct project (run `prjct init` first)");return e.projectId}},Y=new es;Jt();Yt();function $n(r){let t=r;t.tool("prjct_spec_create",'CALL THIS when the user describes a feature, fix, or initiative WITH goals or stakes attached (e.g. "we need rate limiting on auth", "fix onboarding", "let\'s build SDD"). Drafts a spec \u2014 Goal/ELI10/Stakes/Acceptance criteria/Scope/Out-of-scope/Risks/Test plan. The structured fields default to empty; populate them by calling `prjct_spec_update` once you have the answers. Skip this tool only for routine work (single-file fix, doc tweak, GTD capture) \u2014 for that, use `prjct_capture` or the matching memory tool.',{projectPath:f.string().describe("Project directory path"),title:f.string().describe("One-line title (what you'd say to a coworker walking by)"),goal:f.string().describe("What success looks like, 1-3 sentences. Concrete, observable."),eli10:f.string().optional().describe("Plain English a 16-year-old follows, 2-4 sentences"),stakes:f.string().optional().describe("What breaks if we ship the wrong thing"),acceptance_criteria:f.array(f.string()).optional().describe("Testable, observable list. Each item ends in a verifiable claim."),scope:f.array(f.string()).optional().describe("What's IN \u2014 file paths, modules, surfaces"),out_of_scope:f.array(f.string()).optional().describe("What's OUT \u2014 anti-creep shield"),risks:f.array(f.object({risk:f.string(),mitigation:f.string()})).optional().describe("Each risk has a mitigation; a risk without one is just a complaint"),test_plan:f.array(f.string()).optional().describe("How you prove acceptance criteria"),tags:f.record(f.string(),f.string()).optional().describe('Key:value tags (e.g. {domain: "auth", priority: "high"})')},S("prjct_spec_create",async e=>{let s=await Y.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: ${s.title}`,"",`id: ${s.id}`,`status: ${s.status}`,`goal: ${s.content.goal}`,"","Next: `prjct_spec_audit` to dispatch the three review subagents (strategic / architecture / design) in parallel."].join(`
|
|
593
|
+
`)}]}})),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:f.string().describe("Project directory path"),status:f.enum(lt).optional().describe("Filter by status: draft|reviewed|in_progress|shipped|archived"),includeArchived:f.boolean().optional().describe("Include archived specs (default: false)")},S("prjct_spec_list",async e=>{let s=await x(e.projectPath),n=R.list(s,{status:e.status,includeArchived:e.includeArchived});if(n.length===0)return{content:[{type:"text",text:"_No specs match. Start one with `prjct_spec_create`._"}]};let i=["# Specs",""];for(let o of n){let c=o.content.acceptance_criteria.length,u=o.content.linked_tasks.length;i.push(`## ${o.title}
|
|
586
594
|
- id: \`${o.id}\`
|
|
587
595
|
- status: ${o.status}
|
|
588
|
-
- acceptance criteria: ${
|
|
596
|
+
- acceptance criteria: ${c}
|
|
589
597
|
- linked tasks: ${u}
|
|
590
598
|
- created: ${o.createdAt}`),i.push("")}return{content:[{type:"text",text:i.join(`
|
|
591
|
-
`)}]}})),t.tool("prjct_spec_get","Fetch one spec by id, including all structured fields (goal, acceptance criteria, scope, risks, reviews, linked tasks).",{projectPath:f.string().describe("Project directory path"),id:f.string().describe("Spec id")},S("prjct_spec_get",async e=>{let s=await Y.get(e.projectPath,e.id);return s?{content:[{type:"text",text:Qo(s)}]}:{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:f.string().describe("Project directory path"),id:f.string().describe("Spec id"),content:f.object({goal:f.string(),eli10:f.string().optional(),stakes:f.string().optional(),acceptance_criteria:f.array(f.string()).optional(),scope:f.array(f.string()).optional(),out_of_scope:f.array(f.string()).optional(),risks:f.array(f.object({risk:f.string(),mitigation:f.string()})).optional(),test_plan:f.array(f.string()).optional(),notes:f.string().optional(),linked_tasks:f.array(f.string()).optional()}).describe("Full SpecContent shape \u2014 Zod-validated server-side")},S("prjct_spec_update",async e=>{let s=z.parse(e.content),n=await Y.update(e.projectPath,e.id,s);return n?{content:[{type:"text",text:`\u2713 spec updated: ${n.title}`}]}:{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]}})),t.tool("prjct_spec_set_status","Promote / demote a spec lifecycle state. Reviewers passing is auto-promoting (draft \u2192 reviewed); use this tool to mark a spec `in_progress` when work starts, `archived` when superseded, or `shipped` (use `prjct_spec_ship` instead when shipping for the first time, since it also records the PR).",{projectPath:f.string().describe("Project directory path"),id:f.string().describe("Spec id"),status:f.enum(lt).describe("Target status")},S("prjct_spec_set_status",async e=>await Y.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 THIS before any implementation work begins on a spec. Returns a dispatch prompt for THREE review subagents (strategic / architecture / design). RUN ALL THREE IN PARALLEL via your Agent / Task tool \u2014 one tool-use block per reviewer in the SAME message. Each returns a verdict (pass | fail) + notes. Persist each via `prjct_spec_record_review`. All three pass \u2192 the spec auto-promotes draft \u2192 reviewed and is safe to start a task against.",{projectPath:f.string().describe("Project directory path"),id:f.string().describe("Spec id to audit")},S("prjct_spec_audit",async e=>{let s=await Y.get(e.projectPath,e.id);return s?{content:[{type:"text",text:Zo(s.id,s.title,s.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:f.string().describe("Project directory path"),id:f.string().describe("Spec id"),reviewer:f.enum(Ze).describe("Which reviewer"),verdict:f.enum(["pass","fail"]).describe("Verdict"),notes:f.string().describe("2-4 sentence notes from the subagent")},S("prjct_spec_record_review",async e=>{let s=await Y.recordReview(e.projectPath,e.id,e.reviewer,{verdict:e.verdict,notes:e.notes});if(!s)return{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]};let n=s.status==="reviewed"?" (all reviewers passed \u2192 status: reviewed)":"";return{content:[{type:"text",text:`\u2713 ${e.reviewer} \u2192 ${e.verdict}${n}`}]}})),t.tool("prjct_spec_link_task","Link a task to its spec. Call this AFTER starting the task (when the user begins implementation) so `prjct_ship` later knows which spec to gate against. Idempotent \u2014 re-linking the same task is a no-op.",{projectPath:f.string().describe("Project directory path"),specId:f.string().describe("Spec id"),taskId:f.string().describe("Task id (from `prjct_session_start_task` or stateStorage)")},S("prjct_spec_link_task",async e=>await Y.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:f.string().describe("Project directory path"),id:f.string().describe("Spec id"),pr:f.number().optional().describe("PR / MR number that delivered the spec")},S("prjct_spec_ship",async e=>{let s=await Y.ship(e.projectPath,e.id,e.pr);return s?{content:[{type:"text",text:`\u2713 spec shipped: ${s.title}${e.pr?` (PR #${e.pr})`:""}`}]}:{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]}}))}
|
|
592
|
-
`)}
|
|
593
|
-
`)}
|
|
594
|
-
VALUES (?, ?, ?, ?, 0, 1, ?)`,e.name,e.description??null,s,s,e.metadata?JSON.stringify(e.metadata):null);let n=T.get(t,"SELECT id FROM custom_workflows WHERE name = ?",e.name);if(!n)throw new Error(`Failed to create workflow: ${e.name}`);return G({projectId:t,entityType:"custom_workflows",entityId:String(n.id),eventType:"upsert",data:{id:n.id,name:e.name,description:e.description??null,metadata:e.metadata??null,created_at:s,updated_at:s,is_builtin:0,enabled:1}}),n.id}getWorkflow(t,e){let s=T.get(t,"SELECT * FROM custom_workflows WHERE name = ?",e);return s?this.rowToWorkflow(s):null}getAllWorkflows(t,e=!1){let s=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 T.query(t,s).map(i=>this.rowToWorkflow(i))}updateWorkflow(t,e,s){if(!this.getWorkflow(t,e))return!1;let i=new Date().toISOString(),o=[],
|
|
595
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,e.type,e.command,e.position,e.action,e.description??null,e.enabled?1:0,e.timeoutMs,e.createdAt,n,e.whenExpr??null,e.parallel===!1?0:1,e.trustSource??"local");let o=E.get(t,"SELECT last_insert_rowid() as id")?.id??0;return o>0&&G({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:n,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 E.get(t,"SELECT id FROM workflow_rules WHERE id = ?",e)?(E.run(t,"DELETE FROM workflow_rules WHERE id = ?",e),G({projectId:t,entityType:"workflow_rules",entityId:String(e),eventType:"delete",data:{id:e}}),!0):!1}updateRule(t,e,s){if(!E.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:
|
|
596
|
-
### ${
|
|
597
|
-
`)}]}})),t.tool("prjct_workflow_list","List all workflows for this project (built-in + custom)",{projectPath:Kt.string().describe("Project directory path")},S("prjct_workflow_list",async e=>{let s=await x(e.projectPath),n=zt.getAllWorkflows(s);if(n.length===0)return{content:[{type:"text",text:"No workflows configured."}]};let i=n.map(o=>{let
|
|
599
|
+
`)}]}})),t.tool("prjct_spec_get","Fetch one spec by id, including all structured fields (goal, acceptance criteria, scope, risks, reviews, linked tasks).",{projectPath:f.string().describe("Project directory path"),id:f.string().describe("Spec id")},S("prjct_spec_get",async e=>{let s=await Y.get(e.projectPath,e.id);return s?{content:[{type:"text",text:Qo(s)}]}:{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:f.string().describe("Project directory path"),id:f.string().describe("Spec id"),content:f.object({goal:f.string(),eli10:f.string().optional(),stakes:f.string().optional(),acceptance_criteria:f.array(f.string()).optional(),scope:f.array(f.string()).optional(),out_of_scope:f.array(f.string()).optional(),risks:f.array(f.object({risk:f.string(),mitigation:f.string()})).optional(),test_plan:f.array(f.string()).optional(),notes:f.string().optional(),linked_tasks:f.array(f.string()).optional()}).describe("Full SpecContent shape \u2014 Zod-validated server-side")},S("prjct_spec_update",async e=>{let s=z.parse(e.content),n=await Y.update(e.projectPath,e.id,s);return n?{content:[{type:"text",text:`\u2713 spec updated: ${n.title}`}]}:{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]}})),t.tool("prjct_spec_set_status","Promote / demote a spec lifecycle state. Reviewers passing is auto-promoting (draft \u2192 reviewed); use this tool to mark a spec `in_progress` when work starts, `archived` when superseded, or `shipped` (use `prjct_spec_ship` instead when shipping for the first time, since it also records the PR).",{projectPath:f.string().describe("Project directory path"),id:f.string().describe("Spec id"),status:f.enum(lt).describe("Target status")},S("prjct_spec_set_status",async e=>await Y.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 THIS before any implementation work begins on a spec. Returns a dispatch prompt for THREE review subagents (strategic / architecture / design). RUN ALL THREE IN PARALLEL via your Agent / Task tool \u2014 one tool-use block per reviewer in the SAME message. Each returns a verdict (pass | fail) + notes. Persist each via `prjct_spec_record_review`. All three pass \u2192 the spec auto-promotes draft \u2192 reviewed and is safe to start a task against.",{projectPath:f.string().describe("Project directory path"),id:f.string().describe("Spec id to audit")},S("prjct_spec_audit",async e=>{let s=await Y.get(e.projectPath,e.id);return s?{content:[{type:"text",text:Zo(s.id,s.title,s.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:f.string().describe("Project directory path"),id:f.string().describe("Spec id"),reviewer:f.enum(Ze).describe("Which reviewer"),verdict:f.enum(["pass","fail"]).describe("Verdict"),notes:f.string().describe("2-4 sentence notes from the subagent")},S("prjct_spec_record_review",async e=>{let s=await Y.recordReview(e.projectPath,e.id,e.reviewer,{verdict:e.verdict,notes:e.notes});if(!s)return{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]};let n=s.status==="reviewed"?" (all reviewers passed \u2192 status: reviewed)":"";return{content:[{type:"text",text:`\u2713 ${e.reviewer} \u2192 ${e.verdict}${n}`}]}})),t.tool("prjct_spec_link_task","Link a task to its spec. Call this AFTER starting the task (when the user begins implementation) so `prjct_ship` later knows which spec to gate against. Idempotent \u2014 re-linking the same task is a no-op.",{projectPath:f.string().describe("Project directory path"),specId:f.string().describe("Spec id"),taskId:f.string().describe("Task id (from `prjct_session_start_task` or stateStorage)")},S("prjct_spec_link_task",async e=>await Y.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:f.string().describe("Project directory path"),id:f.string().describe("Spec id"),pr:f.number().optional().describe("PR / MR number that delivered the spec")},S("prjct_spec_ship",async e=>{let s=await Y.ship(e.projectPath,e.id,e.pr);return s?{content:[{type:"text",text:`\u2713 spec shipped: ${s.title}${e.pr?` (PR #${e.pr})`:""}`}]}:{content:[{type:"text",text:`_Spec not found: ${e.id}_`}]}}))}a($n,"registerSpecTools");function Qo(r){let t=r.content,e=[`# ${r.title}`,"",`**id:** \`${r.id}\` \xB7 **status:** ${r.status} \xB7 **created:** ${r.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 s of t.acceptance_criteria)e.push(`- [ ] ${s}`)}if(t.scope.length>0){e.push("","## Scope");for(let s of t.scope)e.push(`- ${s}`)}if(t.out_of_scope.length>0){e.push("","## Out of scope");for(let s of t.out_of_scope)e.push(`- ${s}`)}if(t.risks.length>0){e.push("","## Risks");for(let s of t.risks)e.push(`- **${s.risk}** \u2014 ${s.mitigation}`)}if(t.test_plan.length>0){e.push("","## Test plan");for(let s of t.test_plan)e.push(`- ${s}`)}if(t.reviews){e.push("","## Reviews");for(let s of Ze){let n=t.reviews[s];n&&e.push(`- **${s}:** ${n.verdict} \u2014 ${n.notes} _(${n.ts})_`)}}return t.linked_tasks.length>0&&e.push("","## Linked tasks",...t.linked_tasks.map(s=>`- ${s}`)),t.notes&&e.push("","## Notes",t.notes),e.join(`
|
|
600
|
+
`)}a(Qo,"renderSpecMarkdown");function Zo(r,t,e){let s=JSON.stringify(e);return[`# audit-spec dispatch \u2014 ${t}`,"",`Spec id: \`${r}\``,"","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",s,"```","","## After dispatch","For each reviewer that returns:",` Call \`prjct_spec_record_review\` with id="${r}", 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(`
|
|
601
|
+
`)}a(Zo,"renderAuditDispatch");import{z as Kt}from"zod";Et();j();var ss=class{static{a(this,"CustomWorkflowStorage")}createWorkflow(t,e){let s=new Date().toISOString();T.run(t,`INSERT INTO custom_workflows (name, description, created_at, updated_at, is_builtin, enabled, metadata)
|
|
602
|
+
VALUES (?, ?, ?, ?, 0, 1, ?)`,e.name,e.description??null,s,s,e.metadata?JSON.stringify(e.metadata):null);let n=T.get(t,"SELECT id FROM custom_workflows WHERE name = ?",e.name);if(!n)throw new Error(`Failed to create workflow: ${e.name}`);return G({projectId:t,entityType:"custom_workflows",entityId:String(n.id),eventType:"upsert",data:{id:n.id,name:e.name,description:e.description??null,metadata:e.metadata??null,created_at:s,updated_at:s,is_builtin:0,enabled:1}}),n.id}getWorkflow(t,e){let s=T.get(t,"SELECT * FROM custom_workflows WHERE name = ?",e);return s?this.rowToWorkflow(s):null}getAllWorkflows(t,e=!1){let s=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 T.query(t,s).map(i=>this.rowToWorkflow(i))}updateWorkflow(t,e,s){if(!this.getWorkflow(t,e))return!1;let i=new Date().toISOString(),o=[],c=[];if(s.description!==void 0&&(o.push("description = ?"),c.push(s.description)),s.enabled!==void 0&&(o.push("enabled = ?"),c.push(s.enabled?1:0)),s.metadata!==void 0&&(o.push("metadata = ?"),c.push(JSON.stringify(s.metadata))),o.length===0)return!1;o.push("updated_at = ?"),c.push(i),c.push(e),T.run(t,`UPDATE custom_workflows SET ${o.join(", ")} WHERE name = ?`,...c);let u=this.getWorkflow(t,e);return u&&G({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 s=this.getWorkflow(t,e);if(!s)return!1;if(s.isBuiltin)throw new Error(`Cannot delete built-in workflow: ${e}`);return T.run(t,"UPDATE custom_workflows SET enabled = 0 WHERE name = ?",e),G({projectId:t,entityType:"custom_workflows",entityId:String(s.id),eventType:"delete",data:{id:s.id,name:e}}),!0}isBuiltin(t,e){return this.getWorkflow(t,e)?.isBuiltin??!1}isReservedName(t){let e=["task","done","ship","sync"],s=["add","rm","gate","list","create","delete","run","help","reset","init"];return e.includes(t)||s.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}}},zt=new ss;Et();j();function rs(r){let t=r.trust_source==="imported"?"imported":"local";return{id:r.id,type:r.type,command:r.command,position:r.position,action:r.action,description:r.description,enabled:r.enabled===1,timeoutMs:r.timeout_ms,createdAt:r.created_at,sortOrder:r.sort_order,whenExpr:r.when_expr??null,parallel:r.parallel===null?!0:r.parallel===1,trustSource:t}}a(rs,"rowToRule");var ns=class{static{a(this,"WorkflowRuleStorage")}addRule(t,e){let s=E.get(t,"SELECT MAX(sort_order) as m FROM workflow_rules WHERE command = ?",e.command),n=e.sortOrder||(s?.m??-1)+1;E.run(t,`INSERT INTO workflow_rules (type, command, position, action, description, enabled, timeout_ms, created_at, sort_order, when_expr, parallel, trust_source)
|
|
603
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,e.type,e.command,e.position,e.action,e.description??null,e.enabled?1:0,e.timeoutMs,e.createdAt,n,e.whenExpr??null,e.parallel===!1?0:1,e.trustSource??"local");let o=E.get(t,"SELECT last_insert_rowid() as id")?.id??0;return o>0&&G({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:n,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 E.get(t,"SELECT id FROM workflow_rules WHERE id = ?",e)?(E.run(t,"DELETE FROM workflow_rules WHERE id = ?",e),G({projectId:t,entityType:"workflow_rules",entityId:String(e),eventType:"delete",data:{id:e}}),!0):!1}updateRule(t,e,s){if(!E.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:a(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:a(u=>u===!1?0:1,"transform")},trustSource:{column:"trust_source"}},o=[],c=[];for(let[u,p]of Object.entries(s)){let m=i[u];if(!m)continue;o.push(`${m.column} = ?`);let d=p;c.push(m.transform?m.transform(d):d)}return o.length===0||(c.push(e),E.run(t,`UPDATE workflow_rules SET ${o.join(", ")} WHERE id = ?`,...c)),!0}getRuleById(t,e){let s=E.get(t,"SELECT * FROM workflow_rules WHERE id = ?",e);return s?rs(s):null}getRulesForCommand(t,e){let s=zt.getWorkflow(t,e);return!s||!s.enabled?[]:E.query(t,"SELECT * FROM workflow_rules WHERE command = ? AND enabled = 1 ORDER BY sort_order ASC",e).map(rs)}getAllRules(t){return E.query(t,"SELECT * FROM workflow_rules ORDER BY command ASC, sort_order ASC").map(rs)}resetRules(t){let e=E.get(t,"SELECT COUNT(*) as c FROM workflow_rules");return E.run(t,"DELETE FROM workflow_rules"),e?.c??0}},is=new ns;function Wn(r){let t=r;t.tool("prjct_workflow_rules","Get workflow rules for a command (gates, hooks, steps, instructions)",{projectPath:Kt.string().describe("Project directory path"),command:Kt.string().describe("Command name (task, done, ship, sync, etc.)")},S("prjct_workflow_rules",async e=>{let s=await x(e.projectPath),n=is.getRulesForCommand(s,e.command);if(n.length===0)return{content:[{type:"text",text:`No workflow rules for \`${e.command}\`.`}]};let i={};for(let c of n){let u=`${c.type}:${c.position}`;i[u]||(i[u]=[]),i[u].push(c)}let o=[`## Workflow Rules for \`${e.command}\``];for(let[c,u]of Object.entries(i)){o.push(`
|
|
604
|
+
### ${c}`);for(let p of u){let m=p.enabled?"":" (disabled)";o.push(`- ${p.action}${p.description?` \u2014 ${p.description}`:""}${m}`)}}return{content:[{type:"text",text:o.join(`
|
|
605
|
+
`)}]}})),t.tool("prjct_workflow_list","List all workflows for this project (built-in + custom)",{projectPath:Kt.string().describe("Project directory path")},S("prjct_workflow_list",async e=>{let s=await x(e.projectPath),n=zt.getAllWorkflows(s);if(n.length===0)return{content:[{type:"text",text:"No workflows configured."}]};let i=n.map(o=>{let c=o.isBuiltin?"(built-in)":"(custom)",u=o.enabled?"":" [disabled]";return`- **${o.name}** ${c}${u}${o.description?`: ${o.description}`:""}`});return{content:[{type:"text",text:`## Workflows (${n.length})
|
|
598
606
|
|
|
599
607
|
${i.join(`
|
|
600
608
|
`)}`}]}})),t.tool("prjct_workflow_status","Current workflow execution state + active rules",{projectPath:Kt.string().describe("Project directory path")},S("prjct_workflow_status",async e=>{let s=await x(e.projectPath),n=await at.getCurrentTask(s),i=is.getAllRules(s),o=["## Workflow Status"];n?(o.push(`
|
|
601
609
|
Active task: **${n.description}**`),o.push(`Started: ${n.startedAt}`)):o.push(`
|
|
602
|
-
No active task.`);let
|
|
603
|
-
### Active Rules (${
|
|
610
|
+
No active task.`);let c=i.filter(u=>u.enabled);if(c.length>0){o.push(`
|
|
611
|
+
### Active Rules (${c.length})`);for(let u of c)o.push(`- [${u.type}] ${u.command}:${u.position} \u2192 ${u.action}`)}else o.push(`
|
|
604
612
|
No active workflow rules.`);return{content:[{type:"text",text:o.join(`
|
|
605
|
-
`)}]}}))}
|
|
613
|
+
`)}]}}))}a(Wn,"registerWorkflowTools");var ea=`# prjct \u2014 Spec-Driven Development + project memory
|
|
606
614
|
|
|
607
615
|
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.**
|
|
608
616
|
|
|
@@ -637,4 +645,4 @@ Skip the SDD flow only for: routine captures, single-file fixes, doc tweaks, con
|
|
|
637
645
|
- Topic keys are free-form strings; don't invent new vocabularies when existing ones fit.
|
|
638
646
|
- Not every project defines every memory type \u2014 if one is empty, that's fine.
|
|
639
647
|
- Saving a secret-looking string is refused by default. Re-save with a scrubbed version.
|
|
640
|
-
- A spec without acceptance_criteria is just an inbox item \u2014 fill them.`;function Bn(){let r=new ta({name:"prjct",version:"1.0.0"},{instructions:ea});return An(r),On(r),kn(r),Wn(r),fr(r),$n(r),r}
|
|
648
|
+
- A spec without acceptance_criteria is just an inbox item \u2014 fill them.`;function Bn(){let r=new ta({name:"prjct",version:"1.0.0"},{instructions:ea});return An(r),On(r),kn(r),Wn(r),fr(r),$n(r),r}a(Bn,"createServer");async function ra(){let r=Bn(),t=new sa;await r.connect(t)}a(ra,"main");ra().catch(r=>{console.error("prjct MCP server failed:",r),process.exit(1)});
|