prjct-cli 3.92.0 → 3.93.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 +5 -0
- package/dist/bin/hook-chunks/{agent-switch-XMFUTNNV.mjs → agent-switch-A6AYZRJ5.mjs} +1 -1
- package/dist/bin/hook-chunks/{analysis-PFGKPYWQ.mjs → analysis-WPRPBYHY.mjs} +15 -15
- package/dist/bin/hook-chunks/{auto-flush-QZ3YIQP6.mjs → auto-flush-5D4PKOMM.mjs} +1 -1
- package/dist/bin/hook-chunks/{capture-gate-2FXYVHNF.mjs → capture-gate-EOOSAGAP.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-DGBDMUBL.mjs → chunk-3WY2AYPE.mjs} +2 -2
- package/dist/bin/hook-chunks/{chunk-I5BDN25C.mjs → chunk-4OYUJTPR.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-XHDNPEAN.mjs → chunk-6WXGOGAN.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-S4TB2OFJ.mjs → chunk-742LOGHA.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-ZNQXFWSI.mjs → chunk-7AN7VQHN.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-GELCZWKW.mjs → chunk-A7SGMNOK.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-NLDL3N6R.mjs → chunk-ACKEPXP4.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-WSFHSXBZ.mjs → chunk-BNWB77U5.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-MQVVNX63.mjs → chunk-DLHSCKBJ.mjs} +1 -1
- package/dist/bin/hook-chunks/chunk-DV7KV2O4.mjs +38 -0
- package/dist/bin/hook-chunks/{chunk-7JE6VTLN.mjs → chunk-EHP4DYVQ.mjs} +9 -9
- package/dist/bin/hook-chunks/{chunk-CQUG6SO2.mjs → chunk-GIMUTVLP.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-BZ5UR7G3.mjs → chunk-HT3ZCLLJ.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-OLKNK2HB.mjs → chunk-JRKGG2E3.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-OL6ITIAZ.mjs → chunk-KXWBIQGJ.mjs} +2 -2
- package/dist/bin/hook-chunks/{chunk-5PEHJEFE.mjs → chunk-L4376X2P.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-MAHTF6JG.mjs → chunk-LFY5O66D.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-SY2FRLJF.mjs → chunk-MHRMV4WI.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-HX42HFII.mjs → chunk-OB5GRS7T.mjs} +4 -4
- package/dist/bin/hook-chunks/{chunk-2WPR5GFT.mjs → chunk-P4J6TY2L.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-ZX6BC2EB.mjs → chunk-P5ZYAXSE.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-2HTDCLZD.mjs → chunk-PWMMLXZS.mjs} +2 -2
- package/dist/bin/hook-chunks/{chunk-DVBBB5BS.mjs → chunk-QK2IMCDC.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-TBM7736J.mjs → chunk-RXD7MHJ6.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-AWD2AQVJ.mjs → chunk-TSCXXNUF.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-CPHUFXD2.mjs → chunk-UB53HQMG.mjs} +2 -2
- package/dist/bin/hook-chunks/{chunk-3X7TBM4A.mjs → chunk-UBMIPWJR.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-OP467HW6.mjs → chunk-UK7D7EFV.mjs} +2 -2
- package/dist/bin/hook-chunks/{chunk-CDCCAU22.mjs → chunk-VPPHD762.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-Y7CKMFNW.mjs → chunk-VV7VNUTF.mjs} +1 -1
- package/dist/bin/hook-chunks/{codex-skill-2N6656SR.mjs → codex-skill-ZCAUF2RM.mjs} +1 -1
- package/dist/bin/hook-chunks/{command-installer-XSKQS3IS.mjs → command-installer-LNK7WC5I.mjs} +1 -1
- package/dist/bin/hook-chunks/{config-manager-YZANYLPV.mjs → config-manager-4VWDBPMG.mjs} +1 -1
- package/dist/bin/hook-chunks/{cwd-changed-NJ6RYVOJ.mjs → cwd-changed-FYNPPO73.mjs} +1 -1
- package/dist/bin/hook-chunks/detect-changes-M2OYIOE5.mjs +19 -0
- package/dist/bin/hook-chunks/{distill-IABVRW2U.mjs → distill-W7QGQUDX.mjs} +1 -1
- package/dist/bin/hook-chunks/{enriched-recall-NDASPZXZ.mjs → enriched-recall-W7KYRYVR.mjs} +1 -1
- package/dist/bin/hook-chunks/{format-NIBVWBGR.mjs → format-BOWFDUBP.mjs} +1 -1
- package/dist/bin/hook-chunks/{judgment-receipt-HTNEOJLT.mjs → judgment-receipt-WGTFKID7.mjs} +1 -1
- package/dist/bin/hook-chunks/{land-cue-FNLP4IAB.mjs → land-cue-WLGSULSO.mjs} +1 -1
- package/dist/bin/hook-chunks/{land-synthesis-HBPIXP5S.mjs → land-synthesis-V7UH5QV6.mjs} +1 -1
- package/dist/bin/hook-chunks/{legacy-crew-sweep-2MLYPNQR.mjs → legacy-crew-sweep-MFE4BDNR.mjs} +2 -2
- package/dist/bin/hook-chunks/{memory-index-MQCHZFUE.mjs → memory-index-B53F5HAX.mjs} +1 -1
- package/dist/bin/hook-chunks/{notification-VQM2AMNS.mjs → notification-HJLS4L7Y.mjs} +1 -1
- package/dist/bin/hook-chunks/{pack-integrity-BKLDNYE5.mjs → pack-integrity-62XJ5A75.mjs} +1 -1
- package/dist/bin/hook-chunks/{pack-manager-ASWLKYGP.mjs → pack-manager-K3PQ7MCS.mjs} +1 -1
- package/dist/bin/hook-chunks/{planning-QBSY272P.mjs → planning-WMLFXZMA.mjs} +2 -2
- package/dist/bin/hook-chunks/{post-edit-VTLDHWI3.mjs → post-edit-TT3XOG55.mjs} +1 -1
- package/dist/bin/hook-chunks/{pre-bash-JR6257XO.mjs → pre-bash-2KKF4V6G.mjs} +1 -1
- package/dist/bin/hook-chunks/{pre-commit-BYUFDN2N.mjs → pre-commit-UU4SKKWV.mjs} +1 -1
- package/dist/bin/hook-chunks/{pre-edit-MHROFDS3.mjs → pre-edit-RTBLZPWH.mjs} +1 -1
- package/dist/bin/hook-chunks/{pre-package-P7CLTJJV.mjs → pre-package-LQTINBT4.mjs} +1 -1
- package/dist/bin/hook-chunks/{pre-search-BCQHPE46.mjs → pre-search-UJU3XZ2K.mjs} +1 -1
- package/dist/bin/hook-chunks/{prjct-md-WE6WFVL3.mjs → prjct-md-Q6C5YNI3.mjs} +1 -1
- package/dist/bin/hook-chunks/{project-agent-surfaces-A6HGZPAL.mjs → project-agent-surfaces-3BBZIQNI.mjs} +1 -1
- package/dist/bin/hook-chunks/{project-memory-ON54KZEM.mjs → project-memory-YHQBRX3D.mjs} +1 -1
- package/dist/bin/hook-chunks/{project-style-evolution-T27I5N65.mjs → project-style-evolution-HS6HYI7W.mjs} +1 -1
- package/dist/bin/hook-chunks/{prompt-JIOMJCGV.mjs → prompt-AYY7BZFG.mjs} +2 -2
- package/dist/bin/hook-chunks/{purge-QQ6XILZD.mjs → purge-AXMYTZVM.mjs} +1 -1
- package/dist/bin/hook-chunks/{retention-E7WGFL47.mjs → retention-22OSCAGV.mjs} +1 -1
- package/dist/bin/hook-chunks/{sdd-PV6KWXE4.mjs → sdd-W3OUQPHD.mjs} +1 -1
- package/dist/bin/hook-chunks/{session-continuity-5CLT5YBL.mjs → session-continuity-LO2KNHXU.mjs} +1 -1
- package/dist/bin/hook-chunks/{session-start-ATYLOUKB.mjs → session-start-5UZSL6OY.mjs} +1 -1
- package/dist/bin/hook-chunks/{setup-VL7YXVE5.mjs → setup-BSWLQJPE.mjs} +2 -2
- package/dist/bin/hook-chunks/{shipping-LVTFVSWJ.mjs → shipping-HV5IAM2J.mjs} +4 -4
- package/dist/bin/hook-chunks/{spec-context-inference-U6BGGB2Q.mjs → spec-context-inference-UBHJLOIJ.mjs} +1 -1
- package/dist/bin/hook-chunks/{spec-service-2DVDFOR7.mjs → spec-service-TA4Q5S3X.mjs} +2 -2
- package/dist/bin/hook-chunks/{spec-task-breakdown-MPNRRTNZ.mjs → spec-task-breakdown-QJWGCON2.mjs} +1 -1
- package/dist/bin/hook-chunks/{stop-GBUGB5OE.mjs → stop-QVDK6LUV.mjs} +2 -2
- package/dist/bin/hook-chunks/{subagent-start-HURF2GI7.mjs → subagent-start-UYBSD7VK.mjs} +1 -1
- package/dist/bin/hook-chunks/{subagent-stop-WJECHEXI.mjs → subagent-stop-FHLL7X66.mjs} +1 -1
- package/dist/bin/hook-chunks/{surface-attribution-BDKFYUOJ.mjs → surface-attribution-HYCBHBTC.mjs} +1 -1
- package/dist/bin/hook-chunks/{task-service-BM2JQXMS.mjs → task-service-RMCQEHV6.mjs} +1 -1
- package/dist/bin/hook-chunks/{tdd-UJDJUJ3E.mjs → tdd-LV63NXZ3.mjs} +1 -1
- package/dist/bin/hook-chunks/{template-loader-BFTLPG2W.mjs → template-loader-SO6OHPJI.mjs} +1 -1
- package/dist/bin/hook-chunks/{weak-model-mode-GLXXHG32.mjs → weak-model-mode-VDYJ25PX.mjs} +1 -1
- package/dist/bin/hook-chunks/{work-scope-VTF6SKLY.mjs → work-scope-OKFSTW6D.mjs} +1 -1
- package/dist/bin/prjct-core.mjs +694 -692
- package/dist/bin/prjct-hooks.mjs +1 -1
- package/dist/daemon/entry.mjs +609 -607
- package/dist/mcp/server.mjs +309 -307
- package/package.json +1 -1
- package/dist/bin/hook-chunks/chunk-KB3P6XTL.mjs +0 -38
- package/dist/bin/hook-chunks/detect-changes-6N4DCWXQ.mjs +0 -17
package/package.json
CHANGED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __createRequire } from 'module';
|
|
3
|
-
import { fileURLToPath as __fileURLToPath } from 'url';
|
|
4
|
-
import { dirname as __pathDirname } from 'path';
|
|
5
|
-
const require = __createRequire(import.meta.url);
|
|
6
|
-
const __filename = __fileURLToPath(import.meta.url);
|
|
7
|
-
const __dirname = __pathDirname(__filename);
|
|
8
|
-
import{b as Ct}from"./chunk-FGQZ62ZP.mjs";import{a as gt,b as ht,c as yt,d as St,e as wt}from"./chunk-TXJT3G53.mjs";import{a as ut}from"./chunk-A5RNWWTH.mjs";import{a as Be}from"./chunk-HZIORCPO.mjs";import{a as Je}from"./chunk-WDGDFXSB.mjs";import{a as ne,b as qe}from"./chunk-NWY5M34K.mjs";import{a as Ke,b as xt}from"./chunk-2HTDCLZD.mjs";import{a as mt,b as pt}from"./chunk-CPHUFXD2.mjs";import{d as ft}from"./chunk-GELCZWKW.mjs";import{a as ct,b as lt}from"./chunk-QDQ7DTDV.mjs";import{a as kt,b as vt,c as bt,d as Pt}from"./chunk-ZTZTVBAZ.mjs";import{a as f}from"./chunk-DYHYDHCW.mjs";import{b as Y,c as tt,d as rt}from"./chunk-YJMWY4Y6.mjs";import{c as st,d as nt,e as oe,f as at,g as ot}from"./chunk-NJAMZSHM.mjs";import{a as it}from"./chunk-MQVVNX63.mjs";import{i as dt}from"./chunk-J6JZ4PQA.mjs";import{a as et}from"./chunk-2WPR5GFT.mjs";import{b as Qe,c as Xe,d as Ze}from"./chunk-4DDCWMI6.mjs";import{a as Ye}from"./chunk-DVBBB5BS.mjs";import{a as ae,b as R}from"./chunk-BISPGBNN.mjs";import{a as ze}from"./chunk-HJ4HEI45.mjs";import{c as Ve}from"./chunk-3LG3ACQV.mjs";import{c as We}from"./chunk-AOPJ4Z6O.mjs";import{b as T}from"./chunk-OLKNK2HB.mjs";import{d as P,e as I,g as K}from"./chunk-HDHVBB6Q.mjs";import{d as se}from"./chunk-CDCCAU22.mjs";import{b,e as re,m as He,o as Le,r as br,s as q,t as Ge}from"./chunk-AKIN5WSQ.mjs";import{b as Ne,f as vr}from"./chunk-HDSS6UB3.mjs";import{d as Te,e as $e,f as Oe,j as L,n as B}from"./chunk-SVZHJZ5T.mjs";import{a as _e,o as kr}from"./chunk-CTWZQ7YI.mjs";import{a as Ue}from"./chunk-ZNQXFWSI.mjs";import{d as w}from"./chunk-PKDYFXMI.mjs";import{a as M,d as Me,e as v,f as N}from"./chunk-BUDZL4DW.mjs";import{a as i}from"./chunk-E66B27AL.mjs";function Dt(r,e){let t=[];G("Languages",r.languages,e.languages,t),G("Frameworks",r.frameworks,e.frameworks,t),(r.packageManager??"")!==(e.packageManager??"")&&t.push({field:"Package manager",type:"changed",before:r.packageManager??"(none)",after:e.packageManager??"(none)"}),(r.sourceDir??"")!==(e.sourceDir??"")&&t.push({field:"Source directory",type:"changed",before:r.sourceDir??"(none)",after:e.sourceDir??"(none)"}),(r.testDir??"")!==(e.testDir??"")&&t.push({field:"Test directory",type:"changed",before:r.testDir??"(none)",after:e.testDir??"(none)"}),G("Config files",r.configFiles,e.configFiles,t),r.fileCount!==e.fileCount&&t.push({field:"File count",type:"changed",before:String(r.fileCount),after:String(e.fileCount)});let s=r.patterns.map(u=>u.name),a=e.patterns.map(u=>u.name);G("Patterns",s,a,t);let o=r.antiPatterns.map(u=>u.issue),n=e.antiPatterns.map(u=>u.issue);G("Anti-patterns",o,n,t);let l=t.filter(u=>u.type==="added").length,c=t.filter(u=>u.type==="removed").length,d=t.filter(u=>u.type==="changed").length;return{hasChanges:t.length>0,items:t,summary:{added:l,removed:c,changed:d},beforeCommit:r.commitHash??null,afterCommit:e.commitHash??null}}i(Dt,"generateAnalysisDiff");function ps(r){if(!r.hasChanges)return`## Analysis Diff
|
|
9
|
-
|
|
10
|
-
No changes between runs.`;let e=[];e.push("## Analysis Diff"),(r.beforeCommit||r.afterCommit)&&e.push(`> \`${r.beforeCommit?.substring(0,7)??"(none)"}\` \u2192 \`${r.afterCommit?.substring(0,7)??"(none)"}\``),e.push(""),e.push("| Change | Field | Detail |"),e.push("|--------|-------|--------|");for(let s of r.items){let a=s.type==="added"?"+":s.type==="removed"?"-":"~",o=s.type==="changed"?`${s.before} \u2192 ${s.after}`:s.after??s.before??"";e.push(`| ${a} | ${s.field} | ${o} |`)}e.push("");let t=[];return r.summary.added>0&&t.push(`${r.summary.added} added`),r.summary.removed>0&&t.push(`${r.summary.removed} removed`),r.summary.changed>0&&t.push(`${r.summary.changed} changed`),e.push(`**Summary**: ${t.join(", ")}`),e.join(`
|
|
11
|
-
`)}i(ps,"formatAnalysisDiffMd");function fs(r){if(!r.hasChanges)return"No changes between analysis runs.";let e=[];(r.beforeCommit||r.afterCommit)&&(e.push(` ${r.beforeCommit?.substring(0,7)??"(none)"} \u2192 ${r.afterCommit?.substring(0,7)??"(none)"}`),e.push(""));for(let t of r.items)t.type==="added"?e.push(` + ${t.field}: ${t.after}`):t.type==="removed"?e.push(` - ${t.field}: ${t.before}`):e.push(` ~ ${t.field}: ${t.before} \u2192 ${t.after}`);return e.join(`
|
|
12
|
-
`)}i(fs,"formatAnalysisDiffText");function G(r,e,t,s){let a=new Set(e),o=new Set(t);for(let n of t)a.has(n)||s.push({field:r,type:"added",after:n});for(let n of e)o.has(n)||s.push({field:r,type:"removed",before:n})}i(G,"diffStringArray");N();B();vr();import ie from"node:fs/promises";import F from"node:path";import{z as p}from"zod";var Pr=p.enum(["draft","verified","sealed"]),Cr=p.object({name:p.string(),description:p.string(),location:p.string().optional(),severity:p.enum(["low","medium","high"]).optional(),language:p.string().optional(),framework:p.string().optional(),source:p.enum(["baseline","repo","context7","feedback"]).optional(),confidence:p.number().min(0).max(1).optional()}),xr=p.object({issue:p.string(),file:p.string(),suggestion:p.string(),severity:p.enum(["low","medium","high"]).optional(),language:p.string().optional(),framework:p.string().optional(),source:p.enum(["baseline","repo","context7","feedback"]).optional(),confidence:p.number().min(0).max(1).optional()}),ce=p.object({projectId:p.string(),languages:p.array(p.string()),frameworks:p.array(p.string()),packageManager:p.string().optional(),sourceDir:p.string().optional(),testDir:p.string().optional(),configFiles:p.array(p.string()),fileCount:p.number(),patterns:p.array(Cr),antiPatterns:p.array(xr),analyzedAt:p.string(),modelMetadata:Ne.optional(),status:Pr.default("draft"),commitHash:p.string().optional(),signature:p.string().optional(),sealedAt:p.string().optional(),verifiedAt:p.string().optional()});var Dr={TypeScript:[".ts",".tsx",".mts",".cts"],JavaScript:[".js",".jsx",".mjs",".cjs"],Python:[".py",".pyw"],Java:[".java"],Go:[".go"],Rust:[".rs"],Ruby:[".rb"],PHP:[".php"],Swift:[".swift"],Kotlin:[".kt",".kts"],"C++":[".cpp",".cc",".cxx",".hpp",".h"],C:[".c",".h"],"C#":[".cs"],Elixir:[".ex",".exs"],Scala:[".scala"]};async function Ar(r,e){let t=Date.now();if(r.frameworks.length===0)return{name:"Framework verification",passed:!0,output:"No frameworks declared (skipped)",durationMs:Date.now()-t};try{let s=F.join(e,"package.json"),a=await ie.readFile(s,"utf-8"),o=JSON.parse(a),n={...o.dependencies,...o.devDependencies},l=[],c=[];for(let d of r.frameworks){let u=d.toLowerCase();Object.keys(n).some(y=>y.toLowerCase().includes(u))?c.push(d):l.push(d)}return l.length===0?{name:"Framework verification",passed:!0,output:`${c.length} framework(s) verified in dependencies`,durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Frameworks not found in dependencies: ${l.join(", ")}`,durationMs:Date.now()-t}}catch(s){return M(s)?{name:"Framework verification",passed:!1,error:"package.json not found (cannot verify frameworks)",durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Failed to read package.json: ${s instanceof Error?s.message:"unknown error"}`,durationMs:Date.now()-t}}}i(Ar,"verifyFrameworks");async function jr(r,e){let t=Date.now();if(r.languages.length===0)return{name:"Language verification",passed:!0,output:"No languages declared (skipped)",durationMs:Date.now()-t};try{let s=await Fr(e),a=new Set(s),o=[],n=[];for(let l of r.languages){let c=Dr[l];if(!c)continue;c.some(u=>a.has(u))?o.push(l):n.push(l)}return n.length===0?{name:"Language verification",passed:!0,output:`${o.length} language(s) verified with matching files`,durationMs:Date.now()-t}:{name:"Language verification",passed:!1,error:`Languages without matching files: ${n.join(", ")}`,durationMs:Date.now()-t}}catch(s){return{name:"Language verification",passed:!1,error:`Failed to scan project files: ${s instanceof Error?s.message:"unknown error"}`,durationMs:Date.now()-t}}}i(jr,"verifyLanguages");async function Ir(r,e){let t=Date.now(),s=r.patterns.filter(n=>n.location);if(s.length===0)return{name:"Pattern location verification",passed:!0,output:"No pattern locations specified (skipped)",durationMs:Date.now()-t};let a=[],o=[];for(let n of s){let l=n.location,c=F.join(e,l);await L(c)?o.push(l):a.push(`${n.name} (${l})`)}return a.length===0?{name:"Pattern location verification",passed:!0,output:`${o.length} pattern location(s) verified`,durationMs:Date.now()-t}:{name:"Pattern location verification",passed:!1,error:`Pattern locations not found: ${a.join(", ")}`,durationMs:Date.now()-t}}i(Ir,"verifyPatternLocations");async function Er(r,e){let t=Date.now();try{let s=await _r(e),a=r.fileCount,o=.1,n=Math.abs(s-a),l=a*o;return n<=l?{name:"File count verification",passed:!0,output:`File count accurate (declared: ${a}, actual: ${s})`,durationMs:Date.now()-t}:{name:"File count verification",passed:!1,error:`File count mismatch: declared ${a}, actual ${s} (diff: ${n})`,durationMs:Date.now()-t}}catch(s){return{name:"File count verification",passed:!1,error:`Failed to count files: ${s instanceof Error?s.message:"unknown error"}`,durationMs:Date.now()-t}}}i(Er,"verifyFileCount");async function Rr(r,e){let t=Date.now();if(r.antiPatterns.length===0)return{name:"Anti-pattern file verification",passed:!0,output:"No anti-patterns declared (skipped)",durationMs:Date.now()-t};let s=[],a=[];for(let o of r.antiPatterns){let n=F.join(e,o.file);await L(n)?a.push(o.file):s.push(`${o.issue} (${o.file})`)}return s.length===0?{name:"Anti-pattern file verification",passed:!0,output:`${a.length} anti-pattern file(s) verified`,durationMs:Date.now()-t}:{name:"Anti-pattern file verification",passed:!1,error:`Anti-pattern files not found: ${s.join(", ")}`,durationMs:Date.now()-t}}i(Rr,"verifyAntiPatternFiles");async function At(r,e){let t=Date.now(),s=await Promise.all([Ar(r,e),jr(r,e),Ir(r,e),Er(r,e),Rr(r,e)]),a=s.filter(n=>!n.passed).length,o=s.filter(n=>n.passed).length;return{passed:a===0,checks:s,totalMs:Date.now()-t,failedCount:a,passedCount:o}}i(At,"semanticVerify");async function Fr(r){let e=new Set,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function s(a){try{let o=await ie.readdir(a,{withFileTypes:!0});for(let n of o){let l=F.join(a,n.name),c=F.relative(r,l);if(!t.some(d=>d.test(c))){if(n.isDirectory())await s(l);else if(n.isFile()){let d=F.extname(n.name);d&&e.add(d)}}}}catch{}}return i(s,"scanDir"),await s(r),Array.from(e)}i(Fr,"getProjectExtensions");async function _r(r){let e=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function t(s){try{let a=await ie.readdir(s,{withFileTypes:!0});return(await Promise.all(a.map(async n=>{let l=F.join(s,n.name),c=F.relative(r,l);return e.some(d=>d.test(c))?0:n.isDirectory()?t(l):n.isFile()?1:0}))).reduce((n,l)=>n+l,0)}catch{return 0}}return i(t,"scanDir"),t(r)}i(_r,"countProjectFiles");re();var le=class extends ze{static{i(this,"AnalysisStorage")}constructor(){super("analysis.json")}getDefault(){return{draft:null,sealed:null,previousSealed:null,lastUpdated:""}}getEventType(e){return`analysis.${e}d`}async saveDraft(e,t){let s={...t,status:"draft"};ce.parse(s),await this.update(e,a=>({...a,draft:s,lastUpdated:b()})),this.publishAnalysis(e,s)}publishAnalysis(e,t){We({projectId:e,entityType:"analysis",entityId:e,eventType:"upsert",data:{...t,id:e}})}async seal(e){let t=await this.read(e);if(!t.draft)return{success:!1,error:"No draft analysis to seal. Run `p. sync` first."};if(t.draft.status==="sealed")return{success:!1,error:"Draft is already sealed."};let s=this.computeSignature(t.draft),a=b(),o={...t.draft,status:"sealed",signature:s,sealedAt:a};return ce.parse(o),await this.write(e,{draft:null,sealed:o,previousSealed:t.sealed,lastUpdated:a}),this.publishAnalysis(e,o),{success:!0,signature:s}}async getSealed(e){return(await this.read(e)).sealed}async getDraft(e){return(await this.read(e)).draft}async getActive(e){let t=await this.read(e);return t.sealed??t.draft}async getStatus(e){let t=await this.read(e);return{hasSealed:t.sealed!==null,hasDraft:t.draft!==null,hasPreviousSealed:t.previousSealed!==null,sealedCommit:t.sealed?.commitHash??null,draftCommit:t.draft?.commitHash??null,previousSealedCommit:t.previousSealed?.commitHash??null,sealedAt:t.sealed?.sealedAt??null}}async rollback(e){let t=await this.read(e);if(!t.previousSealed)return{success:!1,error:"No previous sealed version to rollback to."};let s=b();return await this.write(e,{draft:t.sealed,sealed:t.previousSealed,previousSealed:null,lastUpdated:s}),this.publishAnalysis(e,t.previousSealed),{success:!0,restoredSignature:t.previousSealed.signature}}async diff(e){let t=await this.read(e);return!t.sealed||!t.draft?null:Dt(t.sealed,t.draft)}checkStaleness(e,t){return e?t?e!==t?{isStale:!0,sealedCommit:e,currentCommit:t,message:`Analysis is stale: sealed at ${e}, HEAD is ${t}. Run \`p. sync\` + \`p. seal\` to update.`}:{isStale:!1,sealedCommit:e,currentCommit:t,message:"Analysis is current."}:{isStale:!0,sealedCommit:e,currentCommit:null,message:"Cannot determine current commit. Analysis may be stale."}:{isStale:!1,sealedCommit:null,currentCommit:t,message:"No sealed analysis. Run `p. sync` then `p. seal`."}}async verify(e){let t=await this.read(e);if(!t.sealed)return{valid:!1,message:"No sealed analysis to verify."};if(!t.sealed.signature)return{valid:!1,message:"Sealed analysis has no signature."};let s=this.computeSignature({...t.sealed,signature:void 0,sealedAt:void 0});return s===t.sealed.signature?{valid:!0,message:"Signature verified. Analysis integrity confirmed."}:{valid:!1,message:`Signature mismatch. Expected ${s}, got ${t.sealed.signature}. Analysis may have been modified.`}}async semanticVerify(e,t){let s=await this.read(e),a=s.sealed??s.draft;return a?await At(a,t):{passed:!1,checks:[{name:"Analysis availability",passed:!1,error:"No analysis available. Run `p. sync` to generate.",durationMs:0}],totalMs:0,failedCount:1,passedCount:0}}computeSignature(e){let t={projectId:e.projectId,languages:e.languages,frameworks:e.frameworks,packageManager:e.packageManager,sourceDir:e.sourceDir,testDir:e.testDir,configFiles:e.configFiles,fileCount:e.fileCount,patterns:e.patterns,antiPatterns:e.antiPatterns,analyzedAt:e.analyzedAt,commitHash:e.commitHash};return ct(JSON.stringify(t))}},Q=new le;import ds from"node:fs/promises";import ee from"node:path";br();Ge();B();import de from"node:fs/promises";import jt from"node:path";import{gunzipSync as Mr,gzipSync as Tr}from"node:zlib";Ge();K();var $r="code-graph.json.gz";function It(r){return jt.join(q.getGlobalProjectPath(r),$r)}i(It,"artifactPath");async function Or(r){if(!oe(r))return null;let e=ot(r),t=(()=>{try{return I.query(r,"SELECT src, dst, edge_type, confidence FROM code_symbol_edges").map(c=>({src:c.src,dst:c.dst,edgeType:c.edge_type,confidence:c.confidence}))}catch{return[]}})(),s=at(r)??{symbolCount:e.length,edgeCount:t.length,fileCount:new Set(e.map(c=>c.file)).size,builtAt:new Date().toISOString()},a={version:1,projectId:r,exportedAt:new Date().toISOString(),meta:s,symbols:e,edges:t},o=Buffer.from(JSON.stringify(a),"utf-8"),n=Tr(o,{level:6}),l=It(r);return await de.mkdir(jt.dirname(l),{recursive:!0}),await de.writeFile(l,n),{path:l,bytes:n.length,symbols:e.length,edges:t.length}}i(Or,"exportCodeGraphArtifact");async function Nr(r){let e=It(r),t=await de.readFile(e).catch(()=>null);if(!t)return{imported:!1,symbols:0,edges:0,reason:"no per-project artifact"};let s=(()=>{try{let o=Mr(t).toString("utf-8");return{payload:JSON.parse(o)}}catch(o){return{error:`corrupt artifact: ${o instanceof Error?o.message:String(o)}`}}})();if("error"in s)return{imported:!1,symbols:0,edges:0,reason:s.error};let a=s.payload;return a.version!==1||!Array.isArray(a.symbols)?{imported:!1,symbols:0,edges:0,reason:"unsupported artifact version"}:a.projectId&&a.projectId!==r?{imported:!1,symbols:0,edges:0,reason:`artifact projectId mismatch (got ${a.projectId}, expected ${r})`}:(I.transaction(r,o=>{o.prepare("DELETE FROM code_symbols").run(),o.prepare("DELETE FROM code_symbol_edges").run();let n=o.prepare(`INSERT INTO code_symbols (id, file, kind, name, qname, start_line, end_line, exported)
|
|
13
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`),l=o.prepare(`INSERT OR IGNORE INTO code_symbol_edges (src, dst, edge_type, confidence)
|
|
14
|
-
VALUES (?, ?, ?, ?)`);for(let c of a.symbols)n.run(c.id,c.file,c.kind,c.name,c.qname,c.startLine,c.endLine,c.exported?1:0);for(let c of a.edges)l.run(c.src,c.dst,c.edgeType,c.confidence)}),I.setDoc(r,"symbol-graph",{...a.meta,builtAt:a.meta.builtAt??a.exportedAt}),{imported:!0,symbols:a.symbols.length,edges:a.edges.length})}i(Nr,"importCodeGraphArtifact");async function Et(r){if(oe(r))return{bootstrapped:!1,detail:"local index already present"};let e=await Nr(r);return e.imported?{bootstrapped:!0,detail:`imported ${e.symbols} symbols / ${e.edges} edges from per-project cache`}:{bootstrapped:!1,detail:e.reason??"import failed"}}i(Et,"bootstrapCodeGraphFromArtifact");function Rt(r){return r?.cloud?.enabled===!0&&r.cloud.paused!==!0}i(Rt,"shouldAutoUploadCodeGraph");async function Ft(r,e){try{await Or(r)}catch{}if(e.uploadToCloud)try{await Hr(r,e.uploadDependencies)}catch{}}i(Ft,"maybeExportAfterIndex");async function Hr(r,e={}){let t=await import("./code-graph-cloud-65GCWNII.mjs"),s=(e.buildSnapshot??t.buildCloudCodeGraphSnapshot)(r);if(!t.isUploadableGraph(s))return{uploaded:!1,reason:"no symbol index or empty graph"};try{let o=await(e.upload??(async(n,l)=>{let{default:c}=await import("./sync-client-DJWOG2ZQ.mjs");return c.uploadCodeGraph(n,l)}))(r,s);return o.ok?{uploaded:!0,nodes:o.nodes??s.nodes.length,links:o.links??s.links.length}:{uploaded:!1,reason:o.reason??"upload failed or unauthenticated",nodes:s.nodes.length,links:s.links.length}}catch(a){return{uploaded:!1,reason:a instanceof Error?a.message:String(a)}}}i(Hr,"maybeUploadCodeGraphToCloud");import $ from"node:fs/promises";import Lr from"node:os";import D from"node:path";var ue=[{name:"prjct",description:gt,allowedTools:[...ht],body:i(()=>St(),"body"),reference:i(()=>wt(),"reference"),referenceFile:yt}];function Gr(r){let e=r.userInvocable!==!1;return`---
|
|
15
|
-
description: "${r.description}"
|
|
16
|
-
allowed-tools: [${r.allowedTools.map(t=>`"${t}"`).join(", ")}]
|
|
17
|
-
user-invocable: ${e}
|
|
18
|
-
---`}i(Gr,"buildFrontmatter");function Ur(r){return`${Gr(r)}
|
|
19
|
-
|
|
20
|
-
${r.body()}`}i(Ur,"buildSkillContent");function _t(){return process.env.HOME||Lr.homedir()}i(_t,"homeDir");function Wr(){return D.join(_t(),".claude","skills")}i(Wr,"claudeSkillsRoot");function Vr(){let r=_t();return[D.join(r,".codex","skills"),D.join(r,".gemini","skills"),D.join(r,".gemini","antigravity","global_skills")]}i(Vr,"compactSkillRoots");function zr(r){return!!(/^# [^\n]+\n[^\n]*\|\s*\d+\s+files\s*\|/m.test(r)||/## Recent Deliveries/m.test(r)||/## Velocity/m.test(r)&&/pts\/sprint/m.test(r))}i(zr,"skillBodyHasProjectStamp");var me=class{static{i(this,"SkillGenerator")}async generateAndInstall(){let e={generated:[],skipped:[]},t=Wr();for(let o of ue)try{let n=Ur(o);if(zr(n))throw new Error("refusing to install project-stamped skill body (isolation guard)");let l=D.join(t,o.name),c=D.join(l,"SKILL.md");await $.mkdir(l,{recursive:!0}),await $.writeFile(c,n,"utf-8"),o.reference&&o.referenceFile&&await $.writeFile(D.join(l,o.referenceFile),o.reference(),"utf-8"),e.generated.push({name:o.name,path:c})}catch(n){f.debug(`Failed to generate skill ${o.name}`,{error:w(n)}),e.skipped.push({name:o.name,reason:w(n)})}let s=Ue();for(let o of Vr())try{let n=D.join(o,"prjct"),l=D.join(n,"SKILL.md");await $.mkdir(n,{recursive:!0}),await $.writeFile(l,s,"utf-8"),e.generated.push({name:"prjct-compact",path:l})}catch(n){f.debug("Compact skill install skipped",{root:o,error:w(n)})}let a=new Set(ue.map(o=>o.name));try{let o=await $.readdir(t,{withFileTypes:!0}).catch(()=>[]);for(let n of o)n.isDirectory()&&n.name.startsWith("prjct-")&&!a.has(n.name)&&await $.rm(D.join(t,n.name),{recursive:!0,force:!0}).catch(()=>{})}catch{}return e.generated.length>0&&f.info("Generated portable multi-host skills",{count:e.generated.length,skills:e.generated.map(o=>o.name)}),e}getDefinitions(){return ue}},Mt=new me;function pe(){return{branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0}}i(pe,"emptyGitData");function fe(){return{fileCount:0,version:"0.0.0",name:"unknown",ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]}}i(fe,"emptyStats");function ge(){return{install:"npm install",run:"npm run",test:"npm test",build:"npm run build",dev:"npm run dev",lint:"npm run lint",format:"npm run format"}}i(ge,"emptyCommands");function he(){return{hasFrontend:!1,hasBackend:!1,hasDatabase:!1,hasDocker:!1,hasTesting:!1,frontendType:null,frameworks:[]}}i(he,"emptyStack");function Tt(r,e){let t=[...r.added,...r.modified],s=new Set(t),a=new Set,o=Y(e);if(o)for(let c of t){let d=o.reverse[c];if(d)for(let u of d)s.has(u)||a.add(u)}let n=Array.from(a),l=[...t,...n];return{directlyChanged:t,affectedByImports:n,deleted:r.deleted,allAffected:l}}i(Tt,"propagateChanges");function $t(r){let e=new Set;for(let t of r){let s=t.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/"))&&(e.add("frontend"),e.add("uxui")),(s.includes(".test.")||s.includes(".spec.")||s.includes("__tests__")||s.includes("/test/"))&&e.add("testing"),(s.includes("dockerfile")||s.includes("docker-compose")||s.includes(".dockerignore")||s.includes(".github/")||s.includes("ci/")||s.includes("cd/"))&&e.add("devops"),(s.endsWith(".sql")||s.includes("prisma")||s.includes("drizzle")||s.includes("migration")||s.includes("/db/"))&&e.add("database"),(s.endsWith(".ts")||s.endsWith(".js"))&&!s.includes(".test.")&&!s.includes(".spec.")&&!s.endsWith(".d.ts")&&e.add("backend")}return e}i($t,"affectedDomains");K();B();import Ot from"node:fs/promises";import Jr from"node:path";function Br(r){return typeof Bun<"u"&&Bun.hash?`xxh64:${Bun.hash(r).toString(36)}`:`fnv1a:${([...r].reduce((t,s)=>Math.imul(t^s.charCodeAt(0),16777619),2166136261)>>>0).toString(36)}`}i(Br,"hashContent");async function qr(r,e={}){let t=await Te(r,{skipDotfiles:!0,dotfileAllowlist:[".env.example"]}),s=new Map,a=e.changedFilesHint?.length?new Set(e.changedFilesHint):null,o=await $e(t,100,async n=>{try{let l=Jr.join(r,n),c=await Ot.stat(l),d=c.mtime.toISOString(),u=e.storedHashes?.get(n),h=a?.has(n)??!1;if(u&&!h&&u.size===c.size&&u.mtime===d&&u.hash)return{path:n,hash:u.hash,size:c.size,mtime:d};let y=await Ot.readFile(l,"utf-8");return{path:n,hash:Br(y),size:c.size,mtime:d}}catch{return null}});for(let n of o)s.set(n.path,n);return s}i(qr,"computeHashes");function Kr(r,e){let t=[],s=[],a=[];for(let[n,l]of r){let c=e.get(n);c?c.hash!==l.hash?s.push(n):a.push(n):t.push(n)}let o=[];for(let n of e.keys())r.has(n)||o.push(n);return{added:t,modified:s,deleted:o,unchanged:a}}i(Kr,"diffHashes");function ye(r,e){let t=I.getDb(r);t.transaction(()=>{t.prepare("DELETE FROM index_checksums").run();let s=t.prepare("INSERT INTO index_checksums (path, checksum, size, mtime) VALUES (?, ?, ?, ?)");for(let[,a]of e)s.run(a.path,a.hash,a.size,a.mtime)})(),I.setDoc(r,"file-hashes-meta",{fileCount:e.size,builtAt:new Date().toISOString()})}i(ye,"saveHashes");function Yr(r){let e=new Map;try{let t=I.query(r,"SELECT path, checksum, size, mtime FROM index_checksums");for(let s of t)e.set(s.path,{path:s.path,hash:s.checksum,size:s.size||0,mtime:s.mtime||""})}catch{}return e}i(Yr,"loadHashes");async function Se(r,e,t){let s=Yr(e),a=await qr(r,{storedHashes:s,changedFilesHint:t});return{diff:Kr(a,s),currentHashes:a}}i(Se,"detectChanges");function Nt(r){return I.hasDoc(r,"file-hashes-meta")}i(Nt,"hasHashRegistry");N();var Qr=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);async function Ht(r){let{projectId:e,projectPath:t,isFullSync:s,changedFilesHint:a}=r,o={shouldRebuildIndexes:!0,changedDomains:new Set,incrementalInfo:void 0,changedSourceFiles:[],deletedSourceFiles:[]};if(!s&&Nt(e)){try{let{diff:n,currentHashes:l}=await Se(t,e,a),c=n.added.length+n.modified.length+n.deleted.length,d=(()=>{if(c===0&&!a?.length)return{shouldRebuildIndexes:!1,changedDomains:new Set,incrementalInfo:{isIncremental:!0,filesChanged:0,filesUnchanged:n.unchanged.length,indexesRebuilt:!1,affectedDomains:[]},changedSourceFiles:[],deletedSourceFiles:[]};let u=Tt(n,e),h=$t(u.allAffected),y=u.allAffected.some(we);return{shouldRebuildIndexes:y,changedDomains:h,incrementalInfo:{isIncremental:!0,filesChanged:c,filesUnchanged:n.unchanged.length,indexesRebuilt:y,affectedDomains:Array.from(h)},changedSourceFiles:[...n.added,...n.modified].filter(we),deletedSourceFiles:n.deleted.filter(we)}})();return ye(e,l),d}catch(n){f.debug("Incremental detection failed, falling back to full sync",{error:v(n)})}return o}try{let{currentHashes:n}=await Se(t,e,a);ye(e,n)}catch(n){f.debug("Hash computation failed (non-critical)",{error:v(n)})}return o}i(Ht,"detectIncrementalChanges");function we(r){let e=r.substring(r.lastIndexOf("."));return Qr.has(e)}i(we,"isSourceFile");import{z as A}from"zod";var gn=A.object({date:A.string(),tokensSaved:A.number(),syncs:A.number(),avgCompressionRate:A.number(),totalDuration:A.number()}),hn=A.object({agentName:A.string(),usageCount:A.number(),tokensSaved:A.number()}),Lt={"claude-opus-4.5":.005,"claude-sonnet-4.5":.003,"claude-haiku-4.5":.001,"claude-opus-4":.015,"claude-sonnet-4":.003,"gpt-4o":.0025,"gemini-pro":.00125,default:.003};function Gt(r,e="default"){let t=Lt[e]||Lt.default;return r/1e3*t}i(Gt,"estimateCostSaved");function yn(r){return r<.01?`$${(r*100).toFixed(2)}\xA2`:`$${r.toFixed(2)}`}i(yn,"formatCost");K();var Xr=i(r=>({date:r.date,tokensSaved:r.tokens_saved,syncs:r.syncs,avgCompressionRate:r.avg_compression_rate,totalDuration:r.total_duration}),"rowToDaily"),X=i(r=>{let e=new Date;return e.setDate(e.getDate()-r),e.toISOString().split("T")[0]},"dayCutoff"),ke=class{static{i(this,"MetricsStorage")}async recordSync(e,t){let s=Math.max(0,t.originalSize-t.filteredSize),a=t.originalSize>0?s/t.originalSize:0,o=new Date().toISOString().split("T")[0];if(P.run(e,`INSERT INTO metrics_daily (date, tokens_saved, syncs, avg_compression_rate, total_duration)
|
|
21
|
-
VALUES (?, ?, 1, ?, ?)
|
|
22
|
-
ON CONFLICT(date) DO UPDATE SET
|
|
23
|
-
tokens_saved = metrics_daily.tokens_saved + excluded.tokens_saved,
|
|
24
|
-
avg_compression_rate =
|
|
25
|
-
(metrics_daily.avg_compression_rate * metrics_daily.syncs + excluded.avg_compression_rate)
|
|
26
|
-
/ (metrics_daily.syncs + 1),
|
|
27
|
-
syncs = metrics_daily.syncs + 1,
|
|
28
|
-
total_duration = metrics_daily.total_duration + excluded.total_duration`,o,s,a,t.duration),t.agents?.length){let n=Math.floor(s/t.agents.length);for(let l of t.agents)P.run(e,`INSERT INTO metrics_agent_usage (agent_name, usage_count, tokens_saved)
|
|
29
|
-
VALUES (?, 1, ?)
|
|
30
|
-
ON CONFLICT(agent_name) DO UPDATE SET
|
|
31
|
-
usage_count = metrics_agent_usage.usage_count + 1,
|
|
32
|
-
tokens_saved = metrics_agent_usage.tokens_saved + excluded.tokens_saved`,l,n)}}async getSummary(e){let t=P.get(e,`SELECT COALESCE(SUM(tokens_saved), 0) AS tokens,
|
|
33
|
-
COALESCE(SUM(syncs), 0) AS syncs,
|
|
34
|
-
COALESCE(SUM(total_duration), 0) AS duration,
|
|
35
|
-
COALESCE(SUM(avg_compression_rate * syncs), 0) AS weighted_rate
|
|
36
|
-
FROM metrics_daily`),s=t?.syncs??0,a=t?.tokens??0,o=i((u,h)=>P.get(e,h?"SELECT COALESCE(SUM(tokens_saved), 0) AS t FROM metrics_daily WHERE date >= ? AND date < ?":"SELECT COALESCE(SUM(tokens_saved), 0) AS t FROM metrics_daily WHERE date >= ?",...h?[u,h]:[u])?.t??0,"rangeTokens"),n=o(X(30)),l=o(X(60),X(30)),c=l>0?(n-l)/l*100:0,d=P.query(e,"SELECT * FROM metrics_agent_usage ORDER BY usage_count DESC LIMIT 5").map(u=>({agentName:u.agent_name,usageCount:u.usage_count,tokensSaved:u.tokens_saved}));return{totalTokensSaved:a,estimatedCostSaved:Gt(a),compressionRate:s>0?(t?.weighted_rate??0)/s:0,syncCount:s,avgSyncDuration:s>0?(t?.duration??0)/s:0,topAgents:d,last30DaysTokens:n,trend:c}}async getDailyStats(e,t=30){return P.query(e,"SELECT * FROM metrics_daily WHERE date >= ? ORDER BY date ASC",X(t)).map(Xr)}async getFirstSyncDate(e){return P.get(e,"SELECT MIN(date) AS d FROM metrics_daily")?.d??""}},Ut=new ke;N();re();import Zr from"node:path";function es(r){return lt(Zr.resolve(r))}i(es,"repoHash");function U(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"")}i(U,"normalizeKey");function ts(r){return ne(r,e=>`${U(e.name)}::${U(e.source)}`)}i(ts,"dedupePatterns");function rs(r){return ne(r,e=>`${U(e.issue)}::${U(e.file)}::${U(e.source)}`)}i(rs,"dedupeAntiPatterns");var ve=class{static{i(this,"PatternExtractor")}async extract(e){let t=es(e.projectPath),s=[];if(e.context7Verified)for(let c of e.frameworks)s.push({name:`${c} API validation via Context7`,description:`Validate ${c} APIs against current documentation through Context7 before implementation.`,framework:c,source:"context7",confidence:.7});let a=(e.feedback?.patternsDiscovered||[]).map(c=>({name:c,description:`Confirmed during completed tasks: ${c}`,source:"feedback",confidence:.75})),o=(e.feedback?.knownGotchas||[]).map(c=>({issue:c,file:"multiple",suggestion:`Recurring gotcha. Prevent this pattern during implementation: ${c}`,source:"feedback",severity:"medium",confidence:.7})),n=ts([...s,...a]),l=rs([...o]);return{patterns:n,antiPatterns:l,repoPathHash:t}}},ss=new ve,Wt=ss;var Vt=200;async function zt(r,e,t){let{bm25Index:s,originalSize:a}=(()=>{try{let d=Qe(r),u=d?Object.values(d.documents).reduce((h,y)=>h+y.length,0):0;return{bm25Index:d,originalSize:u||e.fileCount*Vt}}catch(d){return f.debug("Could not load BM25 index for metrics",{error:v(d)}),{bm25Index:null,originalSize:e.fileCount*Vt}}})(),o=0,n=a>0?Math.max(0,(a-o)/a):0;try{await Ut.recordSync(r,{originalSize:a,filteredSize:o,duration:t,isWatch:!1})}catch(d){f.debug("Failed to record sync metrics",{error:v(d)})}try{let{velocityStorage:d}=await import("./velocity-storage-UPW6TLK6.mjs");await d.recompute(r)}catch(d){f.debug("Failed to recompute velocity",{error:v(d)})}let l=await import("./developer-evolution-R5BXQH6G.mjs").then(({captureDeveloperSnapshot:d})=>d(r)).catch(d=>(f.debug("Failed to capture dev snapshot",{error:v(d)}),!1)),c={};try{let d=s;d&&(c.bm25Files=d.totalDocs,c.bm25AvgTokens=Math.round(d.avgDocLength),c.bm25VocabSize=Object.keys(d.invertedIndex).length);let u=Y(r);u&&(c.importEdges=u.edgeCount,c.importFiles=u.fileCount);let h=mt(r);h&&(c.cochangeCommits=h.commitsAnalyzed,c.cochangeFiles=h.filesAnalyzed)}catch(d){f.debug("Could not load index stats",{error:v(d)})}return{duration:t,originalSize:a,filteredSize:o,compressionRate:n,indexes:c,developerSnapshotCaptured:l}}i(zt,"recordSyncMetrics");async function Jt(r,e,t,s,a,o){try{let n=t.recentCommits[0]?.hash||null,l=await R.getAggregatedFeedback(r).catch(()=>{});try{let{refreshSkillIndex:d}=await import("./skill-index-OOVAXHYJ.mjs");await d(r,e)}catch{}let c=await Wt.extract({projectId:r,projectPath:e,languages:s.languages,frameworks:Array.from(new Set([...s.frameworks,...a.frameworks])),feedback:l,context7Verified:o});await Q.saveDraft(r,{projectId:r,languages:s.languages,frameworks:s.frameworks,configFiles:[],fileCount:s.fileCount,patterns:c.patterns,antiPatterns:c.antiPatterns,analyzedAt:b(),status:"draft",commitHash:n??void 0})}catch(n){f.debug("Failed to save draft analysis (non-critical)",{error:v(n)})}}i(Jt,"saveDraftAnalysis");async function Bt(r){try{let[e,t,s,a,o]=await Promise.all([Je.archiveOldShipped(r).catch(()=>0),Be.markDormantIdeas(r).catch(()=>0),qe.removeStaleCompleted(r).catch(()=>0),R.archiveStalePausedTasks(r).catch(()=>[]),Ye.capEntries(r).catch(()=>0)]),n=e+t+s+a.length+o;if(n>0){f.info("Archived stale data",{shipped:e,dormant:t,staleQueue:s,stalePaused:a.length,memoryCapped:o,total:n});let l=Ve.getStats(r);f.debug("Archive stats",l)}}catch(e){f.debug("Archival failed (non-critical)",{error:v(e)})}}i(Bt,"archiveStaleData");var as=6e4,be=class extends Error{static{i(this,"SyncPhaseTimeoutError")}phase;timeoutMs;constructor(e,t){super(`sync phase '${e}' timed out after ${t}ms. Set PRJCT_SYNC_PHASE_TIMEOUT_MS to tune this guard, or run \`prjct sync --full --md\` if incremental state looks stale.`),this.name="SyncPhaseTimeoutError",this.phase=e,this.timeoutMs=t}};function os(){return Number(process.env.PRJCT_SYNC_PHASE_TIMEOUT_MS)||as}i(os,"syncPhaseTimeoutMs");function qt(r,e){let t=os(),s=(()=>{let a=Promise.withResolvers(),o=setTimeout(()=>a.reject(new be(e,t)),t);return{promise:a.promise,cancel:i(()=>clearTimeout(o),"cancel")}})();return Promise.race([r,s.promise]).finally(s.cancel)}i(qt,"withPhaseTimeout");async function k(r,e){let t=Date.now();f.debug("sync phase start",{phase:r});try{let s=await e();return f.debug("sync phase done",{phase:r,ms:Date.now()-t}),s}catch(s){throw f.debug("sync phase failed",{phase:r,ms:Date.now()-t,error:w(s)}),s}}i(k,"runSyncPhase");function Kt(r,e={}){let t=e.now??Date.now,s=t(),o=(()=>{try{return r().then(()=>({}),n=>({error:n}))}catch(n){return Promise.resolve({error:n})}})().then(n=>{try{e.onComplete?.({totalMs:t()-s,...n})}catch{}});return{async settle(){await o}}}i(Kt,"startPostIndexWork");K();import is from"node:fs/promises";import cs from"node:path";N();re();N();B();import Pe from"node:fs/promises";import Z from"node:path";var Ce=".prjct/.prjct-state.md",xe=class{static{i(this,"LocalStateGenerator")}async generate(e,t){let s=Z.join(e,Ce);await Pe.mkdir(Z.dirname(s),{recursive:!0});let a=this.toMarkdown(t);await Pe.writeFile(s,a,"utf-8")}async remove(e){try{await Pe.unlink(Z.join(e,Ce))}catch(t){if(!M(t))throw t}}async exists(e){let t=Z.join(e,Ce);return L(t)}toMarkdown(e){let t=["<!-- Auto-generated by prjct - DO NOT EDIT -->","<!-- This file provides local state persistence for AI tools -->","","# prjct State",""];if(e.currentTask){let s=e.currentTask;if(t.push("## Current Work Cycle"),t.push(""),t.push(`**${s.description}**`),t.push(""),t.push(`- Started: ${s.startedAt}`),s.linearId&&t.push(`- Linear: ${s.linearId}`),s.branch&&t.push(`- Branch: ${s.branch}`),t.push(`- Status: ${s.status||"active"}`),t.push(""),s.subtasks&&s.subtasks.length>0){t.push("### Subtasks"),t.push(""),s.subtasks.forEach((l,c)=>{let d=l.status==="completed"?"\u2705":l.status==="in_progress"?"\u25B6\uFE0F":"\u23F3",u=c===s.currentSubtaskIndex?" \u2190 **Active**":"";t.push(`${c+1}. ${d} ${l.description}${u}`)}),t.push("");let a=s.subtasks.filter(l=>l.status==="completed").length,o=s.subtasks.length,n=Math.round(a/o*100);t.push(`**Progress**: ${a}/${o} (${n}%)`),t.push("")}}else t.push("*No active work cycle*"),t.push(""),t.push('Start work with `p. work "intent"`'),t.push("");if(e.previousTask){let s=e.previousTask;t.push("---"),t.push(""),t.push("## Previous Work Cycle"),t.push(""),t.push(`**${s.description}**`),t.push(""),t.push(`- Status: ${s.status}`),s.prUrl&&t.push(`- PR: ${s.prUrl}`),t.push("")}return t.push("---"),t.push(`*Last updated: ${e.lastUpdated||new Date().toISOString()}*`),t.push(""),t.join(`
|
|
37
|
-
`)}},Yt=new xe;var ls=["storage","context","memory","analysis","config","sync"];async function Qt(r){try{await Promise.all(ls.map(e=>is.mkdir(cs.join(r,e),{recursive:!0})))}catch(e){throw new Error(Me(e,r,"project directories"))}}i(Qt,"ensureProjectDirectories");async function Xt(r){let{projectId:e,projectPath:t,cliVersion:s,git:a,stats:o}=r,n=P.getDoc(e,"project")||{},l={...n,projectId:e,repoPath:t,name:o.name,version:o.version,cliVersion:s,techStack:o.frameworks,fileCount:o.fileCount,commitCount:a.commits,stack:o.ecosystem,currentBranch:a.branch,hasUncommittedChanges:a.hasChanges,createdAt:n.createdAt||b(),lastSync:b(),lastSyncCommit:a.recentCommits[0]?.hash||null,lastSyncBranch:a.branch};P.setDoc(e,"project",l)}i(Xt,"updateProjectDoc");async function Zt(r){let{projectId:e,projectPath:t,stats:s,stack:a}=r,n={...await R.read(e)};n.projectId=e,n.stack={language:s.languages[0]||"Unknown",framework:s.frameworks[0]||null},n.domains={hasFrontend:a.hasFrontend,hasBackend:a.hasBackend,hasDatabase:a.hasDatabase,hasTesting:a.hasTesting,hasDocker:a.hasDocker},n.projectType=s.projectType,n.metrics={totalFiles:s.fileCount},n.lastSync=b(),n.lastUpdated=b(),n.context={...n.context||{},lastSession:b(),lastAction:"Synced project",nextAction:'Run `p. work "intent"` to start a work cycle'},await R.write(e,n);try{await Yt.remove(t)}catch(l){f.debug("Legacy local state cleanup failed (optional)",{error:v(l)})}}i(Zt,"updateStateDoc");function er(r,e,t){P.appendEvent(r,"sync",{branch:e.branch,uncommitted:e.hasChanges,fileCount:t.fileCount,commitCount:e.commits})}i(er,"logSyncEvent");import tr from"node:fs/promises";import De from"node:path";N();kr();var rr={async jsonFilesValid(r){let e=Date.now(),t=[],s=De.basename(r);try{await R.read(s)}catch(a){M(a)||t.push(`state: ${v(a)}`)}return{name:"State data valid",passed:t.length===0,output:t.length===0?"1 store validated":void 0,error:t.length>0?t.join("; "):void 0,durationMs:Date.now()-e}},async noSensitiveData(r){let e=Date.now(),t=De.join(r,"context"),s=[/(?:api[_-]?key|apikey)\s*[:=]\s*['"][^'"]{10,}/i,/(?:password|passwd|pwd)\s*[:=]\s*['"][^'"]{4,}/i,/(?:secret|token)\s*[:=]\s*['"][^'"]{10,}/i],a=[];try{let o=await tr.readdir(t);for(let n of o){if(!n.endsWith(".md"))continue;let l=await tr.readFile(De.join(t,n),"utf-8");for(let c of s)if(c.test(l)){a.push(`${n}: potential sensitive data detected`);break}}}catch(o){if(!M(o))return{name:"No sensitive data",passed:!1,error:`Could not scan: ${v(o)}`,durationMs:Date.now()-e}}return{name:"No sensitive data",passed:a.length===0,output:a.length===0?"No sensitive patterns found":void 0,error:a.length>0?a.join("; "):void 0,durationMs:Date.now()-e}}},Ae=class{static{i(this,"SyncVerifier")}async verify(e,t,s){let a=Date.now(),o=[],n=s?.failFast??!1,l=[],c=[rr.jsonFilesValid(t),rr.noSensitiveData(t)];for(let y of c){let C=await y;if(o.push(C),!C.passed&&n){l.push(...s?.checks?.filter(_=>_.enabled!==!1).map(_=>_.name)??[]);break}}if((!n||o.every(y=>y.passed))&&s?.checks)for(let y of s.checks){if(y.enabled===!1){l.push(y.name);continue}let C=await this.runCustomCheck(y,e);if(o.push(C),!C.passed&&n){let _=s.checks.slice(s.checks.indexOf(y)+1);l.push(..._.filter(W=>W.enabled!==!1).map(W=>W.name));break}}let u=o.filter(y=>!y.passed).length,h=o.filter(y=>y.passed).length;return{passed:u===0,checks:o,totalMs:Date.now()-a,failedCount:u,passedCount:h,skippedCount:l.length}}async runCustomCheck(e,t){let s=Date.now(),a=e.command||(e.script?`sh ${e.script}`:null);if(!a)return{name:e.name,passed:!1,error:"No command or script specified",durationMs:Date.now()-s};try{let{stdout:o,stderr:n}=await _e(a,{cwd:t,timeout:3e4});return{name:e.name,passed:!0,output:(o.trim()||n.trim()).slice(0,200)||void 0,durationMs:Date.now()-s}}catch(o){let n=o;return{name:e.name,passed:!1,error:(n.stderr?.trim()||n.message).slice(0,200),durationMs:Date.now()-s}}}},sr=new Ae;var je=class{static{i(this,"SyncService")}projectPath;projectId=null;globalPath="";cliVersion="0.0.0";constructor(){this.projectPath=process.cwd()}async sync(e=process.cwd(),t={}){this.projectPath=e;let s=Date.now(),a={installed:!1,verified:!1,configPath:"",message:""},o=[];try{if(this.projectId=await T.getProjectId(e),!this.projectId)return{success:!1,projectId:"",cliVersion:"",git:pe(),stats:fe(),commands:ge(),stack:he(),context7:{installed:!1,verified:!1},error:"No prjct project. Run p. init first."};if(this.globalPath=q.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await ds.rm(ee.join(this.globalPath,"agents"),{recursive:!0,force:!0}).catch(()=>{}),(await Le()).installed){let m=await ft({autoRepair:!0});m.verified||f.warn(`Codex p. router not ready: ${m.message||"verification failed"}`)}await k("mcp-defaults",()=>ut({silent:!0,verifyContext7:!1}));let c=(await He().catch(()=>null))?.name??"claude";try{Object.assign(a,await k("context7",()=>dt.ensureReady(c)))}catch(m){let g=w(m);f.warn(`Context7 MCP not ready (continuing sync): ${g}`),Object.assign(a,{verified:!1,message:g})}await Qt(this.globalPath),process.env.PRJCT_SKIP_CREW_SWEEP!=="1"&&await k("legacy-crew-sweep",async()=>{try{let{legacyCrewSweep:m}=await import("./legacy-crew-sweep-2MLYPNQR.mjs"),g=await m(this.projectPath,this.projectId);(g.checkpointsMigrated||g.teamMigrated||g.checkpointsHandEditWarned||g.teamHandEditWarned||g.ghostDirsPurged.length>0||g.agentFilesRepaired.length>0||g.clientPrjctJunkPurged.length>0||g.errors.length>0)&&f.info("Legacy crew sweep ran",{checkpointsMigrated:g.checkpointsMigrated,teamMigrated:g.teamMigrated,checkpointsHandEditWarned:g.checkpointsHandEditWarned,teamHandEditWarned:g.teamHandEditWarned,ghostDirsPurged:g.ghostDirsPurged,agentFilesRepaired:g.agentFilesRepaired,ghostFilesIngested:g.ghostFilesIngested,clientPrjctJunkPurged:g.clientPrjctJunkPurged,errors:g.errors.length})}catch(m){f.debug("Legacy crew sweep failed (non-critical)",{error:w(m)})}});let[u,h,y,C]=await k("gather",()=>qt(Promise.all([kt(this.projectPath),vt(this.projectPath),bt(this.projectPath),Pt(this.projectPath)]),"gather")),{shouldRebuildIndexes:_,changedDomains:W,incrementalInfo:Re,changedSourceFiles:V,deletedSourceFiles:z}=await k("incremental",()=>Ht({projectId:this.projectId,projectPath:this.projectPath,isFullSync:t.full===!0,changedFilesHint:t.changedFiles}));try{let{refreshFileInventory:m}=await import("./project-file-inventory-ZAPKPKY6.mjs");await m(this.projectId,this.projectPath)}catch{}try{await Et(this.projectId)}catch{}_&&await k("index",async()=>{try{let m=Re?.isIncremental&&(V.length>0||z.length>0);await Promise.all([m?Ze(this.projectPath,this.projectId,V,z):Xe(this.projectPath,this.projectId),m?rt(this.projectPath,this.projectId,V,z):tt(this.projectPath,this.projectId),m?nt(this.projectPath,this.projectId,V,z):st(this.projectPath,this.projectId),pt(this.projectPath,this.projectId)]);let g=this.projectId,S=this.projectPath,H=await T.readConfig(S).catch(()=>null),E=Rt(H);o.push(Kt(()=>Ft(g,{uploadToCloud:E}),{onComplete:i(({totalMs:x,error:J})=>{f.debug("sync post-index work settled",{projectId:g,uploadToCloud:E,totalMs:x,...J===void 0?{}:{error:w(J)}})},"onComplete")}))}catch(m){f.debug("File ranking index build failed (non-critical)",{error:w(m)})}});let or=Date.now();f.debug("sync phase start",{phase:"skills"});let ir=await Mt.generateAndInstall().catch(m=>{f.debug("Native skill generation failed (non-critical)",{error:w(m)})});f.debug("sync phase done",{phase:"skills",ms:Date.now()-or}),await k("update-files",()=>Promise.all([Xt({projectId:this.projectId,projectPath:this.projectPath,cliVersion:this.cliVersion,git:u,stats:h}),Zt({projectId:this.projectId,projectPath:this.projectPath,stats:h,stack:C}),Promise.resolve(er(this.projectId,u,h)),Jt(this.projectId,this.projectPath,u,h,C,a.verified)]));let te=await Q.getActive(this.projectId),cr={patterns:te?.patterns?.length||0,antiPatterns:te?.antiPatterns?.length||0,criticalAntiPatterns:te?.antiPatterns?.filter(m=>m.severity==="high").length||0},lr=Date.now()-s,Fe=await k("metrics",()=>zt(this.projectId,h,lr)),dr=Fe.developerSnapshotCaptured===!0,ur=await(async()=>{try{let{recomputeProjectStyle:m,formatProjectStyleForSync:g}=await import("./project-style-evolution-T27I5N65.mjs"),S=await k("project-style",()=>m({projectId:this.projectId,projectPath:this.projectPath,stats:h,stack:C,commands:y,commitHash:u.recentCommits[0]?.hash??null,source:"sync-mechanical"})),H=g(S),E=S.snapshot.payload.metrics.styleCoverage;return{summary:S.snapshot.summary,evolutionMd:H.evolutionMd,patternCount:S.snapshot.patternCount,antiPatternCount:S.snapshot.antiPatternCount,conventionCount:S.snapshot.conventionCount,styleCoverage:typeof E=="number"?E:Number(E)||0,isFirst:S.isFirst,hasChanges:S.delta.hasChanges}}catch(m){f.debug("Project style recompute failed (non-critical)",{error:w(m)});return}})(),mr=await k("work-cost",()=>Ct(this.projectId));await k("archive",()=>Bt(this.projectId));let pr=await k("context-quality",()=>et(this.projectPath,this.projectId)),fr=await k("retention",async()=>{try{let m=await T.readConfig(this.projectPath).catch(()=>null),g=m?.retention?.mode??"apply";if(g==="off")return;let S=g==="dry-run",{applyRetention:H,triageInbox:E}=await import("./retention-E7WGFL47.mjs"),x=H(this.projectId,{dryRun:S,maxArchive:m?.retention?.maxArchive,maxDelete:m?.retention?.maxDelete}),{inboxMerged:J,inboxArchived:hr}=S?{inboxMerged:0,inboxArchived:0}:(()=>{let j=E(this.projectId);return{inboxMerged:j.merged,inboxArchived:j.archived}})(),{runVaultPurge:yr,vaultHealth:Sr}=await import("./purge-QQ6XILZD.mjs"),O=await yr(this.projectId,{projectPath:this.projectPath,dryRun:S,softDeletedPurgeDays:m?.retention?.softDeletedPurgeDays,archivePruneDays:m?.retention?.archivePruneDays,autoSourceMaxLive:m?.retention?.autoSourceMaxLive}),wr=Sr(this.projectId);return{evaluated:x.evaluated,active:x.active,archive:x.wouldArchive,delete:x.wouldDelete,archived:x.archived,deleted:x.deleted,inboxMerged:J,inboxArchived:hr,dryRun:S,samples:x.samples.map(j=>({id:j.id,type:j.type,verdict:j.verdict,score:j.score,reasons:j.reasons,excess:j.excess})),referenceSize:x.referenceSize,vault:{...wr,softDeletedPurged:O.softDeletedPurged,orphanEventsPurged:O.orphanEventsPurged,archivesPruned:O.archivesPruned,autoSourceTrimmed:O.autoSourceTrimmed,distilledDiscarded:O.distilledDiscarded,digestsWritten:O.digestsWritten}}}catch(m){f.debug("retention phase failed",{error:w(m)});return}});await k("install-global",async()=>{await se.installGlobalConfig(),await se.syncCommands()}),await k("install-agent-surfaces",async()=>{let{detectInstalledAgents:m}=await import("./detection-MEYHME4X.mjs"),g=await m(this.projectPath).catch(()=>[]);await it(this.projectPath,{refreshIfAdopted:!0,agents:g})});let gr=await k("verify",async()=>{try{let m=await T.readConfig(this.projectPath);return await sr.verify(this.projectPath,this.globalPath,m?.verification)}catch(m){f.debug("Verification failed (non-critical)",{error:w(m)});return}});if(process.env.PRJCT_WORLD_MODEL_REFRESH==="1"||process.env.PRJCT_DRIFT_REFRESH==="1")try{let m=await import("node:os"),{markDriftRefreshApplied:g}=await import("./drift-refresh-TD3PYPJN.mjs"),S=process.env.PRJCT_CLI_HOME?ee.resolve(process.env.PRJCT_CLI_HOME):ee.join(m.homedir(),".prjct-cli");g(S)}catch{}return await Promise.all(o.map(m=>m.settle())),{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:u,stats:h,commands:y,stack:C,context7:{installed:a.installed,verified:a.verified,message:a.message},analysisSummary:cr,contextQuality:pr,retentionDryRun:fr,syncMetrics:Fe,workCost:mr,verification:gr,incremental:Re,projectStyle:ur,developerSnapshotCaptured:dr,generatedSkills:ir}}catch(n){return{success:!1,projectId:this.projectId||"",cliVersion:this.cliVersion,git:pe(),stats:fe(),commands:ge(),stack:he(),context7:{installed:a.installed,verified:a.verified,message:a.message},error:w(n)}}}async getCliVersion(){try{let e=ee.join(__dirname,"..","..","package.json");return(await Oe(e))?.version||"0.0.0"}catch(e){return f.debug("Failed to read CLI version",{error:w(e)}),"0.0.0"}}},Ka=new je;import Ie from"chalk";var nr={task:"Start new work cycle",done:"Complete current work",pause:"Pause and switch context",resume:"Continue paused task",ship:"Ship the feature",reopen:"Reopen for rework",next:"View task queue",sync:"Analyze project",bug:"Report a bug",idea:"Capture an idea"},us={task:"work"};function Ee(r){return us[r]??r}i(Ee,"publicCommand");var ar={task:"working",done:"completed","done-subtask":"working",pause:"paused",resume:"working",ship:"shipped",reopen:"working",next:"idle",sync:"idle",init:"idle",bug:"working",idea:"idle"};function eo(r,e={}){if(e.quiet)return;let t=ar[r]||"idle",s=ae.getValidCommands(t);if(s.length===0)return;let a=s.map(o=>({cmd:`p. ${Ee(o)}`,desc:nr[o]||o}));console.log(Ie.dim(`
|
|
38
|
-
Next:`));for(let o of a){let n=Ie.cyan(o.cmd.padEnd(12));console.log(Ie.dim(` ${n} \u2192 ${o.desc}`))}}i(eo,"showNextSteps");function to(r,e=!1){let t=ar[r]||"idle";return ae.getValidCommands(t).map(a=>({cmd:e?`prjct ${Ee(a)} --md`:`p. ${Ee(a)}`,desc:nr[a]||a}))}i(to,"getNextSteps");async function ms(r,e={}){let t=await T.getProjectId(r);return t?{ok:!0,value:t}:(e.md?console.log("> No project ID found. Run `prjct init` first."):Ke.failWithHint("NO_PROJECT_ID"),{ok:!1,result:{success:!1,error:"No project ID found"}})}i(ms,"requireProjectId");async function fo(r,e={}){let t=await xt.ensureInit(r);return t.success?ms(r,e):{ok:!1,result:t}}i(fo,"requireProject");export{ps as a,fs as b,Q as c,yn as d,Ut as e,Ka as f,eo as g,to as h,fo as i};
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __createRequire } from 'module';
|
|
3
|
-
import { fileURLToPath as __fileURLToPath } from 'url';
|
|
4
|
-
import { dirname as __pathDirname } from 'path';
|
|
5
|
-
const require = __createRequire(import.meta.url);
|
|
6
|
-
const __filename = __fileURLToPath(import.meta.url);
|
|
7
|
-
const __dirname = __pathDirname(__filename);
|
|
8
|
-
import{b as F}from"./chunk-YJMWY4Y6.mjs";import{e as R,j as b,l as D,n as C}from"./chunk-NJAMZSHM.mjs";import"./chunk-HDHVBB6Q.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-AKIN5WSQ.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-SVZHJZ5T.mjs";import{n as k,o as A}from"./chunk-CTWZQ7YI.mjs";import"./chunk-BUDZL4DW.mjs";import{a as o}from"./chunk-E66B27AL.mjs";A();async function f(e,n){return k(e,n)}o(f,"safeGit");async function x(e){let n=await f(e,["diff","--name-only","HEAD"])??"",t=await f(e,["diff","--name-only","--cached"])??"",i=await f(e,["ls-files","--others","--exclude-standard"])??"",a=new Set;for(let s of[n,t,i])for(let c of s.split(`
|
|
9
|
-
`))c.trim()&&a.add(c.trim());return[...a]}o(x,"listWorkingTreeFiles");async function v(e){let n=await H(e);if(!n)return[];let t=await f(e,["merge-base",n,"HEAD"]);return t?(await f(e,["diff","--name-only",`${t}..HEAD`])??"").split(`
|
|
10
|
-
`).filter(Boolean):[]}o(v,"listCommittedFiles");async function H(e){let n=await f(e,["rev-parse","--abbrev-ref","origin/HEAD"]);return n&&n!=="origin/HEAD"?n:(await Promise.all(["main","master"].map(async i=>({candidate:i,exists:await f(e,["rev-parse","--verify","--quiet",i])!==null})))).find(({exists:i})=>i)?.candidate??""}o(H,"resolveDefaultRef");async function E(e,n){if(n==="working-tree"||n==="explicit")return"HEAD";let t=await H(e);return t?await f(e,["merge-base",t,"HEAD"])??"HEAD":"HEAD"}o(E,"resolveDiffBase");function _(e){let n=new Map,t={currentFile:null,newLine:0};for(let i of e.split(`
|
|
11
|
-
`)){if(i.startsWith("+++ ")){let s=i.slice(4).trim();if(s==="/dev/null"){t.currentFile=null;continue}t.currentFile=s.replace(/^b\//,""),n.has(t.currentFile)||n.set(t.currentFile,new Set);continue}if(!t.currentFile)continue;let a=i.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);if(a){t.newLine=Number.parseInt(a[1],10);continue}i.startsWith("\\")||(i.startsWith("+")&&!i.startsWith("+++")?(n.get(t.currentFile)?.add(t.newLine),t.newLine++):i.startsWith("-")&&!i.startsWith("---")||(i.startsWith(" ")||i==="")&&t.newLine++)}return n}o(_,"parseChangedLinesFromUnifiedDiff");async function L(e,n,t){if(t.length===0)return new Map;let i=await E(e,n);if(!i)return new Map;let a=n==="committed"?["diff","-U0",`${i}..HEAD`,"--",...t]:["diff","-U0","HEAD","--",...t],s=await f(e,a)??"",c=n!=="committed"?await f(e,["diff","-U0","--cached","--",...t])??"":"";return _(`${s}
|
|
12
|
-
${c}`)}o(L,"loadHunkLines");function M(e,n,t){let i=b(e,n);if(i.length===0)return[];if(!t||t.size===0)return i.slice(0,12).map(c=>c.name);let a=[...t].sort((c,l)=>c-l),s=new Set;for(let c of a){let l=i.reduce((m,g)=>g.startLine<=c?g:m,i[0]);s.add(l.name);for(let m of i)t.has(m.startLine)&&s.add(m.name)}return[...s].slice(0,12)}o(M,"symbolsTouchedByHunks");var W=/(?:^|\/)(?:auth|security|crypto|billing|payment|migrate|schema|migrations?)(?:\/|$)/i,T=/(?:^|\/)(?:storage|database|db|sync|daemon|mcp|hooks?|session)(?:\/|$)/i;function U(e,n,t,i,a){let s=[],c=W.test(e)?"critical":T.test(e)?"high":"low";c==="critical"?s.push("touches auth/security/billing/schema path"):c==="high"&&s.push("touches storage/sync/hooks/mcp path");let l=n>=15?"critical":n>=5?"high":n>0?"medium":"low";n>=15?s.push(`high call fan-in (${n} callers)`):n>=5?s.push(`moderate call fan-in (${n} callers)`):n>0&&s.push(`${n} caller(s) via symbol graph`);let m=t>=10?"high":t>=3?"medium":"low";t>=10?s.push(`${t} importers`):t>=3&&s.push(`${t} importers`),a>0&&s.push(`${a} symbol(s) in changed hunks`),!i&&t===0&&n===0&&s.push("leaf change (no graph neighbors)");let g={low:0,medium:1,high:2,critical:3},u=[c,l,m].reduce((d,p)=>g[p]>g[d]?p:d);return s.length===0&&s.push("isolated or low connectivity"),{risk:u,reasons:s}}o(U,"classifyRisk");async function N(e,n,t={}){let i=await(async()=>{if(t.files&&t.files.length>0)return{changedFiles:t.files,source:"explicit"};let r=t.source??"auto";if(r==="working-tree"||r==="auto"){let h=await x(e);if(h.length>0||r==="working-tree")return{changedFiles:h,source:"working-tree"}}return r==="committed"||r==="auto"?{changedFiles:await v(e),source:"committed"}:{changedFiles:[],source:"explicit"}})(),{changedFiles:a,source:s}=i,c=F(n),l=R(n),m=l?await L(e,s,a.slice(0,80)):new Map,g=new Set(a);for(let r of a){let h=c?.reverse[r]??[];for(let y of h)g.add(y)}if(l)for(let r of C(n,a,2))g.add(r);let u=[],d={critical:0,high:0,medium:0,low:0};for(let r of a){let h=c?.reverse[r]??[],y=l?D(n,r):0,w=l?M(n,r,m.get(r)):[],{risk:$,reasons:S}=U(r,y,h.length,w.length>0||l&&b(n,r).length>0,w.length);d[$]++,u.push({file:r,risk:$,touchedSymbols:w,fanIn:y,reasons:S})}let p={critical:0,high:1,medium:2,low:3};return u.sort((r,h)=>p[r.risk]-p[h.risk]||r.file.localeCompare(h.file)),{changedFiles:a,affectedFiles:[...g].sort(),changes:u,summary:d,source:s}}o(N,"detectChanges");function q(e){if(e.changedFiles.length===0)return`## Detect changes
|
|
13
|
-
|
|
14
|
-
_No changes detected (clean tree / no base range)._
|
|
15
|
-
`;let n=["## Detect changes","",`- **Source**: ${e.source}`,`- **Changed**: ${e.changedFiles.length} file(s)`,`- **Blast radius**: ${e.affectedFiles.length} file(s) (imports + call-graph)`,`- **Risk**: critical ${e.summary.critical} \xB7 high ${e.summary.high} \xB7 medium ${e.summary.medium} \xB7 low ${e.summary.low}`,"","### Per-file risk",""];for(let t of e.changes){let i=t.touchedSymbols.length>0?` \xB7 symbols: ${t.touchedSymbols.slice(0,6).join(", ")}`:"";n.push(`- **${t.risk.toUpperCase()}** \`${t.file}\`${i}`,` - ${t.reasons.join("; ")}`)}if(e.affectedFiles.length>e.changedFiles.length){n.push("","### Affected beyond diff","");let t=e.affectedFiles.filter(i=>!e.changedFiles.includes(i)).slice(0,25);for(let i of t)n.push(`- \`${i}\``);e.affectedFiles.length-e.changedFiles.length>25&&n.push(`- _\u2026+${e.affectedFiles.length-e.changedFiles.length-25} more_`)}return n.push("","_Advisory. Expand with `prjct code trace <symbol>` or MCP `prjct_trace_path`._"),n.join(`
|
|
16
|
-
`)}o(q,"formatDetectChangesMd");function z(e){if(e.changedFiles.length===0)return"detect-changes: no changes detected";let n=[`Detect changes (${e.source}): ${e.changedFiles.length} changed \u2192 blast ${e.affectedFiles.length}`,`Risk: critical=${e.summary.critical} high=${e.summary.high} medium=${e.summary.medium} low=${e.summary.low}`];for(let t of e.changes.slice(0,30)){let i=t.touchedSymbols.length?` [${t.touchedSymbols.slice(0,4).join(",")}]`:"";n.push(` [${t.risk.toUpperCase()}] ${t.file}${i} \u2014 ${t.reasons[0]??""}`)}return n.join(`
|
|
17
|
-
`)}o(z,"formatDetectChangesText");function J(e){return e.changedFiles.length===0?null:e.summary.critical>0?`\u26A0\uFE0F Structural risk CRITICAL (${e.summary.critical} file(s), blast ${e.affectedFiles.length}). Review: \`prjct code impact --md\`.`:e.summary.high>0?`\u26A0\uFE0F Structural risk HIGH (${e.summary.high} file(s), blast ${e.affectedFiles.length}). Consider \`prjct code impact --md\`.`:null}o(J,"shipStructuralRiskCue");export{N as detectChanges,q as formatDetectChangesMd,z as formatDetectChangesText,_ as parseChangedLinesFromUnifiedDiff,J as shipStructuralRiskCue,M as symbolsTouchedByHunks};
|