prjct-cli 3.12.0 → 3.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/bin/prjct-core.mjs +643 -653
- package/dist/bin/prjct-hooks.mjs +523 -385
- package/dist/daemon/entry.mjs +349 -356
- package/dist/mcp/server.mjs +1 -1
- package/package.json +1 -1
package/dist/mcp/server.mjs
CHANGED
|
@@ -700,7 +700,7 @@ CREATE TABLE velocity_sprints (
|
|
|
700
700
|
`);let n=new Set(e.prepare("SELECT version FROM _migrations").all().map(i=>i.version)),s=Ii.filter(i=>!n.has(i.version));if(s.length!==0){if(t&&n.size>0)try{let i=`${t}.pre-migrate.bak`;Ts.existsSync(i)&&Ts.rmSync(i,{force:!0}),e.prepare("VACUUM INTO ?").run(i)}catch(i){console.warn(`prjct: pre-migration backup failed (continuing): ${i?.message??i}`)}for(let i of s)dc(e,()=>{i.up(e),e.prepare("INSERT INTO _migrations (version, name, applied_at) VALUES (?, ?, ?)").run(i.version,i.name,new Date().toISOString())})}}getMigrations(e){return this.getDb(e).prepare("SELECT * FROM _migrations ORDER BY version").all()}getSchemaVersion(e){return this.getDb(e).prepare("SELECT MAX(version) as version FROM _migrations").get()?.version??0}},T=new Di,h=T});import pc from"node:fs/promises";import Lr from"node:path";function im(r){let e=[],t,n=new RegExp(ip.source,"g");for(;(t=n.exec(r))!==null;){let s=t[1];(s.startsWith(".")||s.startsWith("@/"))&&e.push(s)}return e}async function om(r,e,t){let n;if(r.startsWith("@/"))n=Lr.join(t,"src",r.slice(2));else{let s=Lr.dirname(Lr.join(t,e));n=Lr.resolve(s,r)}for(let s of sp){let i=n+s;try{if((await pc.stat(i)).isFile())return Lr.relative(t,i)}catch{}}return null}async function iv(r){let e=await ar(r),t={},n={},s=0,i=await cr(e,50,async o=>{try{let c=await pc.readFile(Lr.join(r,o),"utf-8"),l=im(c),u=[];for(let d of l){let p=await om(d,o,r);p&&p!==o&&u.push(p)}return u.length>0?{filePath:o,imports:u}:null}catch{return null}});for(let{filePath:o,imports:c}of i){t[o]=c,s+=c.length;for(let l of c)n[l]||(n[l]=[]),n[l].push(o)}return{forward:t,reverse:n,fileCount:e.length,edgeCount:s,builtAt:new Date().toISOString()}}function Ni(r,e,t=2){let n=new Set(r),s=new Map,i=[];for(let o of r){let c=e.forward[o]||[],l=e.reverse[o]||[];for(let u of[...c,...l])n.has(u)||i.push({file:u,depth:1})}for(let o=0;o<i.length;o++){let{file:c,depth:l}=i[o];if(l>t)continue;let u=1/(l+1),d=s.get(c);if(d){u>d.score&&s.set(c,{score:u,depth:l});continue}if(s.set(c,{score:u,depth:l}),l<t){let p=e.forward[c]||[],m=e.reverse[c]||[];for(let g of[...p,...m])!n.has(g)&&!s.has(g)&&i.push({file:g,depth:l+1})}}return Array.from(s.entries()).map(([o,{score:c,depth:l}])=>({path:o,score:c,depth:l})).sort((o,c)=>c.score-o.score)}function ov(r){return Object.values(r).reduce((e,t)=>e+t.length,0)}function av(r,e){let t=r.forward[e]||[];delete r.forward[e];for(let n of t){let s=(r.reverse[n]||[]).filter(i=>i!==e);s.length===0?delete r.reverse[n]:r.reverse[n]=s}}function cv(r,e){let t=r.reverse[e]||[];delete r.reverse[e];let n=[];for(let s of t){let i=(r.forward[s]||[]).filter(o=>o!==e);i.length===0?delete r.forward[s]:r.forward[s]=i,n.push(s)}return n}function lv(r,e,t){if(t.length===0)return;let n=Array.from(new Set(t));r.forward[e]=n;for(let s of n)r.reverse[s]||(r.reverse[s]=[]),r.reverse[s].includes(e)||r.reverse[s].push(e)}async function uv(r,e){try{let t=await pc.readFile(Lr.join(r,e),"utf-8"),n=im(t),s=[];for(let i of n){let o=await om(i,e,r);o&&o!==e&&s.push(o)}return{filePath:e,imports:s}}catch{return null}}function am(r){return{schemaVersion:2,fileCount:r.fileCount,edgeCount:r.edgeCount,builtAt:r.builtAt}}function dv(r,e){try{h.transaction(r,t=>{t.prepare("DELETE FROM import_graph_edges").run();let n=t.prepare("INSERT INTO import_graph_edges (from_path, to_path, sort_order) VALUES (?, ?, ?)");for(let[s,i]of Object.entries(e.forward))for(let[o,c]of i.entries())n.run(s,c,o)})}catch{}}function pv(r,e,t,n){try{h.transaction(r,s=>{let i=s.prepare("DELETE FROM import_graph_edges WHERE from_path = ?"),o=s.prepare("INSERT INTO import_graph_edges (from_path, to_path, sort_order) VALUES (?, ?, ?)");for(let c of new Set([...t,...n]))i.run(c);for(let c of t){let l=e.forward[c]||[];for(let[u,d]of l.entries())o.run(c,d,u)}})}catch{}}function mv(r,e,t){try{let n=h.query(r,"SELECT from_path, to_path FROM import_graph_edges ORDER BY from_path, sort_order, to_path");if(n.length===0){if(t?.edgeCount===0){let l={forward:{},reverse:{},fileCount:t.fileCount,edgeCount:0,builtAt:t.builtAt};return $r.set(r,{graph:l,updatedAt:e}),l}return null}let s={},i={};for(let l of n)s[l.from_path]||(s[l.from_path]=[]),s[l.from_path].push(l.to_path),i[l.to_path]||(i[l.to_path]=[]),i[l.to_path].push(l.from_path);let o=new Set;for(let[l,u]of Object.entries(s)){o.add(l);for(let d of u)o.add(d)}let c={forward:s,reverse:i,fileCount:t?.fileCount??o.size,edgeCount:n.length,builtAt:t?.builtAt??e};return $r.set(r,{graph:c,updatedAt:e}),c}catch{return null}}function gv(r,e){h.setDoc(r,ji,am(e)),dv(r,e),$r.delete(r)}function fv(r,e,t,n){h.setDoc(r,ji,am(e)),pv(r,e,t,n),$r.delete(r)}function mt(r){let e=h.get(r,"SELECT updated_at FROM kv_store WHERE key = ?",ji);if(!e)return $r.delete(r),null;let t=$r.get(r);if(t&&t.updatedAt===e.updated_at)return t.graph;let n=h.getDoc(r,ji),s=mv(r,e.updated_at,n);if(s)return s;if(!n?.forward||!n?.reverse)return null;let i={forward:n.forward,reverse:n.reverse,fileCount:n.fileCount,edgeCount:n.edgeCount,builtAt:n.builtAt};return $r.set(r,{graph:i,updatedAt:e.updated_at}),i}async function xs(r,e){let t=await iv(r);return gv(e,t),t}async function cm(r,e,t,n=[]){let s=mt(e);if(!s)return xs(r,e);let i=new Set([...t,...n]);for(let l of i)av(s,l);let o=new Set;for(let l of n)for(let u of cv(s,l))o.add(u);let c=await cr(t,50,l=>uv(r,l));for(let l of c)lv(s,l.filePath,l.imports);return s.edgeCount=ov(s.forward),s.builtAt=new Date().toISOString(),fv(e,s,[...t,...o],n),s}var ji,$r,En=f(()=>{"use strict";Ga();G();Q();a(im,"extractImportSources");a(om,"resolveImport");a(iv,"buildGraph");a(Ni,"scoreFromSeeds");ji="import-graph",$r=new Map;a(ov,"countEdges");a(av,"removeOutgoingEdges");a(cv,"removeIncomingEdges");a(lv,"addEdges");a(uv,"importsForFile");a(am,"graphMetadata");a(dv,"replacePerFileEdges");a(pv,"updatePerFileEdges");a(mv,"loadGraphFromPerFileEdges");a(gv,"saveGraph");a(fv,"saveGraphUpdate");a(mt,"loadGraph");a(xs,"indexImports");a(cm,"updateImportGraph")});function Mi(r,e){let t=[...r.added,...r.modified],n=new Set(t),s=new Set,i=mt(e);if(i)for(let l of t){let u=i.reverse[l];if(u)for(let d of u)n.has(d)||s.add(d)}let o=Array.from(s),c=[...t,...o];return{directlyChanged:t,affectedByImports:o,deleted:r.deleted,allAffected:c}}function Oi(r){let e=new Set;for(let t of r){let n=t.toLowerCase();(n.endsWith(".tsx")||n.endsWith(".jsx")||n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".vue")||n.endsWith(".svelte")||n.includes("/components/")||n.includes("/pages/")||n.includes("/app/"))&&(e.add("frontend"),e.add("uxui")),(n.includes(".test.")||n.includes(".spec.")||n.includes("__tests__")||n.includes("/test/"))&&e.add("testing"),(n.includes("dockerfile")||n.includes("docker-compose")||n.includes(".dockerignore")||n.includes(".github/")||n.includes("ci/")||n.includes("cd/"))&&e.add("devops"),(n.endsWith(".sql")||n.includes("prisma")||n.includes("drizzle")||n.includes("migration")||n.includes("/db/"))&&e.add("database"),(n.endsWith(".ts")||n.endsWith(".js"))&&!n.includes(".test.")&&!n.includes(".spec.")&&!n.endsWith(".d.ts")&&e.add("backend")}return e}var mc=f(()=>{"use strict";En();a(Mi,"propagateChanges");a(Oi,"affectedDomains")});var gc=f(()=>{"use strict"});async function yv(r,e=100){try{let{stdout:t}=await M(`git log --name-only --pretty=format:'---COMMIT---' -${e}`,{cwd:r,maxBuffer:10485760}),n=[],s=null;for(let i of t.split(`
|
|
701
701
|
`)){let o=i.trim();o==="---COMMIT---"?(s&&s.size>0&&s.size<=30&&n.push(s),s=new Set):o&&s&&wv(o)&&s.add(o)}return s&&s.size>0&&s.size<=30&&n.push(s),n}catch{return[]}}function wv(r){return/\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|cs|rb|php|vue|svelte)$/i.test(r)&&!r.includes("node_modules/")}async function kv(r,e=100){let t=await yv(r,e),n=new Map,s=new Map;for(let o of t){let c=Array.from(o);for(let l of c)n.set(l,(n.get(l)||0)+1);for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++){let d=bv(c[l],c[u]);s.set(d,(s.get(d)||0)+1)}}let i={};for(let[o,c]of s){let[l,u]=o.split("\0"),d=n.get(l)||0,p=n.get(u)||0;if(d<2||p<2)continue;let m=d+p-c,g=m>0?c/m:0;g<.1||(i[l]||(i[l]={}),i[u]||(i[u]={}),i[l][u]=g,i[u][l]=g)}return{matrix:i,commitsAnalyzed:t.length,filesAnalyzed:n.size,builtAt:new Date().toISOString()}}function bv(r,e){return r<e?`${r}\0${e}`:`${e}\0${r}`}function Cs(r,e){let t=new Set(r),n=new Map;for(let s of r){let i=e.matrix[s];if(i)for(let[o,c]of Object.entries(i)){if(t.has(o))continue;let l=n.get(o)||0;c>l&&n.set(o,c)}}return Array.from(n.entries()).map(([s,i])=>({path:s,score:i})).sort((s,i)=>i.score-s.score)}function Ev(r,e){h.setDoc(r,fc,e),Li.delete(r)}function Kt(r){let e=h.get(r,"SELECT updated_at FROM kv_store WHERE key = ?",fc);if(!e)return Li.delete(r),null;let t=Li.get(r);if(t&&t.updatedAt===e.updated_at)return t.matrix;let n=h.getDoc(r,fc);return n&&Li.set(r,{matrix:n,updatedAt:e.updated_at}),n}async function Sv(r,e){try{let{stdout:t}=await M(`git rev-list --max-count=${e} HEAD`,{cwd:r,maxBuffer:1048576}),n=t.split(`
|
|
702
702
|
`).map(s=>s.trim()).filter(Boolean);return n.length>0?n.join(`
|
|
703
|
-
`):null}catch{return null}}async function $i(r,e,t=100){let n=await Sv(r,t),s=n?Kt(e):null;if(s?.historyFingerprint===n)return s;let i=await kv(r,t);return n&&(i.historyFingerprint=n),Ev(e,i),i}var fc,Li,Rs=f(()=>{"use strict";gc();G();pe();a(yv,"parseGitLog");a(wv,"isSourceFile");a(kv,"buildMatrix");a(bv,"pairKey");a(Cs,"scoreFromSeeds");fc="cochange-index",Li=new Map;a(Ev,"saveMatrix");a(Kt,"loadMatrix");a(Sv,"recentHistoryFingerprint");a($i,"indexCoChanges")});function vv(r){return r instanceof _s}function be(r){return vv(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var _s,Fi,As,zt=f(()=>{"use strict";_s=class extends Error{static{a(this,"PrjctError")}code;isOperational;constructor(e,t="PRJCT_ERROR"){super(e),this.name="PrjctError",this.code=t,this.isOperational=!0,Error.captureStackTrace?.(this,this.constructor)}},Fi=class r extends _s{static{a(this,"ProjectError")}constructor(e,t="PROJECT_ERROR"){super(e,t),this.name="ProjectError"}static notInitialized(){return new r("Project not initialized. Run p. init first.","PROJECT_NOT_INIT")}static notFound(e){return new r(`Project not found: ${e}`,"PROJECT_NOT_FOUND")}static invalidId(e){return new r(`Invalid project ID: ${e}`,"PROJECT_INVALID_ID")}},As=class r extends _s{static{a(this,"AgentError")}constructor(e,t="AGENT_ERROR"){super(e,t),this.name="AgentError"}static notSupported(e){return new r(`Unsupported agent type: ${e}`,"AGENT_NOT_SUPPORTED")}static initFailed(e){return new r(`Agent initialization failed: ${e}`,"AGENT_INIT_FAILED")}};a(vv,"isPrjctError");a(be,"getErrorMessage")});function dm(r){let e=r.toLowerCase();return e.includes("github")?"github":e.includes("gitlab")?"gitlab":e.includes("bitbucket")?"bitbucket":"other"}function hc(r){let e=r.trim();if(!e)return{};let t=e.match(/^[^/@]+@([^:/]+):(.+?)(?:\.git)?\/?$/);if(t)return{provider:dm(t[1]),repoSlug:t[2]};try{let n=new URL(e),s=n.pathname.replace(/^\/+/,"").replace(/\.git$/,"").replace(/\/+$/,"");return!n.host||!s?{}:{provider:dm(n.host),repoSlug:s}}catch{return{}}}async function Tv(r){try{let{stdout:e}=await B("git",["remote","get-url","origin"],{cwd:r});return e.trim()||void 0}catch{return}}async function xv(r){try{let{stdout:e}=await B("git",["symbolic-ref","--short","refs/remotes/origin/HEAD"],{cwd:r});return e.trim().replace(/^origin\//,"")||void 0}catch{return}}function Fr(r){return typeof r=="string"&&r.length>0?r:void 0}function pm(r){return typeof r=="number"&&Number.isFinite(r)?r:void 0}function Cv(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}async function mm(r){let e=T.getDoc(r,"project")||{},t=Fr(e.repoPath),{provider:n,repoSlug:s}=t?hc(await Tv(t)||""):{},i=t?await xv(t):void 0,o=Array.isArray(e.techStack)?e.techStack.filter(c=>typeof c=="string"):void 0;return Cv({provider:n,repoSlug:s,currentBranch:Fr(e.currentBranch),defaultBranch:i,stack:Fr(e.stack),techStack:o&&o.length>0?o:void 0,version:Fr(e.version),commitCount:pm(e.commitCount),fileCount:pm(e.fileCount),lastCommit:Fr(e.lastSyncCommit),hasUncommitted:typeof e.hasUncommittedChanges=="boolean"?e.hasUncommittedChanges:void 0,cliVersion:Fr(e.cliVersion),syncedAt:Fr(e.lastSync)})}var yc=f(()=>{"use strict";G();pe();a(dm,"providerForHost");a(hc,"parseRemote");a(Tv,"gitRemoteUrl");a(xv,"gitDefaultBranch");a(Fr,"str");a(pm,"num");a(Cv,"compact");a(mm,"buildProjectMeta")});import{execFile as Rv}from"node:child_process";import _v from"node:crypto";import{promisify as Av}from"node:util";function Dv(r,e=Iv){let t=Buffer.from(e.replace(/-/g,""),"hex"),s=_v.createHash("sha1").update(t).update(r,"utf8").digest().subarray(0,16);s[6]=s[6]&15|80,s[8]=s[8]&63|128;let i=s.toString("hex");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20,32)}`}async function jv(r){let e;try{let{stdout:s}=await Pv("git",["remote","get-url","origin"],{cwd:r});e=s.trim()||void 0}catch{return null}if(!e)return null;let{provider:t,repoSlug:n}=hc(e);return!t||!n?null:`${t}:${n}`.toLowerCase()}async function gm(r){let e=await jv(r);return e?Dv(e):null}var Pv,Iv,fm=f(()=>{"use strict";yc();Pv=Av(Rv),Iv="6f9b2c1a-3d4e-5f60-8a7b-1c2d3e4f5a6b";a(Dv,"uuidv5");a(jv,"repoKey");a(gm,"deriveProjectId")});var bc={};Y(bc,{PACKAGE_ROOT:()=>hr,VERSION:()=>Ot,getPackageRoot:()=>kc,getVersion:()=>Hi,resetPackageRoot:()=>Nv});import wc from"node:fs";import Ui from"node:path";function kc(){if(Sn)return Sn;let r=__dirname;for(let e=0;e<5;e++){let t=Ui.join(r,"package.json");if(wc.existsSync(t))try{if(JSON.parse(wc.readFileSync(t,"utf-8")).name==="prjct-cli")return Sn=r,r}catch{}r=Ui.dirname(r)}return Sn=Ui.join(__dirname,"..","..",".."),Sn}function Hi(){if(Ur)return Ur;let r="3.12.0";if(r&&/^\d+\.\d+\.\d+/.test(r))return Ur=r,Ur;try{let e=Ui.join(kc(),"package.json");return Ur=JSON.parse(wc.readFileSync(e,"utf-8")).version,Ur}catch(e){return process.env.PRJCT_DEBUG==="1"&&console.error("Failed to read version from package.json:",R(e)),"0.0.0"}}function Nv(r){Sn=r,Ur=null}var Ur,Sn,Ot,hr,Lt=f(()=>{"use strict";V();Ur=null,Sn=null;a(kc,"getPackageRoot");a(Hi,"getVersion");a(Nv,"resetPackageRoot");Ot=Hi(),hr=kc()});async function Wi(r){try{let{stdout:e}=await M(r,{timeout:5e3});return{success:!0,output:e.trim()}}catch{return{success:!1,output:""}}}async function Mv(){let r=await Wi("gh api user --jq .login");return r.success&&r.output||(r=await Wi("git config --global github.user"),r.success&&r.output)?r.output:null}async function Ov(){let r=await Wi("git config user.name");return r.success&&r.output?r.output:null}async function Lv(){let r=await Wi("git config user.email");return r.success&&r.output?r.output:null}async function vn(){let[r,e,t]=await Promise.all([Mv(),Ov(),Lv()]);return{github:r,email:t,name:e||r||"Unknown"}}var Gi=f(()=>{"use strict";pe();a(Wi,"execCommand");a(Mv,"detectGitHubUsername");a(Ov,"detectGitName");a(Lv,"detectGitEmail");a(vn,"detect")});var Tn={};Y(Tn,{default:()=>L});import Sc from"node:fs/promises";import $v from"node:path";import*as Bi from"jsonc-parser";function hm(r){let e=[],t=Bi.parse(r,e,{allowTrailingComma:!0,disallowComments:!1});if(e.length>0){let n=e[0];throw new SyntaxError(`JSON parse error at offset ${n.offset}: ${Bi.printParseErrorCode(n.error)}`)}return t}var vc,Fv,L,fe=f(()=>{"use strict";zt();fm();V();J();Q();Lt();Gi();Ne();a(hm,"parseJsonc");vc=class{static{a(this,"ConfigManager")}async readConfig(e){try{let t=O.getLocalConfigPath(e),n=await Sc.readFile(t,"utf-8");return hm(n)}catch(t){return N(t)||console.warn(`Warning: Could not read config at ${e}: ${be(t)}`),null}}async writeConfig(e,t){let n=O.getLocalConfigPath(e);await ve(n,t)}async readGlobalConfig(e){try{let t=O.getGlobalProjectConfigPath(e),n=await Sc.readFile(t,"utf-8");return hm(n)}catch(t){return N(t)||console.warn(`Warning: Could not read global config for ${e}: ${be(t)}`),null}}async writeGlobalConfig(e,t){let n=O.getGlobalProjectConfigPath(e);await ve(n,t)}async ensureGlobalConfig(e){let t=await this.readGlobalConfig(e);if(!t){let n=k();t={projectId:e,authors:[],version:Ot,lastSync:n},await this.writeGlobalConfig(e,t)}return t}async createConfig(e,t){let n=await gm(e)??O.generateProjectId(e),s=O.getGlobalProjectPath(n),i=O.getDisplayPath(s),o=k(),c={projectId:n,dataPath:i,showMetrics:!0};await this.writeConfig(e,c);let l={projectId:n,authors:[{name:t.name||"Unknown",email:t.email||"",github:t.github||"",firstContribution:o,lastActivity:o}],version:Ot,created:o,lastSync:o};return await this.writeGlobalConfig(n,l),c}async updateLastSync(e){let t=await this.getProjectId(e),n=await this.readGlobalConfig(t);n&&(n.lastSync=k(),await this.writeGlobalConfig(t,n))}validateConfig(e){return!(!e||!e.projectId||!e.dataPath)}async needsMigration(e){if(!await O.hasLegacyStructure(e))return!1;if(!await O.hasConfig(e))return!0;let s=await this.readConfig(e);if(!s||!s.projectId)return!0;let i=O.getGlobalProjectPath(s.projectId);try{return(await Sc.readdir($v.join(i,"core"))).length===0}catch(o){return N(o),!0}}async getProjectId(e){let t=await this.readConfig(e);if(t?.projectId)return t.projectId;try{let{worktreeService:n}=await Promise.resolve().then(()=>(vi(),Si));if(await n.detect(e)){let i=await n.getMainWorktree(e);if(i!==e){let o=await this.readConfig(i);if(o?.projectId)return o.projectId}}}catch{}return""}async findAuthor(e,t){let n=await this.readGlobalConfig(e);return!n||!n.authors?null:n.authors.find(s=>s.github===t)||null}async addAuthor(e,t){let n=await this.ensureGlobalConfig(e);if(n.authors.some(o=>o.github===t.github))return;let i=k();n.authors.push({name:t.name||"Unknown",email:t.email||"",github:t.github||"",firstContribution:i,lastActivity:i}),n.lastSync=i,await this.writeGlobalConfig(e,n)}async updateAuthorActivity(e,t){let n=await this.readGlobalConfig(e);if(!n||!n.authors)return;let s=n.authors.find(i=>i.github===t);s&&(s.lastActivity=k(),n.lastSync=s.lastActivity,await this.writeGlobalConfig(e,n))}async getCurrentAuthor(e){let t=await vn(),n=await this.getProjectId(e);return await this.addAuthor(n,{name:t.name??void 0,email:t.email??void 0,github:t.github??void 0}),t.github||t.name||"Unknown"}async isConfigured(e){let t=await this.readConfig(e);return this.validateConfig(t)}async getShowMetrics(e){return(await this.readConfig(e))?.showMetrics??!0}async setShowMetrics(e,t){let n=await this.readConfig(e);n&&(n.showMetrics=t,await this.writeConfig(e,n))}async getConfigWithDefaults(e){let t=await this.readConfig(e);if(t)return t;let n=O.generateProjectId(e);return{projectId:n,dataPath:O.getDisplayPath(O.getGlobalProjectPath(n))}}},Fv=new vc,L=Fv});import{z as w}from"zod";var Hv,qi,Wv,Gv,Bv,qv,Vv,Xv,Jv,Tc,km,bm,Em,xc,Sm,wm,Kv,zv,Yv,vm,Qv,Tm,Vi=f(()=>{"use strict";Ss();Hv=w.enum(["low","medium","high","critical"]),qi=w.enum(["feature","bug","improvement","chore"]),Wv=w.enum(["active","backlog","previously_active"]),Gv=w.enum(["H0","H1","H2","H3"]),Bv=w.enum(["bug","feature","refactor","docs","chore","security","unknown"]),qv=w.enum(["low","medium","high"]),Vv=w.enum(["regression-test","focused-tests","docs-if-public-behavior","config-preservation","spec-or-design","edge-cases","scope-check"]),Xv=w.enum(["verify-before-done","scope-check","review-before-ship","spec-before-implementation"]),Jv=w.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),Tc=w.object({title:w.string(),description:w.string(),filesChanged:w.array(w.object({path:w.string(),action:w.enum(["created","modified","deleted"])})),whatWasDone:w.array(w.string()).min(1),outputForNextAgent:w.string().min(1),notes:w.string().optional()}),km=w.object({output:w.string().min(1,"Subtask output is required"),summary:Tc}),bm=w.object({id:w.string(),description:w.string(),domain:w.string(),agent:w.string(),status:Jv,dependsOn:w.array(w.string()),startedAt:w.string().optional(),completedAt:w.string().optional(),output:w.string().optional(),summary:Tc.optional(),skipReason:w.string().optional(),blockReason:w.string().optional(),estimatedPoints:w.number().optional(),estimatedMinutes:w.number().optional()}),Em=w.object({completed:w.number(),total:w.number(),percentage:w.number()}),xc=w.object({level:Gv,kind:Bv,risk:qv,expectedEvidence:w.array(Vv),scopeHints:w.array(w.string()),gates:w.array(Xv),rationale:w.string(),createdAt:w.string()}),Sm=w.object({id:w.string(),description:w.string(),type:qi.optional(),startedAt:w.string(),sessionId:w.string(),featureId:w.string().optional(),subtasks:w.array(bm).optional(),currentSubtaskIndex:w.number().optional(),subtaskProgress:Em.optional(),linearId:w.string().optional(),linearUuid:w.string().optional(),linkedSpecId:w.string().optional(),estimatedPoints:w.number().optional(),estimatedMinutes:w.number().optional(),modelMetadata:Es.optional(),tokensIn:w.number().optional(),tokensOut:w.number().optional(),parentDescription:w.string().optional(),branch:w.string().optional(),prUrl:w.string().optional(),harness:xc.optional(),turnCount:w.number().optional(),turnLimitAcknowledgedAt:w.string().optional()}),wm=w.object({id:w.string(),description:w.string(),status:w.literal("paused"),startedAt:w.string(),pausedAt:w.string(),pauseReason:w.string().optional(),type:qi.optional(),sessionId:w.string().optional(),featureId:w.string().optional(),subtasks:w.array(bm).optional(),currentSubtaskIndex:w.number().optional(),subtaskProgress:Em.optional(),linearId:w.string().optional(),linearUuid:w.string().optional(),estimatedPoints:w.number().optional(),estimatedMinutes:w.number().optional(),modelMetadata:Es.optional(),tokensIn:w.number().optional(),tokensOut:w.number().optional(),harness:xc.optional()}),Kv=w.object({stackConfirmed:w.array(w.string()).optional(),patternsDiscovered:w.array(w.string()).optional(),agentAccuracy:w.array(w.object({agent:w.string(),rating:w.enum(["helpful","neutral","inaccurate"]),note:w.string().optional()})).optional(),issuesEncountered:w.array(w.string()).optional()}),zv=w.object({taskId:w.string(),title:w.string(),classification:qi,startedAt:w.string(),completedAt:w.string(),subtaskCount:w.number(),subtaskSummaries:w.array(Tc),outcome:w.string(),branchName:w.string(),linearId:w.string().optional(),linearUuid:w.string().optional(),prUrl:w.string().optional(),feedback:Kv.optional(),harness:xc.optional(),tokensIn:w.number().optional(),tokensOut:w.number().optional()}),Yv=Sm.extend({workspaceId:w.string(),worktreePath:w.string().optional(),agentSessionId:w.string().optional(),jiraId:w.string().optional(),jiraUuid:w.string().optional(),dispatchedFrom:w.string().optional()}),vm=w.object({currentTask:Sm.nullable(),previousTask:wm.nullable().optional(),pausedTasks:w.array(wm).optional(),taskHistory:w.array(zv).optional(),activeTasks:w.array(Yv).optional(),lastUpdated:w.string()}),Qv=w.object({id:w.string(),description:w.string(),body:w.string().optional(),priority:Hv,type:qi,featureId:w.string().optional(),originFeature:w.string().optional(),completed:w.boolean(),completedAt:w.string().optional(),createdAt:w.string(),section:Wv,agent:w.string().optional(),groupName:w.string().optional(),groupId:w.string().optional()}),Tm=w.object({tasks:w.array(Qv),lastUpdated:w.string()})});var Ps,Cc,xn,Rc=f(()=>{"use strict";Ps={idle:{transitions:["task"],prompt:"prjct work <intent> Start working",description:"No active work cycle"},working:{transitions:["done","pause"],prompt:"prjct status done Complete work | prjct status paused Switch context",description:"Work in progress"},paused:{transitions:["resume","task","ship"],prompt:"prjct status active Continue | prjct work <new> Start different | prjct ship Ship directly",description:"Task paused"},completed:{transitions:["ship","task","pause","reopen"],prompt:"prjct ship Ship it | prjct work <next> Start next | prjct status active Reopen",description:"Task completed"},shipped:{transitions:["task"],prompt:"prjct work <intent> Start new work cycle",description:"Feature shipped"}},Cc=class{static{a(this,"WorkflowStateMachine")}getCurrentState(e,t){if(t){let s=(e?.activeTasks??[]).find(i=>i.workspaceId===t);return s?this.statusToState(s):"idle"}let n=e?.currentTask;return n?this.statusToState(n):(e?.pausedTasks?.length||0)>0||e?.previousTask?.status==="paused"?"paused":"idle"}statusToState(e){switch((typeof e.status=="string"?e.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"working"}}canTransition(e,t){if(Ps[e].transitions.includes(t))return{valid:!0};let s=this.formatNextSteps(e).join(" | ");return{valid:!1,error:`Cannot transition to '${t}' from '${e}' state`,suggestion:`Valid next steps: ${s}`}}getNextState(e,t){switch(t){case"task":return"working";case"done":return"completed";case"pause":return"paused";case"resume":return"working";case"ship":return"shipped";case"reopen":return"working";default:return e}}getStateInfo(e){return Ps[e]}getPrompt(e){return Ps[e].prompt}getValidCommands(e){return Ps[e].transitions}formatNextSteps(e){return Ps[e].transitions.map(n=>{switch(n){case"task":return"prjct work <intent> Start new work cycle";case"done":return"prjct status done Complete current work";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 ${n}`}})}},xn=new Cc});import Zv from"node:crypto";function xe(){return Zv.randomUUID()}var Yt=f(()=>{"use strict";a(xe,"generateUUID")});var _c,Hr,xm=f(()=>{"use strict";J();G();_c=class{static{a(this,"SyncPendingStorage")}append(e,t){let n=k(),s=JSON.stringify(t);return t.entityType&&t.entityId&&t.contentHash&&h.run(e,`DELETE FROM sync_pending
|
|
703
|
+
`):null}catch{return null}}async function $i(r,e,t=100){let n=await Sv(r,t),s=n?Kt(e):null;if(s?.historyFingerprint===n)return s;let i=await kv(r,t);return n&&(i.historyFingerprint=n),Ev(e,i),i}var fc,Li,Rs=f(()=>{"use strict";gc();G();pe();a(yv,"parseGitLog");a(wv,"isSourceFile");a(kv,"buildMatrix");a(bv,"pairKey");a(Cs,"scoreFromSeeds");fc="cochange-index",Li=new Map;a(Ev,"saveMatrix");a(Kt,"loadMatrix");a(Sv,"recentHistoryFingerprint");a($i,"indexCoChanges")});function vv(r){return r instanceof _s}function be(r){return vv(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var _s,Fi,As,zt=f(()=>{"use strict";_s=class extends Error{static{a(this,"PrjctError")}code;isOperational;constructor(e,t="PRJCT_ERROR"){super(e),this.name="PrjctError",this.code=t,this.isOperational=!0,Error.captureStackTrace?.(this,this.constructor)}},Fi=class r extends _s{static{a(this,"ProjectError")}constructor(e,t="PROJECT_ERROR"){super(e,t),this.name="ProjectError"}static notInitialized(){return new r("Project not initialized. Run p. init first.","PROJECT_NOT_INIT")}static notFound(e){return new r(`Project not found: ${e}`,"PROJECT_NOT_FOUND")}static invalidId(e){return new r(`Invalid project ID: ${e}`,"PROJECT_INVALID_ID")}},As=class r extends _s{static{a(this,"AgentError")}constructor(e,t="AGENT_ERROR"){super(e,t),this.name="AgentError"}static notSupported(e){return new r(`Unsupported agent type: ${e}`,"AGENT_NOT_SUPPORTED")}static initFailed(e){return new r(`Agent initialization failed: ${e}`,"AGENT_INIT_FAILED")}};a(vv,"isPrjctError");a(be,"getErrorMessage")});function dm(r){let e=r.toLowerCase();return e.includes("github")?"github":e.includes("gitlab")?"gitlab":e.includes("bitbucket")?"bitbucket":"other"}function hc(r){let e=r.trim();if(!e)return{};let t=e.match(/^[^/@]+@([^:/]+):(.+?)(?:\.git)?\/?$/);if(t)return{provider:dm(t[1]),repoSlug:t[2]};try{let n=new URL(e),s=n.pathname.replace(/^\/+/,"").replace(/\.git$/,"").replace(/\/+$/,"");return!n.host||!s?{}:{provider:dm(n.host),repoSlug:s}}catch{return{}}}async function Tv(r){try{let{stdout:e}=await B("git",["remote","get-url","origin"],{cwd:r});return e.trim()||void 0}catch{return}}async function xv(r){try{let{stdout:e}=await B("git",["symbolic-ref","--short","refs/remotes/origin/HEAD"],{cwd:r});return e.trim().replace(/^origin\//,"")||void 0}catch{return}}function Fr(r){return typeof r=="string"&&r.length>0?r:void 0}function pm(r){return typeof r=="number"&&Number.isFinite(r)?r:void 0}function Cv(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}async function mm(r){let e=T.getDoc(r,"project")||{},t=Fr(e.repoPath),{provider:n,repoSlug:s}=t?hc(await Tv(t)||""):{},i=t?await xv(t):void 0,o=Array.isArray(e.techStack)?e.techStack.filter(c=>typeof c=="string"):void 0;return Cv({provider:n,repoSlug:s,currentBranch:Fr(e.currentBranch),defaultBranch:i,stack:Fr(e.stack),techStack:o&&o.length>0?o:void 0,version:Fr(e.version),commitCount:pm(e.commitCount),fileCount:pm(e.fileCount),lastCommit:Fr(e.lastSyncCommit),hasUncommitted:typeof e.hasUncommittedChanges=="boolean"?e.hasUncommittedChanges:void 0,cliVersion:Fr(e.cliVersion),syncedAt:Fr(e.lastSync)})}var yc=f(()=>{"use strict";G();pe();a(dm,"providerForHost");a(hc,"parseRemote");a(Tv,"gitRemoteUrl");a(xv,"gitDefaultBranch");a(Fr,"str");a(pm,"num");a(Cv,"compact");a(mm,"buildProjectMeta")});import{execFile as Rv}from"node:child_process";import _v from"node:crypto";import{promisify as Av}from"node:util";function Dv(r,e=Iv){let t=Buffer.from(e.replace(/-/g,""),"hex"),s=_v.createHash("sha1").update(t).update(r,"utf8").digest().subarray(0,16);s[6]=s[6]&15|80,s[8]=s[8]&63|128;let i=s.toString("hex");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20,32)}`}async function jv(r){let e;try{let{stdout:s}=await Pv("git",["remote","get-url","origin"],{cwd:r});e=s.trim()||void 0}catch{return null}if(!e)return null;let{provider:t,repoSlug:n}=hc(e);return!t||!n?null:`${t}:${n}`.toLowerCase()}async function gm(r){let e=await jv(r);return e?Dv(e):null}var Pv,Iv,fm=f(()=>{"use strict";yc();Pv=Av(Rv),Iv="6f9b2c1a-3d4e-5f60-8a7b-1c2d3e4f5a6b";a(Dv,"uuidv5");a(jv,"repoKey");a(gm,"deriveProjectId")});var bc={};Y(bc,{PACKAGE_ROOT:()=>hr,VERSION:()=>Ot,getPackageRoot:()=>kc,getVersion:()=>Hi,resetPackageRoot:()=>Nv});import wc from"node:fs";import Ui from"node:path";function kc(){if(Sn)return Sn;let r=__dirname;for(let e=0;e<5;e++){let t=Ui.join(r,"package.json");if(wc.existsSync(t))try{if(JSON.parse(wc.readFileSync(t,"utf-8")).name==="prjct-cli")return Sn=r,r}catch{}r=Ui.dirname(r)}return Sn=Ui.join(__dirname,"..","..",".."),Sn}function Hi(){if(Ur)return Ur;let r="3.12.2";if(r&&/^\d+\.\d+\.\d+/.test(r))return Ur=r,Ur;try{let e=Ui.join(kc(),"package.json");return Ur=JSON.parse(wc.readFileSync(e,"utf-8")).version,Ur}catch(e){return process.env.PRJCT_DEBUG==="1"&&console.error("Failed to read version from package.json:",R(e)),"0.0.0"}}function Nv(r){Sn=r,Ur=null}var Ur,Sn,Ot,hr,Lt=f(()=>{"use strict";V();Ur=null,Sn=null;a(kc,"getPackageRoot");a(Hi,"getVersion");a(Nv,"resetPackageRoot");Ot=Hi(),hr=kc()});async function Wi(r){try{let{stdout:e}=await M(r,{timeout:5e3});return{success:!0,output:e.trim()}}catch{return{success:!1,output:""}}}async function Mv(){let r=await Wi("gh api user --jq .login");return r.success&&r.output||(r=await Wi("git config --global github.user"),r.success&&r.output)?r.output:null}async function Ov(){let r=await Wi("git config user.name");return r.success&&r.output?r.output:null}async function Lv(){let r=await Wi("git config user.email");return r.success&&r.output?r.output:null}async function vn(){let[r,e,t]=await Promise.all([Mv(),Ov(),Lv()]);return{github:r,email:t,name:e||r||"Unknown"}}var Gi=f(()=>{"use strict";pe();a(Wi,"execCommand");a(Mv,"detectGitHubUsername");a(Ov,"detectGitName");a(Lv,"detectGitEmail");a(vn,"detect")});var Tn={};Y(Tn,{default:()=>L});import Sc from"node:fs/promises";import $v from"node:path";import*as Bi from"jsonc-parser";function hm(r){let e=[],t=Bi.parse(r,e,{allowTrailingComma:!0,disallowComments:!1});if(e.length>0){let n=e[0];throw new SyntaxError(`JSON parse error at offset ${n.offset}: ${Bi.printParseErrorCode(n.error)}`)}return t}var vc,Fv,L,fe=f(()=>{"use strict";zt();fm();V();J();Q();Lt();Gi();Ne();a(hm,"parseJsonc");vc=class{static{a(this,"ConfigManager")}async readConfig(e){try{let t=O.getLocalConfigPath(e),n=await Sc.readFile(t,"utf-8");return hm(n)}catch(t){return N(t)||console.warn(`Warning: Could not read config at ${e}: ${be(t)}`),null}}async writeConfig(e,t){let n=O.getLocalConfigPath(e);await ve(n,t)}async readGlobalConfig(e){try{let t=O.getGlobalProjectConfigPath(e),n=await Sc.readFile(t,"utf-8");return hm(n)}catch(t){return N(t)||console.warn(`Warning: Could not read global config for ${e}: ${be(t)}`),null}}async writeGlobalConfig(e,t){let n=O.getGlobalProjectConfigPath(e);await ve(n,t)}async ensureGlobalConfig(e){let t=await this.readGlobalConfig(e);if(!t){let n=k();t={projectId:e,authors:[],version:Ot,lastSync:n},await this.writeGlobalConfig(e,t)}return t}async createConfig(e,t){let n=await gm(e)??O.generateProjectId(e),s=O.getGlobalProjectPath(n),i=O.getDisplayPath(s),o=k(),c={projectId:n,dataPath:i,showMetrics:!0};await this.writeConfig(e,c);let l={projectId:n,authors:[{name:t.name||"Unknown",email:t.email||"",github:t.github||"",firstContribution:o,lastActivity:o}],version:Ot,created:o,lastSync:o};return await this.writeGlobalConfig(n,l),c}async updateLastSync(e){let t=await this.getProjectId(e),n=await this.readGlobalConfig(t);n&&(n.lastSync=k(),await this.writeGlobalConfig(t,n))}validateConfig(e){return!(!e||!e.projectId||!e.dataPath)}async needsMigration(e){if(!await O.hasLegacyStructure(e))return!1;if(!await O.hasConfig(e))return!0;let s=await this.readConfig(e);if(!s||!s.projectId)return!0;let i=O.getGlobalProjectPath(s.projectId);try{return(await Sc.readdir($v.join(i,"core"))).length===0}catch(o){return N(o),!0}}async getProjectId(e){let t=await this.readConfig(e);if(t?.projectId)return t.projectId;try{let{worktreeService:n}=await Promise.resolve().then(()=>(vi(),Si));if(await n.detect(e)){let i=await n.getMainWorktree(e);if(i!==e){let o=await this.readConfig(i);if(o?.projectId)return o.projectId}}}catch{}return""}async findAuthor(e,t){let n=await this.readGlobalConfig(e);return!n||!n.authors?null:n.authors.find(s=>s.github===t)||null}async addAuthor(e,t){let n=await this.ensureGlobalConfig(e);if(n.authors.some(o=>o.github===t.github))return;let i=k();n.authors.push({name:t.name||"Unknown",email:t.email||"",github:t.github||"",firstContribution:i,lastActivity:i}),n.lastSync=i,await this.writeGlobalConfig(e,n)}async updateAuthorActivity(e,t){let n=await this.readGlobalConfig(e);if(!n||!n.authors)return;let s=n.authors.find(i=>i.github===t);s&&(s.lastActivity=k(),n.lastSync=s.lastActivity,await this.writeGlobalConfig(e,n))}async getCurrentAuthor(e){let t=await vn(),n=await this.getProjectId(e);return await this.addAuthor(n,{name:t.name??void 0,email:t.email??void 0,github:t.github??void 0}),t.github||t.name||"Unknown"}async isConfigured(e){let t=await this.readConfig(e);return this.validateConfig(t)}async getShowMetrics(e){return(await this.readConfig(e))?.showMetrics??!0}async setShowMetrics(e,t){let n=await this.readConfig(e);n&&(n.showMetrics=t,await this.writeConfig(e,n))}async getConfigWithDefaults(e){let t=await this.readConfig(e);if(t)return t;let n=O.generateProjectId(e);return{projectId:n,dataPath:O.getDisplayPath(O.getGlobalProjectPath(n))}}},Fv=new vc,L=Fv});import{z as w}from"zod";var Hv,qi,Wv,Gv,Bv,qv,Vv,Xv,Jv,Tc,km,bm,Em,xc,Sm,wm,Kv,zv,Yv,vm,Qv,Tm,Vi=f(()=>{"use strict";Ss();Hv=w.enum(["low","medium","high","critical"]),qi=w.enum(["feature","bug","improvement","chore"]),Wv=w.enum(["active","backlog","previously_active"]),Gv=w.enum(["H0","H1","H2","H3"]),Bv=w.enum(["bug","feature","refactor","docs","chore","security","unknown"]),qv=w.enum(["low","medium","high"]),Vv=w.enum(["regression-test","focused-tests","docs-if-public-behavior","config-preservation","spec-or-design","edge-cases","scope-check"]),Xv=w.enum(["verify-before-done","scope-check","review-before-ship","spec-before-implementation"]),Jv=w.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),Tc=w.object({title:w.string(),description:w.string(),filesChanged:w.array(w.object({path:w.string(),action:w.enum(["created","modified","deleted"])})),whatWasDone:w.array(w.string()).min(1),outputForNextAgent:w.string().min(1),notes:w.string().optional()}),km=w.object({output:w.string().min(1,"Subtask output is required"),summary:Tc}),bm=w.object({id:w.string(),description:w.string(),domain:w.string(),agent:w.string(),status:Jv,dependsOn:w.array(w.string()),startedAt:w.string().optional(),completedAt:w.string().optional(),output:w.string().optional(),summary:Tc.optional(),skipReason:w.string().optional(),blockReason:w.string().optional(),estimatedPoints:w.number().optional(),estimatedMinutes:w.number().optional()}),Em=w.object({completed:w.number(),total:w.number(),percentage:w.number()}),xc=w.object({level:Gv,kind:Bv,risk:qv,expectedEvidence:w.array(Vv),scopeHints:w.array(w.string()),gates:w.array(Xv),rationale:w.string(),createdAt:w.string()}),Sm=w.object({id:w.string(),description:w.string(),type:qi.optional(),startedAt:w.string(),sessionId:w.string(),featureId:w.string().optional(),subtasks:w.array(bm).optional(),currentSubtaskIndex:w.number().optional(),subtaskProgress:Em.optional(),linearId:w.string().optional(),linearUuid:w.string().optional(),linkedSpecId:w.string().optional(),estimatedPoints:w.number().optional(),estimatedMinutes:w.number().optional(),modelMetadata:Es.optional(),tokensIn:w.number().optional(),tokensOut:w.number().optional(),parentDescription:w.string().optional(),branch:w.string().optional(),prUrl:w.string().optional(),harness:xc.optional(),turnCount:w.number().optional(),turnLimitAcknowledgedAt:w.string().optional()}),wm=w.object({id:w.string(),description:w.string(),status:w.literal("paused"),startedAt:w.string(),pausedAt:w.string(),pauseReason:w.string().optional(),type:qi.optional(),sessionId:w.string().optional(),featureId:w.string().optional(),subtasks:w.array(bm).optional(),currentSubtaskIndex:w.number().optional(),subtaskProgress:Em.optional(),linearId:w.string().optional(),linearUuid:w.string().optional(),estimatedPoints:w.number().optional(),estimatedMinutes:w.number().optional(),modelMetadata:Es.optional(),tokensIn:w.number().optional(),tokensOut:w.number().optional(),harness:xc.optional()}),Kv=w.object({stackConfirmed:w.array(w.string()).optional(),patternsDiscovered:w.array(w.string()).optional(),agentAccuracy:w.array(w.object({agent:w.string(),rating:w.enum(["helpful","neutral","inaccurate"]),note:w.string().optional()})).optional(),issuesEncountered:w.array(w.string()).optional()}),zv=w.object({taskId:w.string(),title:w.string(),classification:qi,startedAt:w.string(),completedAt:w.string(),subtaskCount:w.number(),subtaskSummaries:w.array(Tc),outcome:w.string(),branchName:w.string(),linearId:w.string().optional(),linearUuid:w.string().optional(),prUrl:w.string().optional(),feedback:Kv.optional(),harness:xc.optional(),tokensIn:w.number().optional(),tokensOut:w.number().optional()}),Yv=Sm.extend({workspaceId:w.string(),worktreePath:w.string().optional(),agentSessionId:w.string().optional(),jiraId:w.string().optional(),jiraUuid:w.string().optional(),dispatchedFrom:w.string().optional()}),vm=w.object({currentTask:Sm.nullable(),previousTask:wm.nullable().optional(),pausedTasks:w.array(wm).optional(),taskHistory:w.array(zv).optional(),activeTasks:w.array(Yv).optional(),lastUpdated:w.string()}),Qv=w.object({id:w.string(),description:w.string(),body:w.string().optional(),priority:Hv,type:qi,featureId:w.string().optional(),originFeature:w.string().optional(),completed:w.boolean(),completedAt:w.string().optional(),createdAt:w.string(),section:Wv,agent:w.string().optional(),groupName:w.string().optional(),groupId:w.string().optional()}),Tm=w.object({tasks:w.array(Qv),lastUpdated:w.string()})});var Ps,Cc,xn,Rc=f(()=>{"use strict";Ps={idle:{transitions:["task"],prompt:"prjct work <intent> Start working",description:"No active work cycle"},working:{transitions:["done","pause"],prompt:"prjct status done Complete work | prjct status paused Switch context",description:"Work in progress"},paused:{transitions:["resume","task","ship"],prompt:"prjct status active Continue | prjct work <new> Start different | prjct ship Ship directly",description:"Task paused"},completed:{transitions:["ship","task","pause","reopen"],prompt:"prjct ship Ship it | prjct work <next> Start next | prjct status active Reopen",description:"Task completed"},shipped:{transitions:["task"],prompt:"prjct work <intent> Start new work cycle",description:"Feature shipped"}},Cc=class{static{a(this,"WorkflowStateMachine")}getCurrentState(e,t){if(t){let s=(e?.activeTasks??[]).find(i=>i.workspaceId===t);return s?this.statusToState(s):"idle"}let n=e?.currentTask;return n?this.statusToState(n):(e?.pausedTasks?.length||0)>0||e?.previousTask?.status==="paused"?"paused":"idle"}statusToState(e){switch((typeof e.status=="string"?e.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"working"}}canTransition(e,t){if(Ps[e].transitions.includes(t))return{valid:!0};let s=this.formatNextSteps(e).join(" | ");return{valid:!1,error:`Cannot transition to '${t}' from '${e}' state`,suggestion:`Valid next steps: ${s}`}}getNextState(e,t){switch(t){case"task":return"working";case"done":return"completed";case"pause":return"paused";case"resume":return"working";case"ship":return"shipped";case"reopen":return"working";default:return e}}getStateInfo(e){return Ps[e]}getPrompt(e){return Ps[e].prompt}getValidCommands(e){return Ps[e].transitions}formatNextSteps(e){return Ps[e].transitions.map(n=>{switch(n){case"task":return"prjct work <intent> Start new work cycle";case"done":return"prjct status done Complete current work";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 ${n}`}})}},xn=new Cc});import Zv from"node:crypto";function xe(){return Zv.randomUUID()}var Yt=f(()=>{"use strict";a(xe,"generateUUID")});var _c,Hr,xm=f(()=>{"use strict";J();G();_c=class{static{a(this,"SyncPendingStorage")}append(e,t){let n=k(),s=JSON.stringify(t);return t.entityType&&t.entityId&&t.contentHash&&h.run(e,`DELETE FROM sync_pending
|
|
704
704
|
WHERE project_id = ?
|
|
705
705
|
AND entity_type = ?
|
|
706
706
|
AND entity_id = ?
|