@better-vibe/branch-narrator 1.2.1 → 1.5.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/README.md +1 -2
- package/dist/analyzers/angular-components.d.ts +7 -0
- package/dist/analyzers/angular-components.d.ts.map +1 -0
- package/dist/analyzers/angular-routes.d.ts +40 -0
- package/dist/analyzers/angular-routes.d.ts.map +1 -0
- package/dist/analyzers/index.d.ts +3 -0
- package/dist/analyzers/index.d.ts.map +1 -1
- package/dist/analyzers/vite-config.d.ts +13 -0
- package/dist/analyzers/vite-config.d.ts.map +1 -0
- package/dist/analyzers/vitest.d.ts.map +1 -1
- package/dist/cli.js +332 -240
- package/dist/commands/facts/highlights.d.ts.map +1 -1
- package/dist/commands/integrate/shared.d.ts +1 -1
- package/dist/commands/integrate/shared.d.ts.map +1 -1
- package/dist/commands/snap/index.d.ts +1 -1
- package/dist/core/ids.d.ts.map +1 -1
- package/dist/core/types.d.ts +39 -2
- package/dist/core/types.d.ts.map +1 -1
- package/dist/git/collector.d.ts +1 -2
- package/dist/git/collector.d.ts.map +1 -1
- package/dist/index.js +177 -146
- package/dist/profiles/angular.d.ts +9 -0
- package/dist/profiles/angular.d.ts.map +1 -0
- package/dist/profiles/index.d.ts +19 -1
- package/dist/profiles/index.d.ts.map +1 -1
- package/dist/profiles/vite.d.ts +21 -0
- package/dist/profiles/vite.d.ts.map +1 -0
- package/dist/render/markdown.d.ts.map +1 -1
- package/dist/render/terminal.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,58 +1,62 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
3
|
-
Please run this command from within a git repository.`,1);this.name="NotAGitRepoError"}};
|
|
4
|
-
Please ensure the branch or commit exists.`,1);this.name="InvalidRefError"}};
|
|
5
|
-
The branches may be identical or one may not exist.`,1);this.name="NoDiffError"}};
|
|
6
|
-
${Z}`,1);this.stderr=Z;this.name="GitCommandError"}}});import{readFile as
|
|
7
|
-
`).filter(Boolean),
|
|
8
|
-
`).filter(Boolean)}catch{return[]}}async function
|
|
9
|
-
`),q=W.map((V,U)=>({type:"add",content:"+"+V,ln:U+1}));
|
|
10
|
-
`),diffs:
|
|
11
|
-
${
|
|
12
|
-
|
|
13
|
-
`),Q
|
|
14
|
-
`);
|
|
15
|
-
`);for(let Y of K){if(Y.startsWith("@@"))continue;if(Y.startsWith("+")&&!Y.startsWith("+++"))Z.push({line:Y.slice(1),lineNumber:X}),X++;else if(!Y.startsWith("-"))X++}}return Z}function G1($){return $.hunks.flatMap((Z)=>Z.deletions)}function xK($){let Z=[];for(let Q of $.hunks)Z.push(...Q.additions,...Q.deletions);return Z}function wK($){return $.map((Z)=>[...Z.additions,...Z.deletions].join(`
|
|
2
|
+
import{createRequire as FZ}from"node:module";var PZ=Object.create;var{getPrototypeOf:CZ,defineProperty:m0,getOwnPropertyNames:SZ}=Object;var kZ=Object.prototype.hasOwnProperty;var b1=($,Z,X)=>{X=$!=null?PZ(CZ($)):{};let Q=Z||!$||!$.__esModule?m0(X,"default",{value:$,enumerable:!0}):X;for(let Y of SZ($))if(!kZ.call(Q,Y))m0(Q,Y,{get:()=>$[Y],enumerable:!0});return Q};var P1=($,Z)=>{for(var X in Z)m0($,X,{get:Z[X],enumerable:!0,configurable:!0,set:(Q)=>Z[X]=()=>Q})};var T=($,Z)=>()=>($&&(Z=$($=0)),Z);var C1=FZ(import.meta.url);var y,V$,T1,vZ,W1;var x1=T(()=>{y=class y extends Error{exitCode;constructor($,Z=1){super($);this.exitCode=Z;this.name="BranchNarratorError"}};V$=class V$ extends y{constructor($=process.cwd()){super(`Not a git repository: ${$}
|
|
3
|
+
Please run this command from within a git repository.`,1);this.name="NotAGitRepoError"}};T1=class T1 extends y{constructor($){super(`Invalid git reference: ${$}
|
|
4
|
+
Please ensure the branch or commit exists.`,1);this.name="InvalidRefError"}};vZ=class vZ extends y{constructor($,Z){super(`No differences found between ${$} and ${Z}.
|
|
5
|
+
The branches may be identical or one may not exist.`,1);this.name="NoDiffError"}};W1=class W1 extends y{stderr;constructor($,Z){super(`Git command failed: ${$}
|
|
6
|
+
${Z}`,1);this.stderr=Z;this.name="GitCommandError"}}});import{readFile as yZ}from"node:fs/promises";import{join as h0,dirname as mZ}from"node:path";import{fileURLToPath as hZ}from"node:url";async function gZ($){try{let Z=await yZ($,"utf-8");return JSON.parse(Z).version||null}catch{return null}}async function a$(){if(r$)return r$;let $=[h0(u0,"..","package.json"),h0(u0,"..","..","package.json"),h0(u0,"package.json")];for(let Z of $){let X=await gZ(Z);if(X)return r$=X,X}return"unknown"}function J5(){return r$??"unknown"}var uZ,u0,r$=null;var s$=T(()=>{uZ=hZ(import.meta.url),u0=mZ(uZ)});async function v1($,Z){return(await Promise.all($.map((Q)=>Q.analyze(Z)))).flat()}function X4($){let Z=$.trim().split(`
|
|
7
|
+
`).filter(Boolean),X=[];for(let Q of Z){let Y=Q.split("\t"),K=Y[0];if(K.startsWith("R"))X.push({path:Y[2],status:"renamed",oldPath:Y[1]});else if(K==="A")X.push({path:Y[1],status:"added"});else if(K==="M")X.push({path:Y[1],status:"modified"});else if(K==="D")X.push({path:Y[1],status:"deleted"})}return X}function Q4($,Z){let X=new Map,Q=new Map;for(let Y of Z)if(X.set(Y.path,Y.status),Y.oldPath)Q.set(Y.path,Y.oldPath),X.set(Y.oldPath,Y.status);return $.map((Y)=>{let W=(Y.to==="/dev/null"?Y.from:Y.to).replace(/^[ab]\//,""),q=X.get(W)??"modified",V=(Y.chunks||[]).map((U)=>{let J=[],B=[];for(let G of U.changes||[])if(G.type==="add")J.push(G.content.slice(1));else if(G.type==="del")B.push(G.content.slice(1));return{oldStart:U.oldStart,oldLines:U.oldLines,newStart:U.newStart,newLines:U.newLines,content:U.content,additions:J,deletions:B}});return{path:W,status:q,oldPath:Q.get(W),hunks:V}})}function i0($){let Z=X4($.nameStatusOutput),X=Q4($.parsedDiffs,Z);return{base:$.base,head:$.head,files:Z,diffs:X,basePackageJson:$.basePackageJson,headPackageJson:$.headPackageJson}}function HK($={}){return{base:"main",head:"HEAD",files:[],diffs:[],...$}}function zK($,Z,X="modified"){return{path:$,status:X,hunks:[{oldStart:1,oldLines:0,newStart:1,newLines:Z.length,content:"@@ -0,0 +1 @@",additions:Z,deletions:[]}]}}var w5={};P1(w5,{refExists:()=>O$,isWorkingDirDirty:()=>_$,isGitRepo:()=>n0,getUntrackedFiles:()=>E5,getUnifiedDiffByMode:()=>R5,getUnifiedDiff:()=>x5,getRepoRoot:()=>M$,getNameStatusByMode:()=>A5,getNameStatus:()=>T5,getFileAtRef:()=>Q$,getDefaultBranch:()=>t0,collectChangeSet:()=>i1});import{execa as k1}from"execa";import N5 from"parse-diff";async function n0($=process.cwd()){try{let Z=await k1("git",["rev-parse","--is-inside-work-tree"],{cwd:$,reject:!1});return Z.exitCode===0&&Z.stdout.trim()==="true"}catch{return!1}}async function t0($=process.cwd()){try{let Z=await k1("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:$,reject:!1});if(Z.exitCode===0){let X=Z.stdout.trim().split("/");if(X.length>0)return X[X.length-1]}}catch{}return"main"}async function O$($,Z=process.cwd()){try{return(await k1("git",["rev-parse","--verify",$],{cwd:Z,reject:!1})).exitCode===0}catch{return!1}}function Y4($){let Z=["diff","--name-status","--find-renames"];switch($.mode){case"branch":Z.push(`${$.base}..${$.head}`);break;case"unstaged":break;case"staged":Z.push("--staged");break;case"all":Z.push("HEAD");break}return Z}function K4($){let Z=["diff","--unified=3"];switch($.mode){case"branch":Z.push(`${$.base}..${$.head}`);break;case"unstaged":break;case"staged":Z.push("--staged");break;case"all":Z.push("HEAD");break}return Z}async function A5($,Z=process.cwd()){let X=Y4($);try{return(await k1("git",X,{cwd:Z})).stdout}catch(Q){if(Q instanceof Error&&"stderr"in Q)throw new W1(`git ${X.join(" ")}`,String(Q.stderr));throw Q}}async function R5($,Z=process.cwd()){let X=K4($);try{return(await k1("git",X,{cwd:Z})).stdout}catch(Q){if(Q instanceof Error&&"stderr"in Q)throw new W1(`git ${X.join(" ")}`,String(Q.stderr));throw Q}}async function T5($,Z,X=process.cwd()){try{let Q=Z?["diff","--name-status","--find-renames",`${$}..${Z}`]:["diff","--name-status","--find-renames",$];return(await k1("git",Q,{cwd:X})).stdout}catch(Q){if(Q instanceof Error&&"stderr"in Q){let Y=Z?`${$}..${Z}`:$;throw new W1(`git diff --name-status ${Y}`,String(Q.stderr))}throw Q}}async function x5($,Z,X=process.cwd()){try{let Q=Z?["diff","--unified=3",`${$}..${Z}`]:["diff","--unified=3",$];return(await k1("git",Q,{cwd:X})).stdout}catch(Q){if(Q instanceof Error&&"stderr"in Q){let Y=Z?`${$}..${Z}`:$;throw new W1(`git diff ${Y}`,String(Q.stderr))}throw Q}}async function Q$($,Z,X=process.cwd()){try{let Q=await k1("git",["show",`${$}:${Z}`],{cwd:X,reject:!1});if(Q.exitCode===0)return Q.stdout;return null}catch{return null}}function G$($){if(!$)return;try{return JSON.parse($)}catch{return}}async function E5($=process.cwd()){try{return(await k1("git",["ls-files","--others","--exclude-standard"],{cwd:$})).stdout.trim().split(`
|
|
8
|
+
`).filter(Boolean)}catch{return[]}}async function q4($,Z){try{let{readFile:X}=await import("node:fs/promises"),{join:Q}=await import("node:path");return await X(Q(Z,$),"utf-8")}catch{return null}}async function W4($,Z){let X=[],Q=[];for(let Y of $){if(V4(Y)){X.push(`A ${Y}`);continue}let K=await q4(Y,Z);if(K===null)continue;X.push(`A ${Y}`);let W=K.split(`
|
|
9
|
+
`),q=W.map((V,U)=>({type:"add",content:"+"+V,ln:U+1}));Q.push({from:"/dev/null",to:Y,chunks:[{content:`@@ -0,0 +1,${W.length} @@`,oldStart:0,oldLines:0,newStart:1,newLines:W.length,changes:q}],deletions:0,additions:W.length})}return{nameStatus:X.join(`
|
|
10
|
+
`),diffs:Q}}function V4($){let Z=$.toLowerCase(),X=Z.lastIndexOf(".");if(X===-1)return!1;let Q=Z.slice(X);return U4.has(Q)}async function Z0($){try{let{readFile:Z}=await import("node:fs/promises"),{join:X}=await import("node:path"),Q=await Z(X($,"package.json"),"utf-8");return JSON.parse(Q)}catch{return}}async function i1($,Z,X=process.cwd()){if(typeof $==="object"&&"mode"in $)return J4($);let Q;if(typeof $==="string")Q={base:$,head:Z,cwd:X};else Q=$,X=Q.cwd??process.cwd();let{base:Y}=Q,K=Q.head;if(!await n0(X))throw new V$(X);if(!await O$(Y,X))throw new T1(Y);if(K&&!await O$(K,X))throw new T1(K);let[W,q,V]=await Promise.all([T5(Y,K,X),x5(Y,K,X),Q$(Y,"package.json",X)]),U=N5(q),J=G$(await Q$(K,"package.json",X));return i0({base:Y,head:Q.head,nameStatusOutput:W,parsedDiffs:U,basePackageJson:G$(V),headPackageJson:J})}async function J4($){let Z=$.cwd??process.cwd(),X=$.includeUntracked??($.mode==="all"||$.mode==="unstaged");if(!await n0(Z))throw new V$(Z);if($.mode==="branch"){if(!$.base)throw new T1("base (required for branch mode)");if(!$.head)throw new T1("head (required for branch mode)");if(!await O$($.base,Z))throw new T1($.base);if(!await O$($.head,Z))throw new T1($.head)}if($.mode==="staged"||$.mode==="all"){if(!await O$("HEAD",Z))throw new T1("HEAD")}let[Q,Y]=await Promise.all([A5($,Z),R5($,Z)]),K=N5(Y),W=Q;if(X&&$.mode!=="branch"){let B=await E5(Z);if(B.length>0){let G=await W4(B,Z);if(G.nameStatus)W=W?`${W}
|
|
11
|
+
${G.nameStatus}`:G.nameStatus;K=[...K,...G.diffs]}}let q,V,U,J;switch($.mode){case"branch":q=$.base,V=$.head,U=G$(await Q$(q,"package.json",Z)),J=G$(await Q$(V,"package.json",Z));break;case"unstaged":q="INDEX",V="WORKING",U=await Z0(Z),J=await Z0(Z);break;case"staged":q="HEAD",V="INDEX",U=G$(await Q$("HEAD","package.json",Z)),J=await Z0(Z);break;case"all":q="HEAD",V="WORKING",U=G$(await Q$("HEAD","package.json",Z)),J=await Z0(Z);break}return i0({base:q,head:V,nameStatusOutput:W,parsedDiffs:K,basePackageJson:U,headPackageJson:J})}async function M$($=process.cwd()){try{return(await k1("git",["rev-parse","--show-toplevel"],{cwd:$})).stdout.trim()}catch{return $}}async function _$($=process.cwd()){try{return(await k1("git",["diff-index","--quiet","HEAD","--"],{cwd:$,reject:!1})).exitCode!==0}catch{return!1}}var U4;var H$=T(()=>{x1();U4=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".svg",".woff",".woff2",".ttf",".eot",".otf",".zip",".tar",".gz",".tgz",".rar",".pdf",".doc",".docx",".xls",".xlsx",".exe",".dll",".so",".dylib",".mp3",".mp4",".wav",".avi",".mov",".lockb"])});function k$($){return B4.some((Z)=>Z.test($))}var I5,B4;var X0=T(()=>{I5=["**/*.d.ts","**/*.map","**/*.min.js","**/*.min.css","**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/.svelte-kit/**","**/.nuxt/**","**/out/**","**/.cache/**","**/.parcel-cache/**","**/vendor/**","**/*.log","**/package-lock.json","**/yarn.lock","**/pnpm-lock.yaml","**/bun.lock","**/*.tgz","**/*.tar.gz","**/*.zip"],B4=[/^dist\//,/^build\//,/^\.next\//,/^\.svelte-kit\//,/^\.nuxt\//,/^out\//,/^node_modules\//,/^vendor\//,/\.map$/,/\.d\.ts$/,/\.min\.(js|css)$/,/^\.cache\//,/^\.parcel-cache\//]});function G4($,Z,X){let Q=[],Y=$.matchAll(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/g);for(let E of Y){let x=E[1];if(Z.includes(`function ${x}`))Q.push({description:`Modified function: ${x}()`,priority:100});else if(X==="modified")Q.push({description:`Added function: ${x}()`,priority:100});else Q.push({description:`Added function: ${x}()`,priority:100})}let K=$.matchAll(/export\s+const\s+(\w+)\s*=\s*(?:async\s*)?\([^)]*\)\s*(?::\s*[^=]+)?\s*=>/g);for(let E of K){let x=E[1];if(Z.includes(`const ${x}`))Q.push({description:`Modified: ${x}()`,priority:95});else Q.push({description:`Added: ${x}()`,priority:95})}let W=$.matchAll(/(?:export\s+)?class\s+(\w+)/g);for(let E of W){let x=E[1];if(Z.includes(`class ${x}`))Q.push({description:`Modified class: ${x}`,priority:90});else Q.push({description:`Added class: ${x}`,priority:90})}let q=$.matchAll(/(?:export\s+)?interface\s+(\w+)/g);for(let E of q){let x=E[1];if(Z.includes(`interface ${x}`))Q.push({description:`Modified interface: ${x}`,priority:80});else Q.push({description:`Added interface: ${x}`,priority:80})}let V=$.matchAll(/(?:export\s+)?type\s+(\w+)\s*=/g);for(let E of V){let x=E[1];if(Z.includes(`type ${x}`))Q.push({description:`Modified type: ${x}`,priority:80});else Q.push({description:`Added type: ${x}`,priority:80})}let U=$.matchAll(/(?:export\s+)?enum\s+(\w+)/g);for(let E of U){let x=E[1];if(Z.includes(`enum ${x}`))Q.push({description:`Modified enum: ${x}`,priority:75});else Q.push({description:`Added enum: ${x}`,priority:75})}let J=$.matchAll(/export\s+const\s+(\w+)\s*(?::\s*[^=]+)?\s*=/g);for(let E of J){let x=E[1];if(new RegExp(`export\\s+const\\s+${x}\\s*=\\s*(?:async\\s*)?\\(`).test($))continue;if(Z.includes(`const ${x}`))Q.push({description:`Modified const: ${x}`,priority:70});else Q.push({description:`Added const: ${x}`,priority:70})}let B=$.match(/export\s+\*\s+from\s+['"]([^'"]+)['"]/);if(B)Q.push({description:`Re-exports from: ${B[1]}`,priority:60});let G=$.match(/export\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(G){let E=G[1].split(",").map((R)=>R.trim().split(" ")[0]).slice(0,3),x=G[1].split(",").length>3?" ...":"";Q.push({description:`Re-exports: ${E.join(", ")}${x}`,priority:60})}let M=$.matchAll(/^\s*(?:async\s+)?(\w+)\s*\([^)]*\)\s*\{/gm);for(let E of M){let x=E[1];if(["if","for","while","switch","catch","function"].includes(x))continue;if(new RegExp(`\\b${x}\\s*\\(`).test(Z))Q.push({description:`Modified method: ${x}()`,priority:65});else if(X==="added")Q.push({description:`Added method: ${x}()`,priority:65})}let _=$.matchAll(/^import\s+(?:\{[^}]+\}|[^{}\s]+)\s+from\s+['"]([^'"]+)['"]/gm),O=[];for(let E of _){let x=E[1];if(!Z.includes(x))O.push(x)}if(O.length>0){let E=O.slice(0,2).map((R)=>R.split("/").pop()||R),x=O.length>2?` (+${O.length-2} more)`:"";Q.push({description:`New imports: ${E.join(", ")}${x}`,priority:40})}let H=$.matchAll(/case\s+['"]?([^'":\s]+)['"]?\s*:/g),z=[];for(let E of H){let x=E[1];if(!Z.includes(`case ${x}`)&&!Z.includes(`case "${x}"`)&&!Z.includes(`case '${x}'`))z.push(x)}if(z.length>0){let E=z.slice(0,2),x=z.length>2?` (+${z.length-2} more)`:"";Q.push({description:`Added cases: ${E.join(", ")}${x}`,priority:50})}let N=$.matchAll(/\.option\s*\(\s*['"]([^'"]+)['"]/g),j=[];for(let E of N){let x=E[1];if(!Z.includes(x))j.push(x)}if(j.length>0){let E=j.slice(0,2),x=j.length>2?` (+${j.length-2} more)`:"";Q.push({description:`Added CLI options: ${E.join(", ")}${x}`,priority:85})}if(/<[A-Z]\w+/.test($)&&($.includes("return")||$.includes("=>")))Q.push({description:"Component JSX updated",priority:30});return Q}function O4($){let Z=$.hunks.flatMap((V)=>V.additions).join(`
|
|
12
|
+
`),X=$.hunks.flatMap((V)=>V.deletions).join(`
|
|
13
|
+
`);if($.path.startsWith("src/commands/")&&$.status==="added"){if($.path.endsWith("index.ts"))return"New command module";return"New command helper"}if(/\.test\.[jt]sx?$/.test($.path)||/\.spec\.[jt]sx?$/.test($.path)){if($.status==="added")return"New test file";return"Updated tests"}if($.path.endsWith(".md")||$.path.startsWith("docs/")){if($.status==="added")return"New documentation";return"Documentation update"}if($.path.includes("config")||$.path.endsWith(".json")||$.path.endsWith(".yaml")||$.path.endsWith(".yml")||$.path.endsWith(".toml")||$.path.includes(".env")){if($.status==="added")return"New configuration";return"Configuration update"}let Y=G4(Z,X,$.status);if(Y.length===0)return null;Y.sort((V,U)=>U.priority-V.priority);let K=new Set,W=Y.filter((V)=>{if(K.has(V.description))return!1;return K.add(V.description),!0}),q=W[0];if(W.length>1)return`${q.description} (+${W.length-1} more)`;return q.description}var r;var b5=T(()=>{X0();r={name:"file-summary",analyze($){let Z=[],X=[],Q=[],Y=[],K=[];for(let q of $.files){if(k$(q.path))continue;switch(q.status){case"added":Z.push(q.path);break;case"modified":X.push(q.path);break;case"deleted":Q.push(q.path);break;case"renamed":Y.push({from:q.oldPath??q.path,to:q.path});break}}for(let q of $.diffs){if(k$(q.path))continue;let V=O4(q);if(V)K.push({file:q.path,description:V})}if(Z.length===0&&X.length===0&&Q.length===0&&Y.length===0)return[];return[{type:"file-summary",kind:"file-summary",category:"unknown",confidence:"high",evidence:[],added:Z,modified:X,deleted:Q,renamed:Y,changeDescriptions:K.length>0?K:void 0}]}}});function _4($){for(let Z of M4)if(Z.patterns.some((X)=>X.test($)))return Z.category;return"other"}function Q0($){return{product:"Product Code",tests:"Tests",ci:"CI/CD",infra:"Infrastructure",database:"Database",docs:"Documentation",dependencies:"Dependencies",config:"Configuration",artifacts:"Build Artifacts",other:"Other"}[$]}var M4,a;var Y0=T(()=>{M4=[{category:"tests",patterns:[/^tests?\//i,/^__tests__\//i,/\/tests?\//i,/\/__tests__\//i,/\.test\.[jt]sx?$/i,/\.spec\.[jt]sx?$/i,/\.e2e\.[jt]sx?$/i,/vitest\.config/i,/jest\.config/i,/cypress\//i,/playwright\//i]},{category:"ci",patterns:[/^\.github\/workflows\//,/^\.github\/actions\//,/^\.gitlab-ci\.yml$/,/^\.circleci\//,/^Jenkinsfile$/,/^\.travis\.yml$/,/^azure-pipelines\.yml$/,/^bitbucket-pipelines\.yml$/]},{category:"infra",patterns:[/^Dockerfile/i,/^docker-compose/i,/^\.dockerignore$/,/^helm\//i,/^charts?\//i,/^terraform\//i,/^\.tf$/,/^k8s\//i,/^kubernetes\//i,/^pulumi\//i,/^ansible\//i,/^Vagrantfile$/]},{category:"database",patterns:[/^supabase\/migrations\//,/^supabase\/seed/,/^prisma\/migrations\//,/^prisma\/schema\.prisma$/,/^drizzle\/migrations\//,/^drizzle\.config/,/^migrations?\//i,/\/migrations?\//i,/\.sql$/i]},{category:"docs",patterns:[/^docs?\//i,/^documentation\//i,/\.md$/i,/\.mdx$/i,/^README/i,/^CHANGELOG/i,/^CONTRIBUTING/i,/^LICENSE/i,/^\.all-contributorsrc$/]},{category:"dependencies",patterns:[/^package\.json$/,/^package-lock\.json$/,/^yarn\.lock$/,/^pnpm-lock\.yaml$/,/^bun\.lock$/,/^bun\.lockb$/,/^requirements\.txt$/,/^Pipfile(\.lock)?$/,/^poetry\.lock$/,/^pyproject\.toml$/,/^Cargo\.(toml|lock)$/,/^go\.(mod|sum)$/,/^Gemfile(\.lock)?$/,/^composer\.(json|lock)$/]},{category:"config",patterns:[/^\.[a-z]+rc(\.json|\.js|\.cjs|\.mjs|\.yaml|\.yml)?$/i,/\.config\.[jt]s$/i,/\.config\.[a-z]+\.[jt]s$/i,/^\.env/i,/^wrangler\.(toml|json)$/i,/^tsconfig.*\.json$/i,/^\.eslintrc/i,/^\.prettierrc/i,/^\.editorconfig$/,/^\.gitignore$/,/^\.nvmrc$/,/^\.node-version$/]},{category:"artifacts",patterns:[/\.tgz$/i,/\.tar\.gz$/i,/\.zip$/i,/\.whl$/i,/\.jar$/i,/\.war$/i,/\.gem$/i,/\.nupkg$/i,/\.deb$/i,/\.rpm$/i,/\.dmg$/i,/\.exe$/i,/\.dll$/i,/\.so$/i,/\.dylib$/i,/\.a$/i,/\.o$/i,/\.wasm$/i]},{category:"product",patterns:[/^src\//,/^lib\//,/^app\//,/^pages\//,/^components\//,/^hooks\//,/^utils\//,/^services\//,/^api\//,/^server\//,/^client\//,/\.[jt]sx?$/,/\.svelte$/,/\.vue$/,/\.astro$/]}];a={name:"file-category",analyze($){let Z={product:[],tests:[],ci:[],infra:[],database:[],docs:[],dependencies:[],config:[],artifacts:[],other:[]};for(let Y of $.files){let K=_4(Y.path);Z[K].push(Y.path)}let X=Object.entries(Z).filter(([,Y])=>Y.length>0).map(([Y,K])=>({category:Y,count:K.length})).sort((Y,K)=>K.count-Y.count);if(X.length===0)return[];return[{type:"file-category",kind:"file-category",category:"unknown",confidence:"high",evidence:[],categories:Z,summary:X}]}}});function S($){return $.hunks.flatMap((Z)=>Z.additions)}function e0($){let Z=[];for(let X of $.hunks){let Q=X.newStart,Y=X.content.split(`
|
|
14
|
+
`);for(let K of Y){if(K.startsWith("@@"))continue;if(K.startsWith("+")&&!K.startsWith("+++"))Z.push({line:K.slice(1),lineNumber:Q}),Q++;else if(!K.startsWith("-"))Q++}}return Z}function z1($){return $.hunks.flatMap((Z)=>Z.deletions)}function wK($){let Z=[];for(let X of $.hunks)Z.push(...X.additions,...X.deletions);return Z}function IK($){return $.map((Z)=>[...Z.additions,...Z.deletions].join(`
|
|
16
15
|
`)).join(`
|
|
17
|
-
`)}function
|
|
18
|
-
`),
|
|
19
|
-
`),J=
|
|
20
|
-
`),W=
|
|
21
|
-
`);if(
|
|
16
|
+
`)}function H4($,Z){return Z.test($)}function bK($,Z){return $.filter((X)=>H4(X.path,Z))}function PK($,Z){return S($).some((X)=>Z.test(X))}function CK($,Z){let X=[],Q=new RegExp(Z.source,"g"+Z.flags.replace("g",""));for(let Y of S($)){Q.lastIndex=0;let K;while((K=Q.exec(Y))!==null)X.push(K)}return X}function SK($,Z){let X=[],Q=new RegExp(Z.source,"g"+Z.flags.replace("g","")),Y=e0($);for(let{line:K,lineNumber:W}of Y){Q.lastIndex=0;let q;while((q=Q.exec(K))!==null)X.push({match:q,lineNumber:W,line:K})}return X}function A($,Z,X){return{file:$,excerpt:Z.trim(),line:X?.line,hunk:X?.hunk?{oldStart:X.hunk.oldStart,oldLines:X.hunk.oldLines,newStart:X.hunk.newStart,newLines:X.hunk.newLines}:void 0}}function C5($){return{...$,excerpt:K0($.excerpt)}}function K0($){let Z=$;return Z=Z.replace(/\b(sk|pk|rk)_(live|test)_[A-Za-z0-9]{24,}/g,"$1_$2_***REDACTED***"),Z=Z.replace(/\beyJ[A-Za-z0-9_-]{30,}\.[A-Za-z0-9_-]{30,}\.[A-Za-z0-9_-]{30,}/g,"eyJ***REDACTED***"),Z=Z.replace(/\bAKIA[0-9A-Z]{16}\b/g,"AKIA***REDACTED***"),Z=Z.replace(/(password|secret|token|apikey|api_key)(\s*[:=]\s*)(["'])(?!.*\*\*\*REDACTED\*\*\*)([^"']+?)\3/gi,"$1$2$3***REDACTED***$3"),Z=Z.replace(/(password|secret|token|apikey|api_key)(\s*[:=]\s*)(?!.*\*\*\*REDACTED\*\*\*)([^\s"',;)]+)/gi,"$1$2***REDACTED***"),Z}function P5($,Z=200){if($.length<=Z)return $;return $.substring(0,Z-3)+"..."}function F($,Z=200){if($.length===0)return"";for(let X of $){let Q=X.trim();if(Q.length>0&&!Q.startsWith("//")&&!Q.startsWith("/*")&&!Q.startsWith("*")&&!Q.startsWith("#"))return P5(Q,Z)}return P5($[0].trim(),Z)}function S5($){return $.startsWith("src/routes/")&&L4($)}function L4($){let Z=$.split("/").pop()??"";return Object.keys(k5).some((X)=>Z.startsWith(X.replace(".svelte","").replace(".ts",""))&&(Z.endsWith(".svelte")||Z.endsWith(".ts")))}function j4($){let Z=$.split("/").pop()??"";for(let[X,Q]of Object.entries(k5))if(Z===X)return Q;return"unknown"}function D4($){let Z=$.replace(/^src\/routes/,""),X=Z.split("/");if(X.pop(),Z=X.join("/"),Z===""||Z==="/")return"/";if(!Z.startsWith("/"))Z="/"+Z;return Z}function n1($){return $.replace(/\/\([^)]+\)/g,"")}function N4($){let Z=new Set,X=S($).join(`
|
|
17
|
+
`),Q,Y=new RegExp(z4.source,"g");while((Q=Y.exec(X))!==null)Z.add(Q[1]);return Array.from(Z).sort()}var k5,z4,F5;var q0=T(()=>{k5={"+page.svelte":"page","+page.ts":"page","+page.server.ts":"page","+layout.svelte":"layout","+layout.ts":"layout","+layout.server.ts":"layout","+server.ts":"endpoint","+error.svelte":"error"},z4=/export\s+const\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;F5={name:"route-detector",analyze($){let Z=[],X=new Map;for(let Q of $.files)if(S5(Q.path))X.set(Q.path,{status:Q.status});for(let Q of $.diffs)if(S5(Q.path)){let Y=X.get(Q.path);if(Y)Y.diff=Q;else X.set(Q.path,{diff:Q,status:Q.status})}for(let[Q,{diff:Y,status:K}]of X){let W=D4(Q),q=j4(Q),V=[];if(Y&&Y.hunks.length>0){let J=S(Y);if(J.length>0){let B=F(J);if(B)V.push(A(Q,B))}}let U={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:V,routeId:W,file:Q,change:K,routeType:q};if(q==="endpoint"&&Y){let J=N4(Y);if(J.length>0){U.methods=J;let B=J.map((G)=>`export const ${G}`).join(", ");if(!V.length)V.push(A(Q,B))}}Z.push(U)}return Z}}});function T4($){return A4.test($)}function x4($){return R4.test($)}function E4($){let Z=[];for(let{pattern:X,description:Q}of v5)if(X.test($))Z.push({pattern:X.source,description:Q});return Z}function w4($,Z){let X=[],Q=[],Y=!1;for(let W of $){let q=Z.diffs.find((B)=>B.path===W);if(!q)continue;let V=S(q),U=V.join(`
|
|
18
|
+
`),J=E4(U);for(let{description:B}of J){Y=!0,X.push(`${B} detected in ${W}`);let G=V.find((M)=>v5.some((_)=>_.pattern.test(M)));if(G)Q.push({file:W,excerpt:G.trim()})}}if(Y)return{risk:"high",reasons:X,evidence:Q};if($.every((W)=>x4(W)))return{risk:"low",reasons:["Only seed/config files changed"],evidence:Q};return{risk:"medium",reasons:["Migration files changed"],evidence:Q}}var A4,R4,v5,y5;var m5=T(()=>{A4=/^supabase\/migrations\/.*\.sql$/,R4=/^supabase\/(seed|config)/,v5=[{pattern:/DROP\s+TABLE/i,description:"DROP TABLE"},{pattern:/DROP\s+COLUMN/i,description:"DROP COLUMN"},{pattern:/TRUNCATE/i,description:"TRUNCATE"},{pattern:/ALTER\s+COLUMN/i,description:"ALTER COLUMN"},{pattern:/ALTER\s+TABLE\s+\w+\s+.*\s+TYPE/i,description:"ALTER TYPE"},{pattern:/DELETE\s+FROM\s+\w+\s*(?:;|$)/i,description:"DELETE without WHERE"}];y5={name:"supabase",analyze($){let Z=[],X=[],Q=[];for(let U of $.files)if(U.path.startsWith("supabase/")){if(Q.push(U.path),T4(U.path))X.push(U.path)}if(Q.length===0)return[];let{risk:Y,reasons:K,evidence:W}=w4(X.length>0?X:Q,$),q=W.map((U)=>A(U.file,U.excerpt)),V={type:"db-migration",kind:"db-migration",category:"database",confidence:"high",evidence:q,tool:"supabase",files:X.length>0?X:Q,risk:Y,reasons:K};if(Z.push(V),Y==="high"){let U={type:"risk-flag",kind:"risk-flag",category:"database",confidence:"high",evidence:q,risk:"high",evidenceText:`Destructive SQL detected: ${K.join(", ")}`};Z.push(U)}return Z}}});function P4($){if($.endsWith(".md")||$.startsWith("docs/"))return!1;if($.includes("/tests/")||$.includes("/__tests__/")||$.includes(".test.")||$.includes(".spec.")||$.startsWith("tests/"))return!1;if($.includes("/fixtures/")||$.includes("/__fixtures__/"))return!1;for(let X of b4)if(X.test($))return!0;let Z=$.substring($.lastIndexOf("."));return I4.has(Z)}function C4($){return $.split(",").map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>{return Z.split(/\s+as\s+/)[0].trim()})}function S4($){let Z=new Set;m1.processEnv.lastIndex=0;let X;while((X=m1.processEnv.exec($))!==null)Z.add(X[1]);m1.viteEnv.lastIndex=0;while((X=m1.viteEnv.exec($))!==null)Z.add(`VITE_${X[1]}`);m1.publicVar.lastIndex=0;while((X=m1.publicVar.exec($))!==null)Z.add(`PUBLIC_${X[1]}`);let Q=[m1.envStaticPublic,m1.envStaticPrivate,m1.envDynamicPublic,m1.envDynamicPrivate];for(let Y of Q){Y.lastIndex=0;while((X=Y.exec($))!==null){let K=C4(X[1]);for(let W of K)Z.add(W)}}return Z}var I4,b4,m1,$1;var h5=T(()=>{X0();I4=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".svelte",".vue",".astro"]),b4=[/\.env(\..+)?$/,/vite\.config\.(ts|js|mjs)$/,/svelte\.config\.(ts|js|mjs)$/,/next\.config\.(ts|js|mjs)$/,/nuxt\.config\.(ts|js|mjs)$/,/astro\.config\.(ts|js|mjs)$/];m1={processEnv:/process\.env\.([A-Z_][A-Z0-9_]*)/g,viteEnv:/import\.meta\.env\.VITE_([A-Z0-9_]+)/g,publicVar:/\bPUBLIC_([A-Z0-9_]+)/g,envStaticPublic:/import\s*\{([^}]+)\}\s*from\s*["']\$env\/static\/public["']/g,envStaticPrivate:/import\s*\{([^}]+)\}\s*from\s*["']\$env\/static\/private["']/g,envDynamicPublic:/import\s*\{([^}]+)\}\s*from\s*["']\$env\/dynamic\/public["']/g,envDynamicPrivate:/import\s*\{([^}]+)\}\s*from\s*["']\$env\/dynamic\/private["']/g};$1={name:"env-var",analyze($){let Z=[],X=new Map;for(let Q of $.diffs){if(k$(Q.path))continue;if(!P4(Q.path))continue;let Y=S(Q),K=Y.join(`
|
|
19
|
+
`),W=S4(K);for(let q of W){if(!X.has(q))X.set(q,[]);let V=Y.find((J)=>J.includes(q)),U=V?V.trim():F(Y);X.get(q).push({file:Q.path,excerpt:U})}}for(let[Q,Y]of X){let K=Array.from(new Set(Y.map((V)=>V.file))),q={type:"env-var",kind:"env-var",category:"config_env",confidence:"high",evidence:Y.slice(0,3).map((V)=>A(V.file,V.excerpt)),name:Q,change:"added",evidenceFiles:K};Z.push(q)}return Z}}});function y4($){return k4.some((Z)=>Z.test($))}function m4($){return F4.test($)}function h4($){return v4.test($)}var k4,F4,v4,J1;var u5=T(()=>{k4=[/^wrangler\.toml$/,/^wrangler\.json$/],F4=/^\.github\/workflows\/.*\.(yml|yaml)$/,v4=/\b(wrangler|cloudflare|workers|pages)\b/i;J1={name:"cloudflare",analyze($){let Z=[],X=new Map;for(let Q of $.files)if(y4(Q.path)){if(!X.has("wrangler"))X.set("wrangler",[]);let Y=$.diffs.find((W)=>W.path===Q.path),K=Y?F(S(Y)):Q.path;X.get("wrangler").push({file:Q.path,excerpt:K})}for(let Q of $.diffs)if(m4(Q.path)){let Y=S(Q),K=Y.join(`
|
|
20
|
+
`);if(h4(K)){if(!X.has("ci"))X.set("ci",[]);let W=F(Y);X.get("ci").push({file:Q.path,excerpt:W})}}for(let[Q,Y]of X){let K=Y.map((V)=>V.file),q={type:"cloudflare-change",kind:"cloudflare-change",category:"cloudflare",confidence:"high",evidence:Y.slice(0,3).map((V)=>A(V.file,V.excerpt)),area:Q,files:K};Z.push(q)}return Z}}});function W0($){return u4.some((Z)=>Z.test($))}function f4($){return g4.some((Z)=>Z.test($))}var u4,g4,Z1;var $2=T(()=>{u4=[/\.test\.ts$/,/\.spec\.ts$/,/\.test\.js$/,/\.spec\.js$/,/^tests?\//],g4=[/^vitest\.config(\.[a-z0-9]+)?\.(ts|js|mts|mjs)$/,/^vite\.config(\.[a-z0-9]+)?\.(ts|js|mts|mjs)$/];Z1={name:"vitest",analyze($){let Z=[],X=[],Q=[],Y=[];for(let q of $.files)if(W0(q.path)||f4(q.path))switch(Z.push(q.path),q.status){case"added":X.push(q.path);break;case"modified":Q.push(q.path);break;case"deleted":Y.push(q.path);break;case"renamed":Q.push(q.path);break}if(Z.length===0)return[];return[{type:"test-change",kind:"test-change",category:"tests",confidence:"high",evidence:Z.slice(0,3).map((q)=>{let V=X.includes(q)?"added":Y.includes(q)?"deleted":"modified";return A(q,`Test file ${V}: ${q}`)}),framework:"vitest",files:Z,added:X,modified:Q,deleted:Y}]}}});import*as Z2 from"semver";function p4($){return c4.get($)}function g5($){return $.replace(d4,"").trim()}function r4($,Z){if(!$||!Z)return"unknown";let X=g5($),Q=g5(Z),Y=Z2.parse(X),K=Z2.parse(Q);if(!Y||!K)return"unknown";if(K.major>Y.major)return"major";if(K.minor>Y.minor)return"minor";if(K.patch>Y.patch)return"patch";return"unknown"}function a4($,Z){let X=[],Q=["dependencies","devDependencies"];for(let Y of Q){let K=$?.[Y]??{},W=Z?.[Y]??{},q=new Set([...Object.keys(K),...Object.keys(W)]);for(let V of q){let U=K[V],J=W[V];if(U===J)continue;let B=p4(V);if(!U&&J){let G=`"${V}": "${J}"`;X.push({type:"dependency-change",kind:"dependency-change",category:"dependencies",confidence:"high",evidence:[A("package.json",G)],name:V,section:Y,to:J,impact:"new",riskCategory:B})}else if(U&&!J){let G=`"${V}": "${U}" (removed)`;X.push({type:"dependency-change",kind:"dependency-change",category:"dependencies",confidence:"high",evidence:[A("package.json",G)],name:V,section:Y,from:U,impact:"removed",riskCategory:B})}else{let G=r4(U,J),M=`"${V}": "${U}" → "${J}"`;X.push({type:"dependency-change",kind:"dependency-change",category:"dependencies",confidence:"high",evidence:[A("package.json",M)],name:V,section:Y,from:U,to:J,impact:G,riskCategory:B})}}}return X}var l4,c4,d4,X1;var f5=T(()=>{l4=["@sveltejs/kit","svelte","vite"],c4=new Map([...["passport","jsonwebtoken","bcrypt","bcryptjs","oauth","auth0","@auth0/auth0-spa-js","clerk","@clerk/clerk-sdk-node","@clerk/nextjs","next-auth","@auth/core","@auth/sveltekit","lucia","lucia-auth","arctic","oslo","express-session","cookie-session","passport-local","passport-jwt","passport-oauth2","jose","jwks-rsa","supertokens-node","@supabase/auth-helpers-sveltekit","@supabase/ssr"].map(($)=>[$,"auth"]),...["prisma","@prisma/client","drizzle-orm","typeorm","sequelize","knex","mongoose","pg","mysql","mysql2","sqlite3","better-sqlite3","mongodb","redis","ioredis","@neondatabase/serverless","@planetscale/database","@libsql/client","kysely"].map(($)=>[$,"database"]),...["sharp","canvas","node-gyp","node-pre-gyp","node-addon-api","nan","ffi-napi","ref-napi","argon2","libsodium-wrappers","sodium-native","cpu-features","usb","serialport"].map(($)=>[$,"native"]),...["stripe","@stripe/stripe-js","paypal-rest-sdk","@paypal/checkout-server-sdk","braintree","square","@square/web-sdk","adyen-api-library","razorpay","mollie-api-node","lemon-squeezy","@polar-sh/sdk","polar-sdk"].map(($)=>[$,"payment"])]);d4=/^[\^~>=<]+/;X1={name:"dependencies",analyze($){let Z=[],X=a4($.basePackageJson,$.headPackageJson);Z.push(...X);for(let Q of X){if(l4.includes(Q.name)&&Q.impact==="major"&&Q.from&&Q.to){let Y=`${Q.name}: ${Q.from} → ${Q.to}`,K={type:"risk-flag",kind:"risk-flag",category:"dependencies",confidence:"high",evidence:[A("package.json",Y)],risk:"high",evidenceText:`Major version bump: ${Q.name} ${Q.from} → ${Q.to}`};Z.push(K)}if(Q.riskCategory&&Q.impact==="new"){let Y={auth:"Authentication/Security",database:"Database/ORM",native:"Native Module",payment:"Payment Processing"},K=`${Q.name}: ${Q.to}`,W={type:"risk-flag",kind:"risk-flag",category:"dependencies",confidence:"medium",evidence:[A("package.json",K)],risk:"medium",evidenceText:`New ${Y[Q.riskCategory]} package: ${Q.name}`};Z.push(W)}}return Z}}});function o4($){for(let{pattern:Z,reason:X}of s4)if(Z.test($))return X;return null}function X2($){return{"auth-path":"Authentication","session-path":"Session/Token","permission-path":"Permissions/RBAC",middleware:"Middleware",guard:"Route Guard",policy:"Policy"}[$]}var s4,Q1;var Q2=T(()=>{s4=[{pattern:/\bauth\b/i,reason:"auth-path"},{pattern:/\blogin\b/i,reason:"auth-path"},{pattern:/\blogout\b/i,reason:"auth-path"},{pattern:/\bsignin\b/i,reason:"auth-path"},{pattern:/\bsignout\b/i,reason:"auth-path"},{pattern:/\bsignup\b/i,reason:"auth-path"},{pattern:/\bregister\b/i,reason:"auth-path"},{pattern:/\bsession\b/i,reason:"session-path"},{pattern:/\bjwt\b/i,reason:"session-path"},{pattern:/\btoken\b/i,reason:"session-path"},{pattern:/\bcookie\b/i,reason:"session-path"},{pattern:/\boauth\b/i,reason:"session-path"},{pattern:/\bpermission\b/i,reason:"permission-path"},{pattern:/\brbac\b/i,reason:"permission-path"},{pattern:/\bacl\b/i,reason:"permission-path"},{pattern:/\brole\b/i,reason:"permission-path"},{pattern:/\bauthoriz/i,reason:"permission-path"},{pattern:/middleware\.[jt]sx?$/i,reason:"middleware"},{pattern:/\/middleware\//,reason:"middleware"},{pattern:/guard\.[jt]sx?$/i,reason:"guard"},{pattern:/\/guards?\//,reason:"guard"},{pattern:/policy\.[jt]sx?$/i,reason:"policy"},{pattern:/\/policies\//,reason:"policy"}];Q1={name:"security-files",analyze($){let Z=[],X=[],Q=new Set;for(let V of $.files){let U=o4(V.path);if(U)X.push(V.path),Q.add(U)}if(X.length===0)return[];let Y=X.slice(0,3).map((V)=>A(V,`Security file: ${V}`)),K={type:"security-file",kind:"security-file",category:"infra",confidence:"medium",evidence:Y,files:X,reasons:Array.from(Q)};Z.push(K);let W=Array.from(Q).map(X2).join(", "),q={type:"risk-flag",kind:"risk-flag",category:"infra",confidence:"medium",evidence:Y,risk:"medium",evidenceText:`Security-sensitive files changed (${W}): ${X.length} file(s)`};return Z.push(q),Z}}});import{execa as i4}from"execa";async function z$($,Z=process.cwd(),X=i4){if($.length===0)return new Map;let Q=new Map,Y=$.map((W)=>`${W.ref}:${W.path}`),K=Y.join(`
|
|
22
21
|
`)+`
|
|
23
|
-
`;try{let W=
|
|
24
|
-
`,U);if(B===-1)break;let M=V.subarray(U,B).toString("utf-8"),[
|
|
25
|
-
`).filter(Boolean);for(let W of
|
|
26
|
-
`).filter(Boolean)),
|
|
27
|
-
`);for(let G of B){if(!G)continue;let M=G.indexOf("\x00");if(M===-1)continue;let
|
|
28
|
-
`),q=[],V="";for(let U of W)if(U.includes(
|
|
29
|
-
${U.trim()}`:U.trim();let J=U.match(/\{([^}]+)\}/);if(J){let B=J[1].split(",").map((G)=>{return G.trim().split(" as ")[0].trim().replace(/^type\s+/,"")});q.push(...B)}if(!J&&U.trim().startsWith("import")){let B=U.split("from");if(B.length>1){let G=B[0].replace("import","").trim();if(G){let M=G.match(/\*\s+as\s+([A-Za-z0-9_$]+)/);if(M)q.push(M[1].trim());else if(!G.includes("{")&&!G.includes("*"))q.push(G.split(" as ")[0].trim())}}}}return{importedSymbols:q,usageContext:V}}catch(
|
|
30
|
-
`);if(/\b(DROP\s+TABLE|DROP\s+COLUMN|TRUNCATE)\b/gi.test(
|
|
31
|
-
`);if(!K&&/permissions:[\s\S]{0,500}?\b(contents|id-token|actions|packages|deployments|security-events)\b\s*:\s*write/gi.test(V)){K=!0;let G=k(q.additions,200);Z.push({type:"ci-workflow",kind:"ci-workflow",category:"ci",confidence:"high",evidence:[N(X.path,G,{hunk:q})],file:X.path,riskType:"permissions_broadened",details:"Workflow has broadened permissions (write access)"})}if(!Y&&/pull_request_target/i.test(V)){Y=!0;let G=k(q.additions,200);Z.push({type:"ci-workflow",kind:"ci-workflow",category:"ci",confidence:"high",evidence:[N(X.path,G,{hunk:q})],file:X.path,riskType:"pull_request_target",details:"Workflow uses pull_request_target event (can expose secrets)"})}if(!W&&/(curl|wget)\s+[^\s]+\s*\|\s*(sh|bash)/gi.test(V)){W=!0;let G=k(q.additions,200);Z.push({type:"ci-workflow",kind:"ci-workflow",category:"ci",confidence:"high",evidence:[N(X.path,G,{hunk:q})],file:X.path,riskType:"remote_script_download",details:"Workflow downloads and pipes to shell (supply chain risk)"})}}if(!Q.has(X.path)&&X.hunks.length>0){Q.add(X.path);let q=k(X.hunks[0].additions,150);Z.push({type:"ci-workflow",kind:"ci-workflow",category:"ci",confidence:"medium",evidence:[N(X.path,q)],file:X.path,riskType:"pipeline_changed",details:"CI/CD pipeline configuration modified"})}}return Z}}});var U1;var r5=x(()=>{U1={name:"infra",analyze($){let Z=[],Q=[],X=[],K=[];for(let Y of $.files)if(Y.path.toLowerCase().includes("dockerfile"))Q.push(Y.path);else if(Y.path.endsWith(".tf")||Y.path.endsWith(".tfvars"))X.push(Y.path);else if(Y.path.includes("kubernetes/")||Y.path.includes("k8s/")||Y.path.endsWith(".yaml")&&(Y.path.includes("deployment")||Y.path.includes("service")||Y.path.includes("ingress")))K.push(Y.path);if(Q.length>0)Z.push({type:"infra-change",kind:"infra-change",category:"infra",confidence:"high",evidence:[],infraType:"dockerfile",files:Q});if(X.length>0)Z.push({type:"infra-change",kind:"infra-change",category:"infra",confidence:"high",evidence:[],infraType:"terraform",files:X});if(K.length>0)Z.push({type:"infra-change",kind:"infra-change",category:"infra",confidence:"high",evidence:[],infraType:"k8s",files:K});return Z}}});function M6($){return $.includes("openapi")||$.includes("swagger")||$.endsWith(".proto")||$.includes("/api/")&&($.endsWith(".yaml")||$.endsWith(".yml")||$.endsWith(".json"))}var Z1;var a5=x(()=>{Z1={name:"api-contracts",analyze($){let Z=[],Q=$.files.filter((X)=>M6(X.path)).map((X)=>X.path);if(Q.length>0)Z.push({type:"api-contract-change",kind:"api-contract-change",category:"api",confidence:"high",evidence:[],files:Q});return Z}}});import{parse as H6}from"@babel/parser";import s5 from"@babel/traverse";import*as I from"@babel/types";function z6($){return $.endsWith(".tsx")||$.endsWith(".ts")}function o5($){if($==="default")return"<slot />";else if($==="boolean")return"<slot name />";else if($==="dynamic")return"<slot name={...} />";else return`<slot name="${$}" />`}function n5($,Z){let Q=[];try{let X=H6($,{sourceType:"module",plugins:["typescript","jsx","decorators-legacy"]});s5(X,{ClassDeclaration(K){let W=(K.node.decorators||[]).find((H)=>I.isCallExpression(H.expression)&&I.isIdentifier(H.expression.callee)&&H.expression.callee.name==="Component");if(!W)return;let q="",V=!1,U=K.node.loc?.start.line??1;if(I.isCallExpression(W.expression)){let H=W.expression.arguments[0];if(I.isObjectExpression(H)){for(let O of H.properties)if(I.isObjectProperty(O)&&I.isIdentifier(O.key)){if(O.key.name==="tag"){if(I.isStringLiteral(O.value))q=O.value.value}else if(O.key.name==="shadow"){if(I.isBooleanLiteral(O.value))V=O.value.value}}}}if(!q)return;let J=new Map,B=new Map,G=new Map,M=new Set;for(let H of K.node.body.body){if(I.isClassProperty(H)||I.isClassMethod(H)){let O=H.decorators||[],z=O.find((L)=>I.isCallExpression(L.expression)&&I.isIdentifier(L.expression.callee)&&L.expression.callee.name==="Prop"||I.isIdentifier(L.expression)&&L.expression.name==="Prop");if(z&&I.isIdentifier(H.key)){let L=H.key.name,w=H.loc?.start.line??1,T,A=!1,b=!1,R;if(I.isClassProperty(H)&&H.typeAnnotation&&I.isTSTypeAnnotation(H.typeAnnotation));if(I.isCallExpression(z.expression)){let h=z.expression.arguments[0];if(I.isObjectExpression(h)){for(let y of h.properties)if(I.isObjectProperty(y)&&I.isIdentifier(y.key)){if(y.key.name==="attribute"&&I.isStringLiteral(y.value))T=y.value.value;if(y.key.name==="reflect"&&I.isBooleanLiteral(y.value))A=y.value.value;if(y.key.name==="mutable"&&I.isBooleanLiteral(y.value))b=y.value.value}}}J.set(L,{name:L,attribute:T,reflect:A,mutable:b,typeText:R,line:w})}let _=O.find((L)=>I.isCallExpression(L.expression)&&I.isIdentifier(L.expression.callee)&&L.expression.callee.name==="Event"||I.isIdentifier(L.expression)&&L.expression.name==="Event");if(_&&I.isIdentifier(H.key)){let L=H.key.name,w=L,T=H.loc?.start.line??1,A=!0,b=!0,R=!0;if(I.isCallExpression(_.expression)){let h=_.expression.arguments[0];if(I.isObjectExpression(h)){for(let y of h.properties)if(I.isObjectProperty(y)&&I.isIdentifier(y.key)){if(y.key.name==="eventName"&&I.isStringLiteral(y.value))w=y.value.value;if(y.key.name==="bubbles"&&I.isBooleanLiteral(y.value))A=y.value.value;if(y.key.name==="composed"&&I.isBooleanLiteral(y.value))b=y.value.value;if(y.key.name==="cancelable"&&I.isBooleanLiteral(y.value))R=y.value.value}}}B.set(w,{name:w,memberName:L,bubbles:A,composed:b,cancelable:R,line:T})}if(O.find((L)=>I.isCallExpression(L.expression)&&I.isIdentifier(L.expression.callee)&&L.expression.callee.name==="Method"||I.isIdentifier(L.expression)&&L.expression.name==="Method")&&I.isIdentifier(H.key)){let L=H.key.name,w=H.loc?.start.line??1;G.set(L,{name:L,line:w})}}if(I.isClassMethod(H)&&I.isIdentifier(H.key)&&H.key.name==="render")s5(H,{JSXElement(O){let z=O.node.openingElement;if(I.isJSXIdentifier(z.name)&&z.name.name==="slot"){let _="default";for(let D of z.attributes)if(I.isJSXAttribute(D)&&I.isJSXIdentifier(D.name)&&D.name.name==="name")if(I.isStringLiteral(D.value))_=D.value.value;else if(D.value===null)_="boolean";else _="dynamic";M.add(_)}}},K.scope,K)}Q.push({tag:q,shadow:V,file:Z,line:U,props:J,events:B,methods:G,slots:M})}})}catch(X){}return Q}var _6,$2;var i5=x(()=>{o0();_6={batchGetFileContent:$0};$2={name:"stencil",async analyze($){let Z=[],Q=$.files.filter((Y)=>z6(Y.path));if(Q.length===0)return[];let X=[];for(let Y of Q)X.push({ref:$.base,path:Y.path}),X.push({ref:$.head,path:Y.path});let K=await _6.batchGetFileContent(X);for(let Y of Q){let W=`${$.base}:${Y.path}`,q=`${$.head}:${Y.path}`,V=K.get(W),U=K.get(q);if(!V&&!U)continue;let J=V?n5(V,Y.path):[],B=U?n5(U,Y.path):[],G=new Map(J.map((O)=>[O.tag,O])),M=new Map(B.map((O)=>[O.tag,O])),H=new Set([...G.keys(),...M.keys()]);for(let O of H){let z=G.get(O),_=M.get(O);if(z&&!_)Z.push({type:"stencil-component-change",kind:"stencil-component-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Component({ tag: "${O}" })`,{line:z.line})],tag:O,change:"removed",file:Y.path});else if(!z&&_)Z.push({type:"stencil-component-change",kind:"stencil-component-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Component({ tag: "${O}" })`,{line:_.line})],tag:O,change:"added",file:Y.path});else if(z&&_){if(z.shadow!==_.shadow)Z.push({type:"stencil-component-change",kind:"stencil-component-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Component({ tag: "${O}", shadow: ${_.shadow} })`,{line:_.line})],tag:O,change:"shadow-changed",file:Y.path,fromShadow:z.shadow,toShadow:_.shadow});let D=new Set([...z.props.keys(),..._.props.keys()]);for(let A of D){let b=z.props.get(A),R=_.props.get(A);if(b&&!R)Z.push({type:"stencil-prop-change",kind:"stencil-prop-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Prop() ${A}`,{line:b.line})],tag:O,propName:A,change:"removed",file:Y.path});else if(!b&&R)Z.push({type:"stencil-prop-change",kind:"stencil-prop-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Prop() ${A}`,{line:R.line})],tag:O,propName:A,change:"added",file:Y.path,details:{attribute:R.attribute,reflect:R.reflect,mutable:R.mutable}});else if(b&&R){if(b.attribute!==R.attribute||b.reflect!==R.reflect||b.mutable!==R.mutable)Z.push({type:"stencil-prop-change",kind:"stencil-prop-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Prop() ${A}`,{line:R.line})],tag:O,propName:A,change:"changed",file:Y.path,details:{attribute:R.attribute,reflect:R.reflect,mutable:R.mutable}})}}let L=new Set([...z.events.keys(),..._.events.keys()]);for(let A of L){let b=z.events.get(A),R=_.events.get(A);if(b&&!R)Z.push({type:"stencil-event-change",kind:"stencil-event-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Event() ${b.memberName}`,{line:b.line})],tag:O,eventName:A,change:"removed",file:Y.path});else if(!b&&R)Z.push({type:"stencil-event-change",kind:"stencil-event-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Event() ${R.memberName}`,{line:R.line})],tag:O,eventName:A,change:"added",file:Y.path,details:{bubbles:R.bubbles,composed:R.composed,cancelable:R.cancelable}});else if(b&&R){if(b.bubbles!==R.bubbles||b.composed!==R.composed||b.cancelable!==R.cancelable)Z.push({type:"stencil-event-change",kind:"stencil-event-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Event() ${R.memberName}`,{line:R.line})],tag:O,eventName:A,change:"changed",file:Y.path,details:{bubbles:R.bubbles,composed:R.composed,cancelable:R.cancelable}})}}let w=new Set([...z.methods.keys(),..._.methods.keys()]);for(let A of w){let b=z.methods.get(A),R=_.methods.get(A);if(b&&!R)Z.push({type:"stencil-method-change",kind:"stencil-method-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Method() ${A}`,{line:b.line})],tag:O,methodName:A,change:"removed",file:Y.path});else if(!b&&R)Z.push({type:"stencil-method-change",kind:"stencil-method-change",category:"api",confidence:"high",evidence:[N(Y.path,`@Method() ${A}`,{line:R.line})],tag:O,methodName:A,change:"added",file:Y.path})}let T=new Set([...z.slots,..._.slots]);for(let A of T){let b=z.slots.has(A),R=_.slots.has(A);if(b&&!R)Z.push({type:"stencil-slot-change",kind:"stencil-slot-change",category:"api",confidence:"high",evidence:[N(Y.path,o5(A),{line:z.line})],tag:O,slotName:A,change:"removed",file:Y.path});else if(!b&&R)Z.push({type:"stencil-slot-change",kind:"stencil-slot-change",category:"api",confidence:"high",evidence:[N(Y.path,o5(A),{line:_.line})],tag:O,slotName:A,change:"added",file:Y.path})}}}}return Z}}});function t5($){if(!$.startsWith("app/")&&!$.startsWith("src/app/"))return!1;return D6($)}function D6($){let Z=$.split("/").pop()??"";return Object.keys(e5).includes(Z)}function A6($){let Z=$.split("/").pop()??"";return e5[Z]??"unknown"}function N6($){let Z=$.replace(/^src\/app/,"").replace(/^app/,""),Q=Z.split("/");if(Q.pop(),Z=Q.join("/"),Z=Z.replace(/\/\([^)]+\)/g,""),Z===""||Z==="/")return"/";if(!Z.startsWith("/"))Z="/"+Z;if(Z.length>1&&Z.endsWith("/"))Z=Z.slice(0,-1);return Z}function R6($){let Z=new Set,Q=P($).join(`
|
|
32
|
-
`),
|
|
33
|
-
`),X
|
|
34
|
-
`),X
|
|
35
|
-
`);for(let
|
|
36
|
-
`),
|
|
37
|
-
`);if(/\bcontent\s*[:{]/.test(
|
|
38
|
-
`);return/["']workspaces["']/.test(
|
|
39
|
-
`);for(let
|
|
40
|
-
`),
|
|
41
|
-
`);switch($){case"turborepo":if(/pipeline|tasks/.test(
|
|
42
|
-
`),
|
|
22
|
+
`;try{let W=X("git",["cat-file","--batch"],{cwd:Z,input:K}),{stdout:q}=await W,V=Buffer.isBuffer(q)?q:Buffer.from(String(q),"utf-8"),U=0;for(let J of Y){if(U>=V.length)break;let B=V.indexOf(`
|
|
23
|
+
`,U);if(B===-1)break;let M=V.subarray(U,B).toString("utf-8"),[_,O,H]=M.split(" ");if(!_||!O||!H){U=B+1;continue}if(O==="missing"){U=B+1;continue}let z=parseInt(H,10),N=B+1,j=N+z,E=V.subarray(N,j);Q.set(J,E.toString("utf-8")),U=j+1}}catch(W){console.warn("Failed to batch fetch files:",W)}return Q}var U0=()=>{};import{parse as n4}from"@babel/parser";import Y2 from"@babel/traverse";import*as v from"@babel/types";function e4($){if(![".ts",".tsx",".js",".jsx"].some((X)=>$.endsWith(X)))return!1;return!0}function V0($){let Z=$.replace(/\/+/g,"/");if(Z!=="/"&&Z.endsWith("/"))Z=Z.slice(0,-1);return Z}function c5($,Z){if(Z.startsWith("/"))return V0(Z);let X=$==="/"?`/${Z}`:`${$}/${Z}`;return V0(X)}function p5($,Z,X="/"){let Q=[];return Y2($,{JSXElement(Y){let K=Y.node.openingElement,W=K.name;if(v.isJSXIdentifier(W)&&W.name==="Route"){let q=null,V=!1,U=[];for(let J of K.attributes)if(v.isJSXAttribute(J)&&v.isJSXIdentifier(J.name)){if(J.name.name==="path"&&J.value){if(v.isStringLiteral(J.value))q=J.value.value;else if(v.isJSXExpressionContainer(J.value)&&v.isStringLiteral(J.value.expression))q=J.value.expression.value}else if(J.name.name==="index")V=!0}if(V)Q.push({path:V0(X),file:Z});else if(q){let J=c5(X,q);Q.push({path:J,file:Z});for(let B of Y.node.children)if(v.isJSXElement(B))U.push(B);for(let B of U){let G=v.file(v.program([v.expressionStatement(B)])),M=p5(G,Z,J);Q.push(...M)}}Y.skip()}}}),Q}function $6($,Z,X="/"){let Q=[],Y=new Map;return Y2($,{VariableDeclarator(K){if(v.isIdentifier(K.node.id)&&(v.isArrayExpression(K.node.init)||v.isObjectExpression(K.node.init)))Y.set(K.node.id.name,K.node.init)}}),Y2($,{CallExpression(K){let W=K.node.callee;if(v.isIdentifier(W)&&(W.name==="createBrowserRouter"||W.name==="createHashRouter"||W.name==="createMemoryRouter")){let q=K.node.arguments[0],V=null;if(v.isArrayExpression(q))V=q;else if(v.isIdentifier(q)){let U=Y.get(q.name);if(U&&v.isArrayExpression(U))V=U}if(V){let U=d5(V,Z,X);Q.push(...U)}}}}),Q}function d5($,Z,X="/"){let Q=[];for(let Y of $.elements)if(v.isObjectExpression(Y)){let K=Z6(Y);if(K.index)Q.push({path:V0(X),file:Z});else if(K.path){let W=c5(X,K.path);if(Q.push({path:W,file:Z}),K.children){let q=d5(K.children,Z,W);Q.push(...q)}}}return Q}function Z6($){let Z={};for(let X of $.properties)if(v.isObjectProperty(X)&&v.isIdentifier(X.key)){if(X.key.name==="path"&&v.isStringLiteral(X.value))Z.path=X.value.value;else if(X.key.name==="index"){if(v.isBooleanLiteral(X.value)&&X.value.value)Z.index=!0}else if(X.key.name==="children"&&v.isArrayExpression(X.value))Z.children=X.value}return Z}function l5($,Z){try{let X=n4($,{sourceType:"module",plugins:["typescript","jsx"]}),Q=p5(X,Z),Y=$6(X,Z);return[...Q,...Y]}catch(X){return[]}}var t4,K2;var r5=T(()=>{U0();t4={batchGetFileContent:z$};K2={name:"react-router-routes",async analyze($){let Z=[],X=$.files.filter((W)=>{return e4(W.path)});if(X.length===0)return[];let Q=[];for(let W of X)Q.push({ref:$.base,path:W.path}),Q.push({ref:$.head,path:W.path});let Y=await t4.batchGetFileContent(Q);for(let W of X){let q=`${$.base}:${W.path}`,V=`${$.head}:${W.path}`,U=Y.get(q),J=Y.get(V),B=(H)=>H.includes("react-router")||H.includes("<Route")||H.includes("createBrowserRouter")||H.includes("createHashRouter")||H.includes("createMemoryRouter");if(U&&!B(U)&&J&&!B(J))continue;let G=U?l5(U,W.path):[],M=J?l5(J,W.path):[],_=new Set(G.map((H)=>H.path)),O=new Set(M.map((H)=>H.path));for(let H of M)if(!_.has(H.path)){let z={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:[A(W.path,`Route: ${H.path}`)],routeId:H.path,file:W.path,change:"added",routeType:"page"};Z.push(z)}for(let H of G)if(!O.has(H.path)){let z={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:[A(W.path,`Route: ${H.path}`)],routeId:H.path,file:W.path,change:"deleted",routeType:"page"};Z.push(z)}}return Array.from(new Map(Z.map((W)=>{return[`${W.routeId}-${W.change}-${W.file}`,W]})).values()).sort((W,q)=>{let V=W.routeId,U=q.routeId;return V.localeCompare(U)})}}});var W2={};P1(W2,{testParityAnalyzer:()=>M6,createTestParityAnalyzer:()=>o5,_resetCacheForTesting:()=>W6});import B1 from"node:path";import{execa as X6}from"execa";function W6(){q2.clear(),F$=null}async function U6($,Z){let X=new Set,Q=[];for(let Y of $){let K=q2.get(Y);if(K)for(let W of K)X.add(W);else Q.push(Y)}if(Q.length===0)return X;try{let{stdout:Y}=await Z("git",["ls-files","--cached","--others","--exclude-standard","--",...Q],{reject:!1}),K=Y.split(`
|
|
24
|
+
`).filter(Boolean);for(let W of Q){let q=new Set;for(let V of K)if(V.startsWith(W+"/")||V.startsWith(W+B1.sep))q.add(V),X.add(V);q2.set(W,q)}for(let W of K)if(!W.includes("/")&&!W.includes(B1.sep))X.add(W);return X}catch{return V6(Z)}}async function V6($){if(F$)return F$;try{let{stdout:Z}=await $("git",["ls-files","--cached","--others","--exclude-standard"],{reject:!1});return F$=new Set(Z.split(`
|
|
25
|
+
`).filter(Boolean)),F$}catch{return new Set}}function J6($){return{testPatterns:$?.testPatterns??Y6,excludePatterns:[...Q6,...$?.excludePatterns??[]],testDirectories:$?.testDirectories??K6,sourceDirectories:$?.sourceDirectories??q6}}function a5($,Z){if(W0($))return!1;if(Z.some((X)=>X.test($)))return!1;return/\.(ts|js|tsx|jsx|mts|mjs)$/.test($)}function B6($,Z){if(/utils?|helpers?|lib|shared/i.test($))return"medium";if(Z&&Z.additions+Z.deletions<10)return"low";if(/services?|controllers?|handlers?|api|routes|commands?|analyzers?/i.test($))return"high";return"medium"}function s5($,Z,X,Q){let Y=[],K=B1.extname($),W=B1.basename($,K),q=B1.dirname($);for(let J of Z)Y.push(B1.join(q,`${W}${J}`));let V=$;for(let J of Q)if($.startsWith(`${J}/`)){V=$.slice(J.length+1);break}for(let J of X)for(let B of Z)Y.push(B1.join(J,B1.dirname(V),`${W}${B}`)),Y.push(B1.join(J,`${W}${B}`)),Y.push(B1.join(J,q,`${W}${B}`));let U=V.split(B1.sep);if(U.length>1){let J=U[U.length-2],B=`${J}-${W}`,G=`${W}-${J}`;for(let M of X)for(let _ of Z)Y.push(B1.join(M,`${B}${_}`)),Y.push(B1.join(M,`${G}${_}`))}return[...new Set(Y.map((J)=>B1.normalize(J)))]}async function G6($,Z,X,Q,Y){let K=s5($,Z,X,Q);for(let W of K)if(Y.has(W))return W;return null}function O6($,Z){let X=B1.basename($,B1.extname($));return Z.files.some((Q)=>W0(Q.path)&&Q.path.includes(X)&&Q.status!=="deleted")}function o5($,Z){let X=J6($),Q=Z?.exec??X6;return{name:"test-parity",async analyze(Y){let K=[],W=new Set;for(let V of Y.files){if(V.status==="deleted")continue;if(!a5(V.path,X.excludePatterns))continue;let U=B1.dirname(V.path);if(U&&U!==".")W.add(U.split(B1.sep)[0])}for(let V of X.testDirectories)W.add(V);let q=await U6([...W],Q);for(let V of Y.files)if(V.status!=="deleted")q.add(V.path);for(let V of Y.files){if(V.status==="deleted")continue;if(!a5(V.path,X.excludePatterns))continue;if(await G6(V.path,X.testPatterns,X.testDirectories,X.sourceDirectories,q))continue;if(O6(V.path,Y))continue;let J=Y.diffs.find((O)=>O.path===V.path),B=J?{additions:J.hunks.reduce((O,H)=>O+H.additions.length,0),deletions:J.hunks.reduce((O,H)=>O+H.deletions.length,0)}:void 0,G=B6(V.path,B),M=s5(V.path,X.testPatterns,X.testDirectories,X.sourceDirectories).slice(0,5),_={type:"test-parity-violation",kind:"test-parity-violation",category:"tests",confidence:G,evidence:[A(V.path,`Source file modified without corresponding test: ${V.path}`)],sourceFile:V.path,expectedTestLocations:M};K.push(_)}return K}}}var Q6,Y6,K6,q6,q2,F$=null,M6;var J0=T(()=>{$2();Q6=[/\.d\.ts$/,/\.config\.(ts|js|mts|mjs|cjs)$/,/index\.(ts|js|tsx|jsx)$/,/^docs\//,/^tests\//,/^test\//,/^__tests__\//,/^scripts\//,/^dist\//,/^build\//,/^\./,/types?\.(ts|js)$/,/constants?\.(ts|js)$/],Y6=[".test.ts",".spec.ts",".test.js",".spec.js",".test.tsx",".spec.tsx"],K6=["tests","test","__tests__","spec"],q6=["src","lib","app"],q2=new Map;M6=o5()});import L$ from"node:path";import i5 from"node:fs/promises";import{execa as n5}from"execa";async function z6($,Z=process.cwd(),X=n5){let Q=new Map;if($.forEach((q)=>Q.set(q.path,[])),$.length===0)return Q;let Y=new Map;for(let q of $){if(!Y.has(q.baseName))Y.set(q.baseName,[]);Y.get(q.baseName).push(q.path)}let K=Array.from(Y.keys()),W=50;for(let q=0;q<K.length;q+=W){let V=K.slice(q,q+W),U=["grep","-I","-F","--null"];for(let J of V)U.push("-e"),U.push(J);try{let{stdout:J}=await X("git",U,{cwd:Z,maxBuffer:20971520,reject:!1});if(!J)continue;let B=J.split(`
|
|
26
|
+
`);for(let G of B){if(!G)continue;let M=G.indexOf("\x00");if(M===-1)continue;let _=G.slice(0,M),O=G.slice(M+1);if(t5.some((H)=>H.test(_)))continue;if(!H6.test(_))continue;for(let H of V)if(O.includes(H)){let z=Y.get(H)||[];for(let N of z)if(N!==_){let j=Q.get(N);if(!j.includes(_))j.push(_)}}}}catch(J){}}return Q}async function L6($,Z,X=process.cwd(),Q=i5.readFile){try{let Y=await Q(L$.join(X,$),"utf-8"),K=L$.basename(Z,L$.extname(Z)),W=Y.split(`
|
|
27
|
+
`),q=[],V="";for(let U of W)if(U.includes(K)&&(U.trim().startsWith("import")||U.trim().startsWith("export"))){V=V?`${V}
|
|
28
|
+
${U.trim()}`:U.trim();let J=U.match(/\{([^}]+)\}/);if(J){let B=J[1].split(",").map((G)=>{return G.trim().split(" as ")[0].trim().replace(/^type\s+/,"")});q.push(...B)}if(!J&&U.trim().startsWith("import")){let B=U.split("from");if(B.length>1){let G=B[0].replace("import","").trim();if(G){let M=G.match(/\*\s+as\s+([A-Za-z0-9_$]+)/);if(M)q.push(M[1].trim());else if(!G.includes("{")&&!G.includes("*"))q.push(G.split(" as ")[0].trim())}}}}return{importedSymbols:q,usageContext:V}}catch(Y){return null}}function j6($){let Z=$?.cwd??process.cwd(),X=$?.exec??n5,Q=$?.readFile??i5.readFile;return{name:"impact",async analyze(Y){let K=[],W=Y.files.filter((U)=>{if(U.status!=="modified"&&U.status!=="renamed")return!1;if(t5.some((B)=>B.test(U.path)))return!1;let J=L$.extname(U.path).toLowerCase();return _6.has(J)});if(W.length===0)return[];let q=W.map((U)=>{let J=L$.extname(U.path),B=L$.basename(U.path,J);return{path:U.path,baseName:B}}),V=await z6(q,Z,X);for(let U of W){let J=V.get(U.path)||[];if(J.length>0){let B=[];for(let O of J)if(B.length<20){let H=await L6(O,U.path,Z,Q);if(H)B.push({file:O,details:H});else B.push({file:O,details:{importedSymbols:[],usageContext:""}})}else B.push({file:O,details:{importedSymbols:[],usageContext:""}});let G=J.length>10?"High":J.length>3?"Medium":"Low",M=[A(U.path,`${G} blast radius: ${J.length} file(s) depend on this module`),...B.slice(0,5).map((O)=>{let H=O.details.importedSymbols?.length>0?`Imports: ${O.details.importedSymbols.slice(0,3).join(", ")}${O.details.importedSymbols.length>3?` (+${O.details.importedSymbols.length-3} more)`:""}`:"Imports module";return A(O.file,H)})],_=new Set;B.forEach((O)=>O.details.importedSymbols?.forEach((H)=>_.add(H))),K.push({type:"impact-analysis",kind:"impact-analysis",category:"impact",confidence:"medium",evidence:M,sourceFile:U.path,affectedFiles:J,importedSymbols:Array.from(_),usageContext:B[0]?.details.usageContext,blastRadius:J.length>10?"high":J.length>3?"medium":"low",tags:["impact","dependency"]})}}return K}}}var t5,_6,H6,s;var e5=T(()=>{t5=[/node_modules/,/\.d\.ts$/,/^dist\//,/^build\//,/^\.git\//],_6=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".mts",".cts",".vue",".svelte"]),H6=/\.(js|jsx|ts|tsx|mjs|cjs|mts|cts|vue|svelte)$/i;s=j6()});var o;var $8=T(()=>{o={name:"large-diff",analyze($){let Z=[],X=$.files.length,Q=0;for(let Y of $.diffs)for(let K of Y.hunks)Q+=K.additions.length+K.deletions.length;if(X>30||Q>1000)Z.push({type:"large-diff",kind:"large-diff",category:"unknown",confidence:"high",evidence:[],filesChanged:X,linesChanged:Q});return Z}}});function Z8($){return $==="package.json"}function D6($){return $==="package-lock.json"||$==="yarn.lock"||$==="pnpm-lock.yaml"||$==="bun.lockb"||$==="bun.lock"}function T6($){let Z=$.match(/^\s*"([^"]+)"\s*:/);return Z?Z[1]:null}function x6($){if(!/^\s*"[^"]+"\s*:\s*"/.test($))return!1;let Z=T6($);if(Z&&A6.includes(Z))return!1;return R6.some((X)=>X.test($))}function E6($){for(let Z of $.hunks){let X=[...Z.additions,...Z.deletions];for(let Q of X){for(let Y of N6)if(Q.includes(Y))return!0;if(x6(Q))return!0}}return!1}var N6,A6,R6,i;var X8=T(()=>{N6=['"dependencies"','"devDependencies"','"peerDependencies"','"optionalDependencies"','"bundledDependencies"','"bundleDependencies"'],A6=["name","version","description","main","module","types","typings","exports","bin","scripts","repository","keywords","author","license","bugs","homepage","funding","files","engines","os","cpu","private","publishConfig","workspaces","packageManager","type","sideEffects","browser","unpkg","jsdelivr"],R6=[/"\s*[\^~>=<]?\d+\.\d+/,/"\s*[\*x]\s*"/,/"\s*\d+\.x/,/"\s*npm:/,/"\s*git(\+https?|\+ssh)?:/,/"\s*github:/,/"\s*(file|link):/,/"\s*workspace:/,/"\s*https?:\/\//];i={name:"lockfiles",analyze($){let Z=[],X=$.files.find((K)=>Z8(K.path)),Q=$.files.some((K)=>D6(K.path)),Y=!1;if(X){let K=$.diffs.find((W)=>Z8(W.path));if(K)Y=E6(K);else Y=X.status==="added"}if(Y&&!Q||!X&&Q)Z.push({type:"lockfile-mismatch",kind:"lockfile-mismatch",category:"dependencies",confidence:"high",evidence:[],manifestChanged:!!X,lockfileChanged:Q});return Z}}});function w6($){return $.includes("/tests/")||$.includes("/__tests__/")||$.includes(".test.")||$.includes(".spec.")||$.startsWith("tests/")}function I6($){return $.endsWith(".md")||$.startsWith("docs/")}function b6($){let Z=$.split("/").pop()||"";return Z==="package.json"||Z==="package-lock.json"||Z==="yarn.lock"||Z==="pnpm-lock.yaml"||Z==="bun.lockb"||Z.endsWith(".config.js")||Z.endsWith(".config.ts")||Z.endsWith(".config.mjs")||Z.endsWith(".config.cjs")||Z.endsWith(".toml")||$.split("/").length===1&&Z.startsWith(".")}var n;var Q8=T(()=>{n={name:"test-gaps",analyze($){let Z=[],X=0,Q=0,Y=[];for(let K of $.files){if(I6(K.path)||b6(K.path))continue;if(w6(K.path))Q++;else X++,Y.push(K.path)}if(X>=3&&Q===0){let K=Y.slice(0,5).map((W,q)=>A(W,q===0?`${X} production file(s) changed with no test updates`:"No corresponding test changes"));Z.push({type:"test-gap",kind:"test-gap",category:"quality",confidence:"medium",evidence:K,prodFilesChanged:X,testFilesChanged:Q})}return Z}}});function P6($){return $.includes("/migrations/")||$.includes("/migrate/")||$.endsWith(".sql")}var Y1;var Y8=T(()=>{Y1={name:"sql-risks",analyze($){let Z=[];for(let X of $.diffs){if(!P6(X.path))continue;for(let Q of X.hunks){let Y=Q.additions.join(`
|
|
29
|
+
`);if(/\b(DROP\s+TABLE|DROP\s+COLUMN|TRUNCATE)\b/gi.test(Y)){let V=F(Q.additions,200);Z.push({type:"sql-risk",kind:"sql-risk",category:"database",confidence:"high",evidence:[A(X.path,V,{hunk:Q})],file:X.path,riskType:"destructive",details:"Contains DROP TABLE/COLUMN or TRUNCATE"});continue}if(/ALTER\s+TABLE[^;]+\b(ALTER\s+COLUMN|TYPE)\b/gi.test(Y)){let V=F(Q.additions,200);Z.push({type:"sql-risk",kind:"sql-risk",category:"database",confidence:"high",evidence:[A(X.path,V,{hunk:Q})],file:X.path,riskType:"schema_change",details:"Contains ALTER COLUMN or TYPE change"});continue}if(/(UPDATE|DELETE)\s+(?![^;\n]*\bWHERE\b)/gi.test(Y)){let V=F(Q.additions,200);Z.push({type:"sql-risk",kind:"sql-risk",category:"database",confidence:"medium",evidence:[A(X.path,V,{hunk:Q})],file:X.path,riskType:"unscoped_modification",details:"Contains UPDATE/DELETE without WHERE clause"})}}}return Z}}});function C6($){return $.includes(".github/workflows/")&&($.endsWith(".yml")||$.endsWith(".yaml"))||$===".gitlab-ci.yml"||$==="Jenkinsfile"||$==="azure-pipelines.yml"}var t;var K8=T(()=>{t={name:"ci-workflows",analyze($){let Z=[],X=new Set;for(let Q of $.diffs){if(!C6(Q.path))continue;let Y=!1,K=!1,W=!1;for(let q of Q.hunks){let V=q.additions.join(`
|
|
30
|
+
`);if(!Y&&/permissions:[\s\S]{0,500}?\b(contents|id-token|actions|packages|deployments|security-events)\b\s*:\s*write/gi.test(V)){Y=!0;let G=F(q.additions,200);Z.push({type:"ci-workflow",kind:"ci-workflow",category:"ci",confidence:"high",evidence:[A(Q.path,G,{hunk:q})],file:Q.path,riskType:"permissions_broadened",details:"Workflow has broadened permissions (write access)"})}if(!K&&/pull_request_target/i.test(V)){K=!0;let G=F(q.additions,200);Z.push({type:"ci-workflow",kind:"ci-workflow",category:"ci",confidence:"high",evidence:[A(Q.path,G,{hunk:q})],file:Q.path,riskType:"pull_request_target",details:"Workflow uses pull_request_target event (can expose secrets)"})}if(!W&&/(curl|wget)\s+[^\s]+\s*\|\s*(sh|bash)/gi.test(V)){W=!0;let G=F(q.additions,200);Z.push({type:"ci-workflow",kind:"ci-workflow",category:"ci",confidence:"high",evidence:[A(Q.path,G,{hunk:q})],file:Q.path,riskType:"remote_script_download",details:"Workflow downloads and pipes to shell (supply chain risk)"})}}if(!X.has(Q.path)&&Q.hunks.length>0){X.add(Q.path);let q=F(Q.hunks[0].additions,150);Z.push({type:"ci-workflow",kind:"ci-workflow",category:"ci",confidence:"medium",evidence:[A(Q.path,q)],file:Q.path,riskType:"pipeline_changed",details:"CI/CD pipeline configuration modified"})}}return Z}}});var K1;var q8=T(()=>{K1={name:"infra",analyze($){let Z=[],X=[],Q=[],Y=[];for(let K of $.files)if(K.path.toLowerCase().includes("dockerfile"))X.push(K.path);else if(K.path.endsWith(".tf")||K.path.endsWith(".tfvars"))Q.push(K.path);else if(K.path.includes("kubernetes/")||K.path.includes("k8s/")||K.path.endsWith(".yaml")&&(K.path.includes("deployment")||K.path.includes("service")||K.path.includes("ingress")))Y.push(K.path);if(X.length>0)Z.push({type:"infra-change",kind:"infra-change",category:"infra",confidence:"high",evidence:[],infraType:"dockerfile",files:X});if(Q.length>0)Z.push({type:"infra-change",kind:"infra-change",category:"infra",confidence:"high",evidence:[],infraType:"terraform",files:Q});if(Y.length>0)Z.push({type:"infra-change",kind:"infra-change",category:"infra",confidence:"high",evidence:[],infraType:"k8s",files:Y});return Z}}});function S6($){return $.includes("openapi")||$.includes("swagger")||$.endsWith(".proto")||$.includes("/api/")&&($.endsWith(".yaml")||$.endsWith(".yml")||$.endsWith(".json"))}var e;var W8=T(()=>{e={name:"api-contracts",analyze($){let Z=[],X=$.files.filter((Q)=>S6(Q.path)).map((Q)=>Q.path);if(X.length>0)Z.push({type:"api-contract-change",kind:"api-contract-change",category:"api",confidence:"high",evidence:[],files:X});return Z}}});import{parse as k6}from"@babel/parser";import U8 from"@babel/traverse";import*as I from"@babel/types";function v6($){return $.endsWith(".tsx")||$.endsWith(".ts")}function V8($){if($==="default")return"<slot />";else if($==="boolean")return"<slot name />";else if($==="dynamic")return"<slot name={...} />";else return`<slot name="${$}" />`}function J8($,Z){let X=[];try{let Q=k6($,{sourceType:"module",plugins:["typescript","jsx","decorators-legacy"]});U8(Q,{ClassDeclaration(Y){let W=(Y.node.decorators||[]).find((_)=>I.isCallExpression(_.expression)&&I.isIdentifier(_.expression.callee)&&_.expression.callee.name==="Component");if(!W)return;let q="",V=!1,U=Y.node.loc?.start.line??1;if(I.isCallExpression(W.expression)){let _=W.expression.arguments[0];if(I.isObjectExpression(_)){for(let O of _.properties)if(I.isObjectProperty(O)&&I.isIdentifier(O.key)){if(O.key.name==="tag"){if(I.isStringLiteral(O.value))q=O.value.value}else if(O.key.name==="shadow"){if(I.isBooleanLiteral(O.value))V=O.value.value}}}}if(!q)return;let J=new Map,B=new Map,G=new Map,M=new Set;for(let _ of Y.node.body.body){if(I.isClassProperty(_)||I.isClassMethod(_)){let O=_.decorators||[],H=O.find((j)=>I.isCallExpression(j.expression)&&I.isIdentifier(j.expression.callee)&&j.expression.callee.name==="Prop"||I.isIdentifier(j.expression)&&j.expression.name==="Prop");if(H&&I.isIdentifier(_.key)){let j=_.key.name,E=_.loc?.start.line??1,x,R=!1,b=!1,w;if(I.isClassProperty(_)&&_.typeAnnotation&&I.isTSTypeAnnotation(_.typeAnnotation));if(I.isCallExpression(H.expression)){let p=H.expression.arguments[0];if(I.isObjectExpression(p)){for(let P of p.properties)if(I.isObjectProperty(P)&&I.isIdentifier(P.key)){if(P.key.name==="attribute"&&I.isStringLiteral(P.value))x=P.value.value;if(P.key.name==="reflect"&&I.isBooleanLiteral(P.value))R=P.value.value;if(P.key.name==="mutable"&&I.isBooleanLiteral(P.value))b=P.value.value}}}J.set(j,{name:j,attribute:x,reflect:R,mutable:b,typeText:w,line:E})}let z=O.find((j)=>I.isCallExpression(j.expression)&&I.isIdentifier(j.expression.callee)&&j.expression.callee.name==="Event"||I.isIdentifier(j.expression)&&j.expression.name==="Event");if(z&&I.isIdentifier(_.key)){let j=_.key.name,E=j,x=_.loc?.start.line??1,R=!0,b=!0,w=!0;if(I.isCallExpression(z.expression)){let p=z.expression.arguments[0];if(I.isObjectExpression(p)){for(let P of p.properties)if(I.isObjectProperty(P)&&I.isIdentifier(P.key)){if(P.key.name==="eventName"&&I.isStringLiteral(P.value))E=P.value.value;if(P.key.name==="bubbles"&&I.isBooleanLiteral(P.value))R=P.value.value;if(P.key.name==="composed"&&I.isBooleanLiteral(P.value))b=P.value.value;if(P.key.name==="cancelable"&&I.isBooleanLiteral(P.value))w=P.value.value}}}B.set(E,{name:E,memberName:j,bubbles:R,composed:b,cancelable:w,line:x})}if(O.find((j)=>I.isCallExpression(j.expression)&&I.isIdentifier(j.expression.callee)&&j.expression.callee.name==="Method"||I.isIdentifier(j.expression)&&j.expression.name==="Method")&&I.isIdentifier(_.key)){let j=_.key.name,E=_.loc?.start.line??1;G.set(j,{name:j,line:E})}}if(I.isClassMethod(_)&&I.isIdentifier(_.key)&&_.key.name==="render")U8(_,{JSXElement(O){let H=O.node.openingElement;if(I.isJSXIdentifier(H.name)&&H.name.name==="slot"){let z="default";for(let N of H.attributes)if(I.isJSXAttribute(N)&&I.isJSXIdentifier(N.name)&&N.name.name==="name")if(I.isStringLiteral(N.value))z=N.value.value;else if(N.value===null)z="boolean";else z="dynamic";M.add(z)}}},Y.scope,Y)}X.push({tag:q,shadow:V,file:Z,line:U,props:J,events:B,methods:G,slots:M})}})}catch(Q){}return X}var F6,U2;var B8=T(()=>{U0();F6={batchGetFileContent:z$};U2={name:"stencil",async analyze($){let Z=[],X=$.files.filter((K)=>v6(K.path));if(X.length===0)return[];let Q=[];for(let K of X)Q.push({ref:$.base,path:K.path}),Q.push({ref:$.head,path:K.path});let Y=await F6.batchGetFileContent(Q);for(let K of X){let W=`${$.base}:${K.path}`,q=`${$.head}:${K.path}`,V=Y.get(W),U=Y.get(q);if(!V&&!U)continue;let J=V?J8(V,K.path):[],B=U?J8(U,K.path):[],G=new Map(J.map((O)=>[O.tag,O])),M=new Map(B.map((O)=>[O.tag,O])),_=new Set([...G.keys(),...M.keys()]);for(let O of _){let H=G.get(O),z=M.get(O);if(H&&!z)Z.push({type:"stencil-component-change",kind:"stencil-component-change",category:"api",confidence:"high",evidence:[A(K.path,`@Component({ tag: "${O}" })`,{line:H.line})],tag:O,change:"removed",file:K.path});else if(!H&&z)Z.push({type:"stencil-component-change",kind:"stencil-component-change",category:"api",confidence:"high",evidence:[A(K.path,`@Component({ tag: "${O}" })`,{line:z.line})],tag:O,change:"added",file:K.path});else if(H&&z){if(H.shadow!==z.shadow)Z.push({type:"stencil-component-change",kind:"stencil-component-change",category:"api",confidence:"high",evidence:[A(K.path,`@Component({ tag: "${O}", shadow: ${z.shadow} })`,{line:z.line})],tag:O,change:"shadow-changed",file:K.path,fromShadow:H.shadow,toShadow:z.shadow});let N=new Set([...H.props.keys(),...z.props.keys()]);for(let R of N){let b=H.props.get(R),w=z.props.get(R);if(b&&!w)Z.push({type:"stencil-prop-change",kind:"stencil-prop-change",category:"api",confidence:"high",evidence:[A(K.path,`@Prop() ${R}`,{line:b.line})],tag:O,propName:R,change:"removed",file:K.path});else if(!b&&w)Z.push({type:"stencil-prop-change",kind:"stencil-prop-change",category:"api",confidence:"high",evidence:[A(K.path,`@Prop() ${R}`,{line:w.line})],tag:O,propName:R,change:"added",file:K.path,details:{attribute:w.attribute,reflect:w.reflect,mutable:w.mutable}});else if(b&&w){if(b.attribute!==w.attribute||b.reflect!==w.reflect||b.mutable!==w.mutable)Z.push({type:"stencil-prop-change",kind:"stencil-prop-change",category:"api",confidence:"high",evidence:[A(K.path,`@Prop() ${R}`,{line:w.line})],tag:O,propName:R,change:"changed",file:K.path,details:{attribute:w.attribute,reflect:w.reflect,mutable:w.mutable}})}}let j=new Set([...H.events.keys(),...z.events.keys()]);for(let R of j){let b=H.events.get(R),w=z.events.get(R);if(b&&!w)Z.push({type:"stencil-event-change",kind:"stencil-event-change",category:"api",confidence:"high",evidence:[A(K.path,`@Event() ${b.memberName}`,{line:b.line})],tag:O,eventName:R,change:"removed",file:K.path});else if(!b&&w)Z.push({type:"stencil-event-change",kind:"stencil-event-change",category:"api",confidence:"high",evidence:[A(K.path,`@Event() ${w.memberName}`,{line:w.line})],tag:O,eventName:R,change:"added",file:K.path,details:{bubbles:w.bubbles,composed:w.composed,cancelable:w.cancelable}});else if(b&&w){if(b.bubbles!==w.bubbles||b.composed!==w.composed||b.cancelable!==w.cancelable)Z.push({type:"stencil-event-change",kind:"stencil-event-change",category:"api",confidence:"high",evidence:[A(K.path,`@Event() ${w.memberName}`,{line:w.line})],tag:O,eventName:R,change:"changed",file:K.path,details:{bubbles:w.bubbles,composed:w.composed,cancelable:w.cancelable}})}}let E=new Set([...H.methods.keys(),...z.methods.keys()]);for(let R of E){let b=H.methods.get(R),w=z.methods.get(R);if(b&&!w)Z.push({type:"stencil-method-change",kind:"stencil-method-change",category:"api",confidence:"high",evidence:[A(K.path,`@Method() ${R}`,{line:b.line})],tag:O,methodName:R,change:"removed",file:K.path});else if(!b&&w)Z.push({type:"stencil-method-change",kind:"stencil-method-change",category:"api",confidence:"high",evidence:[A(K.path,`@Method() ${R}`,{line:w.line})],tag:O,methodName:R,change:"added",file:K.path})}let x=new Set([...H.slots,...z.slots]);for(let R of x){let b=H.slots.has(R),w=z.slots.has(R);if(b&&!w)Z.push({type:"stencil-slot-change",kind:"stencil-slot-change",category:"api",confidence:"high",evidence:[A(K.path,V8(R),{line:H.line})],tag:O,slotName:R,change:"removed",file:K.path});else if(!b&&w)Z.push({type:"stencil-slot-change",kind:"stencil-slot-change",category:"api",confidence:"high",evidence:[A(K.path,V8(R),{line:z.line})],tag:O,slotName:R,change:"added",file:K.path})}}}}return Z}}});function G8($){if(!$.startsWith("app/")&&!$.startsWith("src/app/"))return!1;return h6($)}function h6($){let Z=$.split("/").pop()??"";return Object.keys(O8).includes(Z)}function u6($){let Z=$.split("/").pop()??"";return O8[Z]??"unknown"}function g6($){let Z=$.replace(/^src\/app/,"").replace(/^app/,""),X=Z.split("/");if(X.pop(),Z=X.join("/"),Z=Z.replace(/\/\([^)]+\)/g,""),Z===""||Z==="/")return"/";if(!Z.startsWith("/"))Z="/"+Z;if(Z.length>1&&Z.endsWith("/"))Z=Z.slice(0,-1);return Z}function f6($){let Z=new Set,X=S($).join(`
|
|
31
|
+
`),Q,Y=new RegExp(m6.source,"g");while((Q=Y.exec(X))!==null)Z.add(Q[1]);return Array.from(Z).sort()}function l6($){return y6.includes($)}var O8,y6,m6,V2;var J2=T(()=>{O8={"page.tsx":"page","page.ts":"page","page.jsx":"page","page.js":"page","layout.tsx":"layout","layout.ts":"layout","layout.jsx":"layout","layout.js":"layout","loading.tsx":"page","loading.ts":"page","loading.jsx":"page","loading.js":"page","error.tsx":"error","error.ts":"error","error.jsx":"error","error.js":"error","not-found.tsx":"error","not-found.ts":"error","not-found.jsx":"error","not-found.js":"error","route.ts":"endpoint","route.tsx":"endpoint","route.js":"endpoint","route.jsx":"endpoint"},y6=["middleware.ts","middleware.js","middleware.tsx","middleware.jsx","src/middleware.ts","src/middleware.js","src/middleware.tsx","src/middleware.jsx"],m6=/export\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s*\(/g;V2={name:"next-routes",analyze($){let Z=[],X=new Map;for(let Q of $.files){if(G8(Q.path))X.set(Q.path,{status:Q.status});if(l6(Q.path)){let Y=$.diffs.find((q)=>q.path===Q.path),K=[];if(Y&&Y.hunks.length>0){let q=S(Y);if(q.length>0){let V=F(q);if(V)K.push(A(Q.path,V))}}let W={type:"security-file",kind:"security-file",category:"routes",confidence:"high",evidence:K,files:[Q.path],reasons:["middleware"]};Z.push(W)}}for(let Q of $.diffs)if(G8(Q.path)){let Y=X.get(Q.path);if(Y)Y.diff=Q;else X.set(Q.path,{diff:Q,status:Q.status})}for(let[Q,{diff:Y,status:K}]of X){let W=g6(Q),q=u6(Q),V=[];if(Y&&Y.hunks.length>0){let J=S(Y);if(J.length>0){let B=F(J);if(B)V.push(A(Q,B))}}let U={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:V,routeId:W,file:Q,change:K,routeType:q};if(q==="endpoint"&&Y){let J=f6(Y);if(J.length>0){U.methods=J;let B=J.map((G)=>`export function ${G}`).join(", ");if(!V.length)V.push(A(Q,B))}}Z.push(U)}return Z}}});function p6($){return c6.some((Z)=>Z.test($))}function d6($){let Z=[],X=$.join(`
|
|
32
|
+
`),Q=X.match(/type\s+(\w+)\s*[{@]/g);if(Q)for(let q of Q){let V=q.match(/type\s+(\w+)/)?.[1];if(V)Z.push(`Removed type: ${V}`)}let Y=X.match(/enum\s+(\w+)\s*{/g);if(Y)for(let q of Y){let V=q.match(/enum\s+(\w+)/)?.[1];if(V)Z.push(`Removed enum: ${V}`)}let K=X.match(/interface\s+(\w+)\s*[{@]/g);if(K)for(let q of K){let V=q.match(/interface\s+(\w+)/)?.[1];if(V)Z.push(`Removed interface: ${V}`)}let W=X.match(/input\s+(\w+)\s*{/g);if(W)for(let q of W){let V=q.match(/input\s+(\w+)/)?.[1];if(V)Z.push(`Removed input type: ${V}`)}return Z}function r6($){let Z=[],X=$.join(`
|
|
33
|
+
`),Q=X.match(/type\s+(\w+)\s*[{@]/g);if(Q)for(let K of Q){let W=K.match(/type\s+(\w+)/)?.[1];if(W&&!["Query","Mutation","Subscription"].includes(W))Z.push(`Added type: ${W}`)}let Y=X.match(/enum\s+(\w+)\s*{/g);if(Y)for(let K of Y){let W=K.match(/enum\s+(\w+)/)?.[1];if(W)Z.push(`Added enum: ${W}`)}return Z}var c6,v$;var B2=T(()=>{c6=[/\.graphql$/,/\.gql$/,/schema\.graphqls$/,/schema\.sdl$/];v$={name:"graphql",analyze($){let Z=[];for(let X of $.diffs){if(!p6(X.path))continue;let Q=S(X),Y=z1(X),K=d6(Y),W=r6(Q),q=K.length>0,V=W.length>0,U=Y.length>0,J=q?F(Y):F(Q),B="medium";if(q)B="high";else if(V&&!U)B="low";let G={type:"graphql-change",kind:"graphql-change",category:"api",confidence:B,evidence:[A(X.path,J)],file:X.path,status:X.status,isBreaking:q,breakingChanges:K.slice(0,5),addedElements:W.slice(0,5)};Z.push(G)}return Z}}});function i6($){return a6.some((Z)=>Z.test($))}function n6($,Z){let X=[],Q=[],Y=[],K=/"(\w+)":\s*/,W=new Set,q=new Set;for(let V of $){let U=V.match(K);if(U)W.add(U[1])}for(let V of Z){let U=V.match(K);if(U)q.add(U[1])}for(let V of W)if(q.has(V))Y.push(V);else X.push(V);for(let V of q)if(!W.has(V))Q.push(V);return{added:X,removed:Q,modified:Y}}function t6($,Z,X){for(let Q of[...$,...Z,...X])if(s6.has(Q))return!0;return!1}function e6($,Z,X){let Q=[],Y=[...$,...Z,...X];for(let K of Y)if(o6.has(K))if($.includes(K))Q.push(`Added ${K}`);else if(Z.includes(K))Q.push(`Removed ${K}`);else Q.push(`Modified ${K}`);return Q}var a6,s6,o6,L1;var f1=T(()=>{a6=[/^tsconfig\.json$/,/^tsconfig\.\w+\.json$/,/\/tsconfig\.json$/,/\/tsconfig\.\w+\.json$/],s6=new Set(["strict","strictNullChecks","strictFunctionTypes","strictBindCallApply","strictPropertyInitialization","noImplicitAny","noImplicitThis","noImplicitReturns","noUncheckedIndexedAccess","target","module","moduleResolution","lib","jsx","esModuleInterop","allowSyntheticDefaultImports","skipLibCheck","isolatedModules","verbatimModuleSyntax","baseUrl","paths","outDir","rootDir","declaration","declarationMap","sourceMap","composite","incremental","emitDecoratorMetadata","experimentalDecorators"]),o6=new Set(["strict","strictNullChecks","strictFunctionTypes","strictBindCallApply","strictPropertyInitialization","noImplicitAny","noImplicitThis","noImplicitReturns","noUncheckedIndexedAccess","noUnusedLocals","noUnusedParameters","exactOptionalPropertyTypes"]);L1={name:"typescript-config",analyze($){let Z=[];for(let X of $.diffs){if(!i6(X.path))continue;let Q=S(X),Y=z1(X),{added:K,removed:W,modified:q}=n6(Q,Y);if(K.length===0&&W.length===0&&q.length===0){if(Q.length>0||Y.length>0){let M={type:"typescript-config",kind:"typescript-config",category:"config_env",confidence:"low",evidence:[A(X.path,F(Q.length>0?Q:Y))],file:X.path,status:X.status,isBreaking:!1,changedOptions:{added:[],removed:[],modified:[]},strictnessChanges:[]};Z.push(M)}continue}let V=t6(K,W,q),U=e6(K,W,q),J=V?"high":"medium",B=F(Q.length>0?Q:Y),G={type:"typescript-config",kind:"typescript-config",category:"config_env",confidence:J,evidence:[A(X.path,B)],file:X.path,status:X.status,isBreaking:V,changedOptions:{added:K,removed:W,modified:q},strictnessChanges:U};Z.push(G)}return Z}}});function Y3($){return $3.some((Z)=>Z.test($))}function K3($){return Z3.some((Z)=>Z.test($))}function q3($){let Z=new Set,X=$.join(`
|
|
34
|
+
`);for(let Q of X3)if(new RegExp(`\\b${Q}\\s*[:{]`,"i").test(X))Z.add(Q);for(let Q of Q3)if(new RegExp(`\\b${Q}\\s*[:{]`,"i").test(X))Z.add(`theme.${Q}`);return Array.from(Z)}function W3($,Z){let X=[],Q=$.join(`
|
|
35
|
+
`),Y=Z.join(`
|
|
36
|
+
`);if(/\bcontent\s*[:{]/.test(Y)||/\bcontent\s*[:{]/.test(Q)){if(Z.length>0)X.push("Content paths modified (may affect CSS purging)")}if(/\bprefix\s*[:{]/.test(Y)&&/\bprefix\s*[:{]/.test(Q))X.push("Class prefix changed (requires updating all class names)");if(/colors\s*[:{]/.test(Y))X.push("Theme colors modified (may break existing color classes)");if(/screens\s*[:{]/.test(Y))X.push("Screen breakpoints modified (may affect responsive design)");if(/plugins\s*[:{]/.test(Y)&&Z.some((K)=>K.includes("require(")))X.push("Plugins removed (may remove utility classes)");if(/darkMode\s*[:{]/.test(Y)||/darkMode\s*[:{]/.test(Q))X.push("Dark mode configuration changed");return{isBreaking:X.length>0,reasons:X}}var $3,Z3,X3,Q3,j1;var l1=T(()=>{$3=[/^tailwind\.config\.(js|cjs|mjs|ts)$/,/\/tailwind\.config\.(js|cjs|mjs|ts)$/],Z3=[/^postcss\.config\.(js|cjs|mjs)$/,/\/postcss\.config\.(js|cjs|mjs)$/],X3=["theme","content","plugins","presets","prefix","important","darkMode","safelist"],Q3=["colors","spacing","screens","fontFamily","fontSize","fontWeight","extend","borderRadius","boxShadow","animation","keyframes"];j1={name:"tailwind",analyze($){let Z=[];for(let X of $.diffs){let Q=Y3(X.path),Y=K3(X.path);if(!Q&&!Y)continue;let K=S(X),W=z1(X),q=q3([...K,...W]),{isBreaking:V,reasons:U}=W3(K,W),J=V?"high":q.length>0?"medium":"low",B=F(K.length>0?K:W),G={type:"tailwind-config",kind:"tailwind-config",category:"config_env",confidence:J,evidence:[A(X.path,B)],file:X.path,status:X.status,configType:Q?"tailwind":"postcss",isBreaking:V,affectedSections:q,breakingReasons:U};Z.push(G)}return Z}}});function J3($){for(let[Z,X]of Object.entries(U3))if(X.some((Q)=>Q.test($))){if(Z==="npm"&&!$.endsWith("package.json"))continue;return Z}return null}function B3($,Z){let X=[...$,...Z].join(`
|
|
37
|
+
`);return/["']workspaces["']/.test(X)}function G3($,Z){let X=V3[Z]||[],Q=[],Y=$.join(`
|
|
38
|
+
`);for(let K of X)if(new RegExp(`["']?${K}["']?\\s*[:{[]`,"i").test(Y))Q.push(K);return Q}function O3($,Z,X){let Q=[],Y=Z.join(`
|
|
39
|
+
`),K=X.join(`
|
|
40
|
+
`);switch($){case"turborepo":if(/pipeline|tasks/.test(K))Q.push("Build pipeline configuration changed");if(/cache\s*[:=]\s*false/.test(Y))Q.push("Caching disabled for tasks");if(/globalDependencies/.test(Y)||/globalDependencies/.test(K))Q.push("Global dependencies changed (affects cache invalidation)");break;case"pnpm":if(/packages/.test(K))Q.push("Workspace packages configuration changed");break;case"lerna":if(/version/.test(Y)&&/independent/.test(Y))Q.push("Switching to independent versioning");if(/npmClient/.test(Y)||/npmClient/.test(K))Q.push("npm client configuration changed");break;case"nx":if(/targetDefaults/.test(K))Q.push("Default target configuration changed");if(/plugins/.test(Y)||/plugins/.test(K))Q.push("Nx plugins configuration changed");break;case"yarn":if(/nodeLinker/.test(Y)||/nodeLinker/.test(K))Q.push("Node linker strategy changed (affects dependency resolution)");break;case"npm":if(/workspaces/.test(K))Q.push("Workspace packages configuration changed");break;case"changesets":if(/baseBranch/.test(Y)||/baseBranch/.test(K))Q.push("Base branch for changesets modified");if(/access/.test(Y))Q.push("Package publish access level changed");break}return Q}var U3,V3,G2;var O2=T(()=>{U3={turborepo:[/^turbo\.json$/],pnpm:[/^pnpm-workspace\.yaml$/,/^pnpm-workspace\.yml$/],lerna:[/^lerna\.json$/],nx:[/^nx\.json$/,/^project\.json$/],yarn:[/^\.yarnrc\.yml$/,/^\.yarnrc$/],npm:[/^package\.json$/],changesets:[/^\.changeset\/config\.json$/]},V3={turborepo:["pipeline","globalDependencies","globalEnv","tasks"],pnpm:["packages"],lerna:["packages","version","npmClient","useWorkspaces"],nx:["targetDefaults","namedInputs","plugins","defaultProject"],yarn:["nodeLinker","enableGlobalCache","nmMode"],npm:["workspaces"],changesets:["baseBranch","access","changelog"]};G2={name:"monorepo",analyze($){let Z=[];for(let X of $.diffs){let Q=J3(X.path);if(!Q)continue;let Y=S(X),K=z1(X);if(Q==="npm"&&!B3(Y,K))continue;let W=G3([...Y,...K],Q),q=O3(Q,Y,K);if(W.length===0&&q.length===0)continue;let U=q.length>0?"high":"medium",J=F(Y.length>0?Y:K),B={type:"monorepo-config",kind:"monorepo-config",category:"config_env",confidence:U,evidence:[A(X.path,J)],file:X.path,status:X.status,tool:Q,affectedFields:W,impacts:q};Z.push(B)}return Z}}});function B0($,Z=""){if(!$)return[];if(typeof $==="string")return[Z||"."];if(typeof $==="object"){let X=[];for(let[Q,Y]of Object.entries($))if(Q.startsWith("."))X.push(...B0(Y,Q));else if(typeof Y==="string"||typeof Y==="object")X.push(...B0(Y,Z));return[...new Set(X)]}return[]}function M3($,Z){let X=B0($),Q=B0(Z),Y=new Set(X),K=new Set(Q),W=Q.filter((V)=>!Y.has(V)),q=X.filter((V)=>!K.has(V));return{added:W,removed:q,hasExportsField:{base:$!==void 0&&$!==null,head:Z!==void 0&&Z!==null}}}function _3($,Z){let X=["main","module","types","typings","browser"],Q=[];for(let Y of X){let K=$?.[Y],W=Z?.[Y];if(K!==W)Q.push({field:Y,from:K,to:W})}return Q}function H3($,Z){let X=$?.bin,Q=Z?.bin,Y=(q)=>{if(typeof q==="string")return["(default)"];if(typeof q==="object"&&q!==null)return Object.keys(q);return[]},K=new Set(Y(X)),W=new Set(Y(Q));return{added:[...W].filter((q)=>!K.has(q)),removed:[...K].filter((q)=>!W.has(q))}}var M2;var _2=T(()=>{M2={name:"package-exports",analyze($){let Z=[],X=$.basePackageJson,Q=$.headPackageJson;if(!X&&!Q)return Z;let Y=X?.exports,K=Q?.exports,W=M3(Y??null,K??null),q=_3(X,Q),V=H3(X,Q),U=W.removed.length>0,J=V.removed.length>0,B=q.some((j)=>j.from!==void 0&&j.to===void 0),G=U||J||B,M=W.added.length>0||W.removed.length>0,_=q.length>0,O=V.added.length>0||V.removed.length>0;if(!M&&!_&&!O)return Z;let H="medium";if(G)H="high";else if(W.added.length>0||V.added.length>0)H="low";let z=[];if(W.removed.length>0)z.push(`Removed exports: ${W.removed.slice(0,3).join(", ")}`);if(W.added.length>0)z.push(`Added exports: ${W.added.slice(0,3).join(", ")}`);if(q.length>0)z.push(`Changed fields: ${q.map((j)=>j.field).join(", ")}`);if(V.removed.length>0)z.push(`Removed bins: ${V.removed.join(", ")}`);if(V.added.length>0)z.push(`Added bins: ${V.added.join(", ")}`);let N={type:"package-exports",kind:"package-exports",category:"api",confidence:H,evidence:[A("package.json",z.join("; "))],isBreaking:G,addedExports:W.added,removedExports:W.removed,legacyFieldChanges:q,binChanges:{added:V.added,removed:V.removed}};return Z.push(N),Z}}});function D3($){return M8.test($)}function _8($){return z3.test($)}function H8($){return L3.test($)}function N3($){return j3.some((Z)=>Z.test($))}function A3($){let Z=$.match(M8);if(!Z)return $;let X=Z[2];return X=X.replace(/\.(get|post|put|delete|patch)$/i,""),X=X.replace(/\/index$/,"").replace(/^index$/,"").replace(/\[\.\.\.(\w+)\]/g,":$1*").replace(/\[(\w+)\]/g,":$1"),"/"+X}function R3($){let Z=[],X=$.match(/\.(\w+)\.(ts|js)$/);if(X){let Q=X[1].toUpperCase();if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].includes(Q))Z.push(Q)}if(Z.length===0)Z.push("*");return Z}function T3($){if(_8($))return"endpoint";if(H8($))return"layout";if($.includes("error.vue")||$.includes("404.vue")||$.includes("500.vue"))return"error";return"page"}var M8,z3,L3,j3,H2;var z2=T(()=>{M8=/^(pages|src\/pages)\/(.+)\.(vue|ts|tsx|js|jsx)$/,z3=/^server\/(api|routes|middleware)\/(.+)\.(ts|js)$/,L3=/^(layouts|src\/layouts)\/(.+)\.vue$/,j3=[/router\.(ts|js)$/,/routes\.(ts|js)$/,/router\/index\.(ts|js)$/];H2={name:"vue-routes",analyze($){let Z=[];for(let X of $.files){let Q=D3(X.path),Y=_8(X.path),K=H8(X.path),W=N3(X.path);if(!Q&&!Y&&!K&&!W)continue;if(W){let O=$.diffs.find((j)=>j.path===X.path),H=O?S(O):[],z=F(H),N={type:"route-change",kind:"route-change",category:"routes",confidence:"medium",evidence:[A(X.path,z||"Vue Router config changed")],routeId:"vue-router-config",file:X.path,change:X.status,routeType:"unknown"};Z.push(N);continue}let q=Q?A3(X.path):X.path,V=T3(X.path),U=Y?R3(X.path):void 0,J=$.diffs.find((O)=>O.path===X.path),B=J?S(J):[],G=F(B),M=[];if(G)M.push(A(X.path,G));let _={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:M,routeId:q,file:X.path,change:X.status,routeType:V,methods:U};Z.push(_)}return Z}}});function I3($){return L2.test($)}function z8($){return L2.test($)&&/\.(ts|js)$/.test($)}function L8($){return x3.test($)}function b3($){return E3.test($)}function P3($){return w3.test($)}function C3($){let Z=$.match(L2);if(!Z)return $;let X=Z[1];return X=X.replace(/\.(astro|md|mdx|html|ts|js)$/,""),X=X.replace(/\/index$/,"").replace(/^index$/,"").replace(/\[\.\.\.(\w+)\]/g,":$1*").replace(/\[(\w+)\]/g,":$1"),"/"+X}function S3($){let Z=[],X=$.join(`
|
|
41
|
+
`),Q=[{pattern:/export\s+(const|function|async function)\s+GET\b/,method:"GET"},{pattern:/export\s+(const|function|async function)\s+POST\b/,method:"POST"},{pattern:/export\s+(const|function|async function)\s+PUT\b/,method:"PUT"},{pattern:/export\s+(const|function|async function)\s+DELETE\b/,method:"DELETE"},{pattern:/export\s+(const|function|async function)\s+PATCH\b/,method:"PATCH"},{pattern:/export\s+(const|function|async function)\s+ALL\b/,method:"*"}];for(let{pattern:Y,method:K}of Q)if(Y.test(X))Z.push(K);return Z}function k3($){if(L8($))return"layout";if(z8($))return"endpoint";if($.includes("404.")||$.includes("500."))return"error";return"page"}var L2,x3,E3,w3,j2;var D2=T(()=>{L2=/^src\/pages\/(.+)\.(astro|md|mdx|html|ts|js)$/,x3=/^src\/layouts\/(.+)\.astro$/,E3=/^src\/content\/(.+)\.(md|mdx|json|yaml|yml)$/,w3=/^astro\.config\.(mjs|ts|js)$/;j2={name:"astro-routes",analyze($){let Z=[];for(let X of $.files){let Q=I3(X.path),Y=L8(X.path),K=b3(X.path),W=P3(X.path);if(!Q&&!Y&&!K&&!W)continue;let q=$.diffs.find((H)=>H.path===X.path),V=q?S(q):[],U=F(V);if(W){let H={type:"route-change",kind:"route-change",category:"routes",confidence:"medium",evidence:[A(X.path,U||"Astro config changed")],routeId:"astro-config",file:X.path,change:X.status,routeType:"unknown"};Z.push(H);continue}if(K){let H={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:U?[A(X.path,U)]:[],routeId:X.path.replace(/^src\/content\//,"/content/"),file:X.path,change:X.status,routeType:"page",tags:["content-collection"]};Z.push(H);continue}let J=Q?C3(X.path):X.path,B=k3(X.path),G=z8(X.path)?S3(V):[],M=G.length>0?G:void 0,_=[];if(U)_.push(A(X.path,U));let O={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:_,routeId:J,file:X.path,change:X.status,routeType:B,methods:M};Z.push(O)}return Z}}});function v3($){let Z=$.split("/").pop()??"";return j8.test(Z)||D8.test(Z)||N8.test(Z)||A8.test(Z)||R8.test(Z)}function y3($){let Z=$.split("/").pop()??"";if(j8.test(Z))return"requirements";if(D8.test(Z))return"pyproject";if(N8.test(Z))return"setup";if(A8.test(Z))return"pipfile";if(R8.test(Z))return"poetry";return"unknown"}function T8($){let Z=$.trim();if(!Z||Z.startsWith("#")||Z.startsWith("-"))return null;if(Z.startsWith("-r "))return null;let X=Z.match(/^([a-zA-Z0-9_-]+)(?:\[[^\]]+\])?(?:[><=~!]+(.+))?/);if(X)return{name:X[1].toLowerCase(),version:X[2]?.trim()};return null}function x8($){let Z=$.match(/["']([a-zA-Z0-9_-]+)(?:\[[^\]]+\])?(?:[><=~!]+([^"']+))?["']/);if(Z)return{name:Z[1].toLowerCase(),version:Z[2]?.trim()};let X=$.match(/^([a-zA-Z0-9_-]+)\s*=/);if(X)return{name:X[1].toLowerCase(),version:void 0};return null}function m3($,Z){let X=S($),Q=[];for(let Y of X){let K=null;if(Z==="requirements")K=T8(Y);else if(Z==="pyproject"||Z==="pipfile"||Z==="poetry")K=x8(Y);if(K)Q.push(K)}return Q}function h3($,Z){let X=z1($),Q=[];for(let Y of X){let K=null;if(Z==="requirements")K=T8(Y);else if(Z==="pyproject"||Z==="pipfile"||Z==="poetry")K=x8(Y);if(K)Q.push(K)}return Q}var j8,D8,N8,A8,R8,F3,N2;var E8=T(()=>{j8=/requirements.*\.txt$/,D8=/pyproject\.toml$/,N8=/^setup\.(py|cfg)$/,A8=/^Pipfile(\.lock)?$/,R8=/^poetry\.lock$/,F3={"django-allauth":"auth","python-social-auth":"auth",authlib:"auth",oauthlib:"auth","python-jose":"auth",pyjwt:"auth",passlib:"auth","argon2-cffi":"auth",bcrypt:"auth",django:"database",sqlalchemy:"database",alembic:"database",psycopg2:"database","psycopg2-binary":"database",asyncpg:"database",pymysql:"database",mysqlclient:"database",pymongo:"database",motor:"database",redis:"database",aioredis:"database","tortoise-orm":"database",peewee:"database",sqlmodel:"database",databases:"database",prisma:"database",numpy:"native",pandas:"native",scipy:"native",pillow:"native","opencv-python":"native",tensorflow:"native",torch:"native",cryptography:"native",pycryptodome:"native",pynacl:"native",stripe:"payment",braintree:"payment",paypalrestsdk:"payment"};N2={name:"python-dependencies",analyze($){let Z=[];for(let X of $.files){if(!v3(X.path))continue;let Q=$.diffs.find((K)=>K.path===X.path),Y=y3(X.path);if(Q){let K=m3(Q,Y),W=h3(Q,Y),q=new Set(W.map((U)=>U.name)),V=new Set(K.map((U)=>U.name));for(let U of K){let J=q.has(U.name),B=J?W.find((H)=>H.name===U.name):void 0,G="new";if(J&&B?.version&&U.version){let H=parseInt(B.version.match(/(\d+)/)?.[1]??"0",10);if(parseInt(U.version.match(/(\d+)/)?.[1]??"0",10)>H)G="major";else G="minor"}else if(J)G="unknown";let M=F3[U.name],O=S(Q).find((H)=>H.toLowerCase().includes(U.name))??U.name;Z.push({type:"dependency-change",kind:"dependency-change",category:"dependencies",confidence:"high",evidence:[A(X.path,O)],name:U.name,section:"dependencies",from:B?.version,to:U.version,impact:G,riskCategory:M})}for(let U of W){if(V.has(U.name))continue;let B=z1(Q).find((G)=>G.toLowerCase().includes(U.name))??U.name;Z.push({type:"dependency-change",kind:"dependency-change",category:"dependencies",confidence:"high",evidence:[A(X.path,B)],name:U.name,section:"dependencies",from:U.version,to:void 0,impact:"removed"})}}else if(X.status==="added"||X.status==="deleted")Z.push({type:"dependency-change",kind:"dependency-change",category:"dependencies",confidence:"medium",evidence:[A(X.path,`${Y} file ${X.status}`)],name:X.path,section:"dependencies",impact:X.status==="added"?"new":"removed"})}return Z}}});function w8($,Z){let X=$.split("/").pop()??"";if(/urls\.py$/.test(X))return"django";if(Z.includes("from fastapi")||Z.includes("import fastapi")||Z.includes("APIRouter"))return"fastapi";if(Z.includes("from django")||Z.includes("urlpatterns"))return"django";if(Z.includes("from flask")||Z.includes("Flask(")||Z.includes("Blueprint("))return"flask";for(let Q of S8)if(Q.test(X))return"django";for(let Q of C8)if(Q.test(X))return"fastapi";for(let Q of k8)if(Q.test(X))return"flask";return null}function I8($){if(!$.endsWith(".py"))return!1;let Z=$.split("/").pop()??"";return[...C8,...S8,...k8].some((Q)=>Q.test(Z))}function c3($){let Z=[],X=new RegExp(g3.source,"gi"),Q;while((Q=X.exec($))!==null){let Y=Q[1].toLowerCase(),K=Q[2],W=Y==="api_route"?["GET"]:[Y.toUpperCase()];Z.push({path:K,methods:W})}return Z}function p3($){let Z=[],X=new RegExp(f3.source,"gi"),Q;while((Q=X.exec($))!==null){let Y=Q[1];Z.push({path:Y,methods:[]})}return Z}function d3($){let Z=[],X=new RegExp(l3.source,"gi"),Q;while((Q=X.exec($))!==null){let Y=Q[1],K=Q[2],W=["GET"];if(K)W=K.replace(/["']/g,"").split(",").map((q)=>q.trim().toUpperCase()).filter((q)=>q.length>0);Z.push({path:Y,methods:W})}return Z}function b8($,Z){switch(Z){case"fastapi":return c3($);case"django":return p3($);case"flask":return d3($)}}function P8($,Z){return"endpoint"}function A2($,Z){let X=$;if(Z==="django")X=X.replace(/^\^/,"").replace(/\$$/,""),X=X.replace(/\(\?P<(\w+)>[^)]+\)/g,":{$1}");if(!X.startsWith("/"))X="/"+X;if(X.length>1&&X.endsWith("/"))X=X.slice(0,-1);return X}var u3,g3,f3,l3,C8,S8,k8,R2;var F8=T(()=>{u3=["get","post","put","patch","delete","head","options"],g3=new RegExp(`@\\w+\\.(${u3.join("|")}|api_route)\\s*\\(\\s*["']([^"']+)["']`,"gi"),f3=/(?:path|re_path|url)\s*\(\s*(?:r)?["']([^"']+)["']/gi,l3=/@\w+\.route\s*\(\s*["']([^"']+)["'](?:.*?methods\s*=\s*\[([^\]]+)\])?/gi,C8=[/routers?\.py$/,/endpoints?\.py$/,/api\.py$/,/main\.py$/,/app\.py$/,/routes?\.py$/],S8=[/urls\.py$/,/views\.py$/],k8=[/views?\.py$/,/routes?\.py$/,/app\.py$/,/api\.py$/,/__init__\.py$/];R2={name:"python-routes",analyze($){let Z=[],X=new Map;for(let Q of $.files)if(I8(Q.path))X.set(Q.path,{status:Q.status});for(let Q of $.diffs)if(I8(Q.path)){let Y=X.get(Q.path);if(Y)Y.diff=Q;else X.set(Q.path,{diff:Q,status:Q.status})}for(let[Q,{diff:Y}]of X){if(!Y)continue;let K=S(Y),W=z1(Y),q=K.join(`
|
|
43
42
|
`),V=W.join(`
|
|
44
|
-
`),U=
|
|
45
|
-
`),J=
|
|
46
|
-
`),q=[];if(Y.length>0){let G=k(Y);if(G)q.push(N(Q.path,G))}let V=!1,U=[];if(X.configType==="pyproject")U=h3(W),V=U.length>0;let J=g3(W),B={type:"python-config",kind:"python-config",category:"config_env",confidence:"high",evidence:q,file:Q.path,status:Q.status,configType:X.configType,configCategory:X.category,isBreaking:V,affectedSections:J,breakingReasons:U};Z.push(B)}return Z}}});var P1=x(()=>{y5();i5();Q2();$8();i1();t1();Y2();W2();V2();G2();O8();A8();T8();x8();M5();n$();t$();N5();R5();T5();a0();w5();E5();Q0();h5();g5();c5();f5();p5();d5();r5();a5()});var L2;var w8=x(()=>{P1();L2={name:"auto",analyzers:[a,s,X1,J1,K1,Y1,q1,n,X2,i,t,e,W1,$1,U1,Z1]}});var E8;var I8=x(()=>{P1();t1();E8={name:"sveltekit",analyzers:[a,s,j5,A5,X1,J1,K1,Y1,q1,n,w1,i,t,e,W1,$1,U1,Z1]}});var b8;var C8=x(()=>{P1();t1();i1();b8={name:"react",analyzers:[a,s,i0,X1,J1,K1,Y1,q1,n,w1,x1,i,t,e,W1,$1,U1,Z1]}});var P8;var y8=x(()=>{P1();i1();P8={name:"stencil",analyzers:[a,s,$2,X1,J1,K1,Y1,q1,n,x1,i,t,e,W1,$1,U1,Z1]}});var k8;var S8=x(()=>{P1();Q2();t1();k8={name:"next",analyzers:[a,s,Z2,X1,J1,K1,Y1,q1,n,w1,i,t,e,W1,$1,U1,Z1]}});var v8;var F8=x(()=>{P1();V2();t1();i1();v8={name:"vue",analyzers:[a,s,U2,X1,J1,K1,Y1,q1,n,w1,x1,i,t,e,W1,$1,U1,Z1]}});var m8;var u8=x(()=>{P1();G2();t1();i1();m8={name:"astro",analyzers:[a,s,B2,X1,J1,K1,Y1,q1,n,w1,x1,i,t,e,W1,$1,U1,Z1]}});var h8;var g8=x(()=>{P1();W2();i1();Y2();h8={name:"library",analyzers:[a,s,q2,x1,Y1,K1,n,K2,i,t,e,$1,Z1]}});var l8;var c8=x(()=>{P1();l8={name:"python",analyzers:[a,s,O2,H2,_2,z2,X1,q1,n,i,t,e,W1,$1,U1,Z1]}});import{existsSync as _1}from"node:fs";import{join as z1}from"node:path";function l3($=process.cwd()){if(_1(z1($,"src","routes")))return!0;return!1}function c3($){if(!$)return!1;let{dependencies:Z,devDependencies:Q}=$;return Boolean(Z?.["@sveltejs/kit"]||Q?.["@sveltejs/kit"])}function f3($){if(!$)return!1;let{dependencies:Z,devDependencies:Q}=$;return Boolean(Z?.react&&Z?.["react-dom"]||Q?.react&&Q?.["react-dom"])}function p3($){if(!$)return!1;let{dependencies:Z,devDependencies:Q}=$;return Boolean(Z?.["react-router"]||Z?.["react-router-dom"]||Q?.["react-router"]||Q?.["react-router-dom"])}function d3($){if(!$)return!1;let{dependencies:Z,devDependencies:Q}=$;return Boolean(Z?.next||Q?.next)}function r3($){if(!$)return!1;let{dependencies:Z,devDependencies:Q}=$;return Boolean(Z?.["@stencil/core"]||Q?.["@stencil/core"])}function a3($=process.cwd()){return _1(z1($,"stencil.config.ts"))||_1(z1($,"stencil.config.js"))}function s3($=process.cwd()){if(_1(z1($,"app")))return!0;if(_1(z1($,"src","app")))return!0;return!1}function o3($){if(!$)return!1;let{dependencies:Z,devDependencies:Q}=$;return Boolean(Z?.vue||Q?.vue)}function n3($){if(!$)return!1;let{dependencies:Z,devDependencies:Q}=$;return Boolean(Z?.nuxt||Q?.nuxt)}function i3($=process.cwd()){return _1(z1($,"pages"))||_1(z1($,"src","pages"))}function t3($){if(!$)return!1;let{dependencies:Z,devDependencies:Q}=$;return Boolean(Z?.astro||Q?.astro)}function e3($=process.cwd()){return _1(z1($,"astro.config.mjs"))||_1(z1($,"astro.config.ts"))||_1(z1($,"astro.config.js"))}function $7($){if(!$)return!1;if($.exports)return!0;if($.publishConfig)return!0;if($.private===!1)return!0;if($.bin)return!0;return!1}function Z7($=process.cwd()){return["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","poetry.lock"].some((Q)=>_1(z1($,Q)))}function Q7($=process.cwd()){return["manage.py","app/main.py","src/main.py","app/__init__.py"].some((Q)=>_1(z1($,Q)))}function X7($){for(let Z of $.files){if(Z.path.includes("/migrations/")&&Z.path.endsWith(".py"))return"django";if(Z.path==="manage.py"||Z.path.includes("urls.py"))return"django";if(Z.path.includes("routers/")||Z.path.includes("endpoints/"))return"fastapi";if(Z.path.includes("alembic/versions/"))return"alembic"}return null}function b$($,Z=process.cwd()){let Q=[],X=l3(Z),K=c3($.headPackageJson);if(X||K){if(X)Q.push("Found src/routes/ directory (SvelteKit file-based routing)");if(K)Q.push("Found @sveltejs/kit in package.json dependencies");return{profile:"sveltekit",confidence:X&&K?"high":"high",reasons:Q}}let Y=r3($.headPackageJson),W=a3(Z);if(Y||W){if(Y)Q.push("Found @stencil/core in package.json dependencies");if(W)Q.push("Found stencil.config.ts or stencil.config.js");return{profile:"stencil",confidence:Y&&W?"high":"high",reasons:Q}}let q=d3($.headPackageJson),V=s3(Z);if(q&&V)return Q.push("Found next in package.json dependencies"),Q.push("Found app/ directory (Next.js App Router)"),{profile:"next",confidence:"high",reasons:Q};if(q)return Q.push("Found next in package.json dependencies"),{profile:"next",confidence:"medium",reasons:Q};let U=f3($.headPackageJson),J=p3($.headPackageJson);if(U&&J)return Q.push("Found react and react-dom in package.json dependencies"),Q.push("Found react-router or react-router-dom in package.json dependencies"),{profile:"react",confidence:"high",reasons:Q};let B=o3($.headPackageJson),G=n3($.headPackageJson),M=i3(Z);if(G||B&&M){if(G)Q.push("Found nuxt in package.json dependencies");if(B)Q.push("Found vue in package.json dependencies");if(M)Q.push("Found pages/ directory (Nuxt file-based routing)");return{profile:"vue",confidence:"high",reasons:Q}}if(B)return Q.push("Found vue in package.json dependencies"),{profile:"vue",confidence:"medium",reasons:Q};let H=t3($.headPackageJson),O=e3(Z);if(H||O){if(H)Q.push("Found astro in package.json dependencies");if(O)Q.push("Found astro.config.{mjs,ts,js}");return{profile:"astro",confidence:H&&O?"high":"medium",reasons:Q}}if($7($.headPackageJson)){if($.headPackageJson?.exports)Q.push("Found exports field in package.json");if($.headPackageJson?.publishConfig)Q.push("Found publishConfig in package.json");if($.headPackageJson?.bin)Q.push("Found bin field in package.json (CLI tool)");if($.headPackageJson?.private===!1)Q.push("Package marked as public (private: false)");return{profile:"library",confidence:"medium",reasons:Q}}let _=Z7(Z),D=Q7(Z),L=X7($);if(_||D||L){if(_)Q.push("Found Python project files (pyproject.toml, requirements.txt, etc.)");if(D)Q.push("Found Python web framework markers (manage.py, main.py, etc.)");if(L)Q.push(`Detected ${L} framework from changed files`);return{profile:"python",confidence:_&&(D||L)?"high":"medium",reasons:Q}}return Q.push("No framework-specific markers detected, using default analyzers"),{profile:"auto",confidence:"medium",reasons:Q}}function K7($,Z=process.cwd()){return b$($,Z).profile}function y1($){switch($){case"sveltekit":return E8;case"react":return b8;case"stencil":return P8;case"next":return k8;case"vue":return v8;case"astro":return m8;case"library":return h8;case"python":return l8;case"auto":return L2;default:return L2}}function e1($,Z,Q=process.cwd()){if($==="auto")return K7(Z,Q);return $}var C$=x(()=>{w8();I8();C8();y8();S8();F8();u8();g8();c8()});function P7($){let Z=$.find((Y)=>Y.type==="file-category");if(!Z)return{isLowRisk:!1,category:null};let{categories:Q}=Z;if(["product","infra","ci","dependencies"].some((Y)=>Q[Y].length>0))return{isLowRisk:!1,category:null};if(Q.docs.length>0&&Q.tests.length===0)return{isLowRisk:!0,category:"docs"};if(Q.tests.length>0&&Q.docs.length===0)return{isLowRisk:!0,category:"tests"};if(Q.config.length>0&&Q.docs.length===0&&Q.tests.length===0)return{isLowRisk:!0,category:"config"};if(Q.docs.length>0||Q.tests.length>0||Q.config.length>0)return{isLowRisk:!0,category:"docs/tests/config"};return{isLowRisk:!1,category:null}}function O$($){let Z=0,Q=[],X=[],{isLowRisk:K,category:Y}=P7($);if(K&&Y){let J={docs:-15,tests:-10,config:-5,"docs/tests/config":-10}[Y]??0;Z+=J,Q.push(`✅ Changes are only in ${Y} (lower risk)`),X.push({kind:"low-risk-category",weight:J,explanation:`Changes are only in ${Y} (lower risk)`,evidence:[]})}for(let U of $)switch(U.type){case"risk-flag":{let J=U.risk==="high"?40:U.risk==="medium"?20:5;Z+=J;let B=U.risk==="high"?"⚠️":U.risk==="medium"?"⚡":"ℹ️";Q.push(`${B} ${U.evidenceText}`),X.push({kind:`risk-${U.risk}`,weight:J,explanation:U.evidenceText,evidence:U.evidence})}break;case"db-migration":{let J=U.risk==="high"?30:U.risk==="medium"?15:0;if(J>0){Z+=J;let B=U.risk==="high"?`High-risk database migration: ${U.reasons.join(", ")}`:`Database migration detected: ${U.files.join(", ")}`;Q.push(U.risk==="high"?`⚠️ ${B}`:`⚡ ${B}`),X.push({kind:"db-migration",weight:J,explanation:B,evidence:U.evidence})}}break;case"route-change":if(U.change==="added")Z+=5,X.push({kind:"route-added",weight:5,explanation:`Route added: ${U.routeId}`,evidence:U.evidence});else if(U.change==="deleted")Z+=10,Q.push(`ℹ️ Route deleted: ${U.routeId}`),X.push({kind:"route-deleted",weight:10,explanation:`Route deleted: ${U.routeId}`,evidence:U.evidence});break;case"dependency-change":{let J=0;if(U.impact==="major")J=15;else if(U.impact==="minor")J=5;if(U.riskCategory&&U.impact==="new")J+=10;if(J>0)Z+=J,X.push({kind:`dependency-${U.impact}`,weight:J,explanation:`${U.name}: ${U.from??"new"} → ${U.to??"removed"}`,evidence:U.evidence})}break;case"env-var":if(U.change==="added")Z+=5,Q.push(`ℹ️ New env var: ${U.name}`),X.push({kind:"env-var-added",weight:5,explanation:`New env var: ${U.name}`,evidence:U.evidence});break;case"security-file":Z+=15,X.push({kind:"security-file",weight:15,explanation:`Security-sensitive files changed: ${U.files.length} file(s)`,evidence:U.evidence});break;case"convention-violation":{let J=U,B=J.files.length;if(B>5)Z+=10,Q.push(`⚡ ${B} source files lack test coverage`),X.push({kind:"test-coverage-gap",weight:10,explanation:`${B} source files lack test coverage`,evidence:J.evidence.slice(0,3)})}break;case"large-diff":{let J=U,B=J.linesChanged>1000?15:J.linesChanged>500?10:5;Z+=B,Q.push(`ℹ️ Large diff: ${J.filesChanged} files, ${J.linesChanged} lines`),X.push({kind:"large-diff",weight:B,explanation:`Large diff: ${J.filesChanged} files, ${J.linesChanged} lines`,evidence:J.evidence})}break}let W=[/\/types\.ts$/,/\/core\/.*\.ts$/,/\/index\.ts$/],q=$.find((U)=>U.type==="file-summary");if(q){let U=q.modified.filter((J)=>W.some((B)=>B.test(J)));if(U.length>0)Z+=10,Q.push(`⚡ Core module files modified: ${U.join(", ")}`),X.push({kind:"core-module-change",weight:10,explanation:`Core module files modified (types.ts, index.ts): ${U.length} file(s)`,evidence:[]})}Z=Math.max(0,Math.min(Z,100));let V;if(Z>=50)V="high";else if(Z>=20)V="medium";else V="low";return{score:Z,level:V,factors:X,evidenceBullets:Q}}function f7($){if($.includes("db-migration")||$.includes("database")||$.includes("sql"))return"database";if($.includes("dependency")||$.includes("deps"))return"dependencies";if($.includes("route"))return"routes";if($.includes("env-var")||$.includes("config"))return"config_env";if($.includes("security")||$.includes("infra")||$.includes("docker")||$.includes("k8s")||$.includes("terraform"))return"infra";if($.includes("cloudflare")||$.includes("wrangler")||$.includes("workers"))return"cloudflare";if($.includes("ci")||$.includes("workflow")||$.includes("pipeline"))return"ci";if($.includes("test")&&!$.includes("test-gap")&&!$.includes("test-coverage"))return"tests";if($.includes("test-gap")||$.includes("test-coverage")||$.includes("quality"))return"quality";if($.includes("api")||$.includes("contract"))return"api";if($.includes("core-module")||$.includes("impact")||$.includes("blast-radius")||$.includes("large-diff")||$.includes("churn"))return"impact";if($.includes("doc"))return"docs";return"unknown"}function d8($){let Z=$.excerpt.toLowerCase(),Q=0;if(/\d+/.test(Z))Q+=10;if(Z.includes("blast radius"))Q+=15;if(Z.includes("high"))Q+=5;if(Z.includes("critical"))Q+=8;if(Z.includes("breaking"))Q+=8;if(Z.includes("added")||Z.includes("removed")||Z.includes("modified"))Q+=3;if(Z==="imports module")Q-=10;if(Z.startsWith("depends on"))Q-=5;return Q}function K0($,Z){let Q=new Map;for(let K of $){if(K.kind==="file-summary"||K.kind==="file-category")continue;let Y=K.category;if(!Q.has(Y))Q.set(Y,{count:0,riskWeight:0,evidence:[]});let W=Q.get(Y);W.count+=1,W.evidence.push(...K.evidence)}for(let K of Z){let Y="unknown";for(let q of $)if(q.evidence.length>0&&K.evidence.length>0){let V=new Set(q.evidence.map((B)=>B.file)),U=new Set(K.evidence.map((B)=>B.file));if(Array.from(V).some((B)=>U.has(B))){Y=q.category;break}}if(Y==="unknown")Y=f7(K.kind);if(!Q.has(Y))Q.set(Y,{count:0,riskWeight:0,evidence:[]});let W=Q.get(Y);W.riskWeight+=K.weight,W.evidence.push(...K.evidence)}let X=Array.from(Q.entries()).filter(([K,Y])=>Y.count>0).map(([K,Y])=>{let W=[...Y.evidence].sort((U,J)=>{let B=d8(U),G=d8(J);if(G!==B)return G-B;return U.file.localeCompare(J.file)}),q=new Set,V=[];for(let U of W){if(!q.has(U.file))q.add(U.file),V.push(U);if(V.length>=3)break}return{id:K,count:Y.count,riskWeight:Y.riskWeight,topEvidence:V}});return X.sort((K,Y)=>{if(Y.riskWeight!==K.riskWeight)return Y.riskWeight-K.riskWeight;if(Y.count!==K.count)return Y.count-K.count;return K.id.localeCompare(Y.id)}),X}function Y0($){let Z={};for(let Q of $)Z[Q.id]=Q.count;return Z}function q0($,Z){let Q=[];if(Z==="sveltekit"){let U=$.some((J)=>J.type==="route-change");if(U||$.length>0){let J=[];if(U)J.push("Route files changed");if($.length>0&&!U)J.push("Source files changed");Q.push({id:"sveltekit-check",category:"types",blocking:!0,reason:"Run SvelteKit type checker to verify no type errors were introduced",triggers:J})}}let X=$.filter((U)=>U.type==="test-change"),K=X.length>0;if(K||$.length>0){let U=[];if(K){let J=X.reduce((B,G)=>B+G.files.length,0);U.push(`${J} test file(s) changed`)}if($.length>0&&!K)U.push("Source files changed without corresponding test changes");Q.push({id:"run-tests",category:"tests",blocking:!0,reason:"Run test suite to verify functionality and catch regressions",triggers:U})}let Y=$.filter((U)=>U.type==="db-migration");if(Y.length>0){let U=Y.some((M)=>M.risk==="high"),J=Y.flatMap((M)=>M.files),B=[...new Set(Y.flatMap((M)=>M.reasons))],G=[`${J.length} migration file(s) changed`,...B];if(U)G.push("DANGEROUS SQL DETECTED (DROP, TRUNCATE, or destructive operations)");if(Q.push({id:"apply-migrations",category:"database",blocking:U,reason:U?"Apply database migrations in a safe environment and verify data integrity before production":"Apply and test database migrations in development environment",triggers:G}),U)Q.push({id:"backup-db",category:"database",blocking:!0,reason:"Create database backup before applying destructive migrations",triggers:["High-risk SQL operations detected in migrations"]})}let W=$.filter((U)=>U.type==="cloudflare-change");if(W.length>0){let U=[...new Set(W.map((B)=>B.area))],J=W.flatMap((B)=>B.files);Q.push({id:"verify-cloudflare-config",category:"cloudflare",blocking:!1,reason:"Verify Cloudflare configuration and bindings match across environments",triggers:[`Cloudflare ${U.join(", ")} configuration changed`,`Files: ${J.join(", ")}`]})}let q=$.filter((U)=>U.type==="env-var");if(q.length>0){let U=q.map((G)=>G.name),J=q.filter((G)=>G.change==="added"),B=[];if(J.length>0)B.push(`New environment variable(s): ${J.map((G)=>G.name).join(", ")}`);if(q.length>J.length)B.push(`Modified environment variable(s): ${U.filter((G)=>!J.some((M)=>M.name===G)).join(", ")}`);Q.push({id:"update-env-docs",category:"environment",blocking:!1,reason:"Update .env.example and documentation with new or changed environment variables",triggers:B})}let V=$.filter((U)=>U.type==="dependency-change"&&U.impact==="major");if(V.length>0){let U=V.map((J)=>{let B=J.from||"new",G=J.to||"removed";return`${J.name} (${B} → ${G})`});Q.push({id:"review-dependencies",category:"dependencies",blocking:!1,reason:"Review major dependency changes for breaking changes and update migration guides if needed",triggers:[`Major version changes: ${U.join(", ")}`,"Check CHANGELOG and migration guides for breaking changes"]})}return Q.sort((U,J)=>{if(U.blocking!==J.blocking)return U.blocking?-1:1;return U.id.localeCompare(J.id)}),Q}function r8($){let Z=[],Q=0,X=(j,C)=>{Z.push({text:j,priority:C,order:Q++})},K=$.filter((j)=>j.type==="impact-analysis"),Y=K.filter((j)=>j.blastRadius==="high"),W=K.filter((j)=>j.blastRadius==="medium");if(Y.length>0)X(`${Y.length} file(s) with high blast radius`,F.HIGH_BLAST_RADIUS);if(W.length>0)X(`${W.length} file(s) with medium blast radius`,F.MEDIUM_BLAST_RADIUS);let q=$.filter((j)=>j.type==="typescript-config");if(q.length>0){let j=q.some((C)=>C.isBreaking);X(j?"TypeScript config changed (breaking)":"TypeScript config modified",j?F.BREAKING_CONFIG:F.NON_BREAKING_CONFIG)}let V=$.filter((j)=>j.type==="tailwind-config");if(V.length>0){let j=V.some((C)=>C.isBreaking);X(j?"Tailwind config changed (breaking)":"Tailwind config modified",j?F.BREAKING_CONFIG:F.NON_BREAKING_CONFIG)}let U=$.filter((j)=>j.type==="graphql-change");if(U.length>0){let j=U.some((C)=>C.isBreaking);X(j?"GraphQL schema changed (breaking)":"GraphQL schema modified",j?F.BREAKING_CONFIG:F.NON_BREAKING_CONFIG)}let J=$.filter((j)=>j.type==="package-exports");if(J.length>0){if(J.some((C)=>C.isBreaking))X("Package exports changed (breaking)",F.BREAKING_CONFIG);else if(J.filter((O1)=>O1.binChanges&&(O1.binChanges.added.length>0||O1.binChanges.removed.length>0)).length>0)X("Package bin/exports modified",F.NON_BREAKING_CONFIG)}let G=$.filter((j)=>j.type==="risk-flag").filter((j)=>j.risk==="high");if(G.length>0)X(`${G.length} high-risk condition(s) detected`,F.HIGH_RISK_FLAGS);let H=$.filter((j)=>j.type==="sql-risk").filter((j)=>j.riskType==="destructive");if(H.length>0)X(`Destructive SQL detected in ${H.length} file(s)`,F.DESTRUCTIVE_SQL);let O=$.filter((j)=>j.type==="db-migration");if(O.length>0){let j=O.some((C)=>C.risk==="high");X(j?"Database migrations (HIGH RISK)":"Database migrations",j?F.HIGH_RISK_DB_MIGRATION:F.DB_MIGRATION)}let z=$.filter((j)=>j.type==="ci-workflow");if(z.length>0)if(z.filter((C)=>C.riskType==="permissions_broadened"||C.riskType==="pull_request_target").length>0)X("CI workflow security changes detected",F.CI_SECURITY);else X(`${z.length} CI workflow(s) modified`,F.CI_WORKFLOW);if($.filter((j)=>j.type==="security-file").length>0)X("Security-sensitive files changed",F.SECURITY_FILES);let D=$.find((j)=>j.type==="lockfile-mismatch");if(D){if(D.manifestChanged&&!D.lockfileChanged)X("Lockfile mismatch: package.json changed but lockfile not updated",F.LOCKFILE_MISMATCH);else if(!D.manifestChanged&&D.lockfileChanged)X("Lockfile mismatch: lockfile changed but package.json not updated",F.LOCKFILE_MISMATCH)}let L=$.filter((j)=>j.type==="infra-change");if(L.length>0){let j=[...new Set(L.map((C)=>C.infraType))];X(`Infrastructure changes: ${j.join(", ")}`,F.INFRA_CHANGES)}let w=$.filter((j)=>j.type==="dependency-change"),T=w.filter((j)=>j.impact==="major");if(T.length>0)X(`${T.length} major dependency update(s)`,F.MAJOR_DEPS);let A=$.filter((j)=>j.type==="route-change");if(A.length>0)X(`${A.length} route(s) changed`,F.ROUTE_CHANGES);let b=$.filter((j)=>j.type==="api-contract-change");if(b.length>0)X(`${b.length} API contract(s) modified`,F.API_CONTRACTS);let R=$.filter((j)=>j.type==="cloudflare-change");if(R.length>0){let j=[...new Set(R.map((C)=>C.area))];X(`Cloudflare ${j.join("/")} configuration changed`,F.CLOUDFLARE)}let h=$.filter((j)=>j.type==="stencil-component-change"||j.type==="stencil-prop-change"||j.type==="stencil-event-change"||j.type==="stencil-method-change"||j.type==="stencil-slot-change");if(h.length>0){let j=new Set(h.map((C)=>C.tag));X(`${j.size} Stencil component(s) with API changes`,F.STENCIL_API)}let y=$.filter((j)=>j.type==="monorepo-config");if(y.length>0){let j=[...new Set(y.map((C)=>C.tool))];X(`Monorepo config changed: ${j.join(", ")}`,F.MONOREPO_CONFIG)}let r1=$.filter((j)=>j.type==="env-var");if(r1.length>0){let j=r1.filter((C)=>C.change==="added");X(j.length>0?`${j.length} new environment variable(s)`:`${r1.length} environment variable(s) touched`,F.ENV_VARS)}let a1=w.filter((j)=>j.impact==="new");if(a1.length>0)X(`${a1.length} new dependency(ies) added`,F.NEW_DEPS);let K$=$.filter((j)=>j.type==="test-change");if(K$.length>0){let j=K$.flatMap((C)=>C.files);X(`${j.length} test file(s) modified`,F.TEST_CHANGES)}let Y$=$.filter((j)=>j.type==="convention-violation");if(Y$.length>0){let j=Y$.reduce((C,O1)=>C+O1.files.length,0);X(`${j} source file(s) missing corresponding tests`,F.CONVENTION_VIOLATIONS)}let r=$.filter((j)=>j.type==="test-gap");if(r.length>0){let j=r.reduce((C,O1)=>C+O1.prodFilesChanged,0);X(`${j} modified file(s) lack test coverage`,F.TEST_GAPS)}if(Z.length===0&&$.length>0){let j=$.find((C)=>C.type==="file-summary");if(j){let C=j.added.length+j.modified.length+j.deleted.length+j.renamed.length;if(C>0)X(`${C} ${j.category} file(s) changed`,F.FALLBACK)}if(Z.length===0&&K.length>0){let C=K.reduce((O1,I0)=>O1+I0.affectedFiles.length,0);X(`${K.length} file(s) analyzed, ${C} dependent file(s)`,F.FALLBACK)}if(Z.length===0)X(`${$.length} finding(s) detected`,F.FALLBACK)}return Z.sort((j,C)=>{if(C.priority!==j.priority)return C.priority-j.priority;return j.order-C.order}),Z.map((j)=>j.text)}var F;var a8=x(()=>{F={HIGH_BLAST_RADIUS:100,MEDIUM_BLAST_RADIUS:95,BREAKING_CONFIG:90,HIGH_RISK_FLAGS:85,DESTRUCTIVE_SQL:85,HIGH_RISK_DB_MIGRATION:85,CI_SECURITY:85,SECURITY_FILES:85,LOCKFILE_MISMATCH:80,INFRA_CHANGES:70,MAJOR_DEPS:70,ROUTE_CHANGES:70,API_CONTRACTS:70,CLOUDFLARE:70,STENCIL_API:60,MONOREPO_CONFIG:60,ENV_VARS:60,NEW_DEPS:60,NON_BREAKING_CONFIG:60,DB_MIGRATION:55,CI_WORKFLOW:55,TEST_CHANGES:50,TEST_GAPS:50,CONVENTION_VIOLATIONS:50,FALLBACK:10}});function s8($){return $.replace(/\\/g,"/").toLowerCase()}function W0($,Z){let Q=s8($),X=s8(Z);return Q.localeCompare(X)}function o8($){return[...$].sort((Z,Q)=>{let X=Z.category.localeCompare(Q.category);if(X!==0)return X;let K=Q.effectiveScore-Z.effectiveScore;if(K!==0)return K;let Y=Z.ruleKey.localeCompare(Q.ruleKey);if(Y!==0)return Y;return Z.flagId.localeCompare(Q.flagId)})}function n8($){return[...$].sort((Z,Q)=>{let X=Z.type.localeCompare(Q.type);if(X!==0)return X;let K=(J)=>{if(J.evidence&&J.evidence.length>0)return J.evidence[0].file;return""},Y=K(Z),W=K(Q);if(Y&&W){let J=W0(Y,W);if(J!==0)return J}let q=(J)=>{if(J.evidence&&J.evidence.length>0){let B=J.evidence[0];if(B.line!==void 0)return B.line;if(B.hunk?.newStart!==void 0)return B.hunk.newStart}return 0},V=q(Z),U=q(Q);return V-U})}function N2($){return[...$].sort((Z,Q)=>{let X=W0(Z.file,Q.file);if(X!==0)return X;let K=Z.line??(Z.hunk?.newStart??0),Y=Q.line??(Q.hunk?.newStart??0);return K-Y})}function R2($){return[...$].sort((Z,Q)=>{let X=W0(Z.file,Q.file);if(X!==0)return X;if(Z.hunk&&Q.hunk){let K=(Y)=>{let W=Y.match(/\+(\d+)/);return W?parseInt(W[1],10):0};return K(Z.hunk)-K(Q.hunk)}return 0})}function $U($){return[...$].sort(W0)}function ZU($){let Z=[...$].sort((X,K)=>X[0].localeCompare(K[0])),Q={};for(let[X,K]of Z)Q[X]=K;return Q}import{createHash as p7}from"node:crypto";function m($){return $.replace(/\\/g,"/")}function i8($){return p7("sha256").update($).digest("hex").slice(0,12)}function u($){return[...$].sort()}function d7($){let Z;switch($.type){case"env-var":{let X=u($.evidenceFiles.map(m));Z=`env-var:${$.name}:${X.join(",")}`;break}case"dependency-change":{Z=`dependency-change:${$.name}:${$.from||"null"}:${$.to||"null"}:${$.section}`;break}case"route-change":{Z=`route-change:${m($.routeId)}:${$.change}:${$.routeType}`;break}case"db-migration":{let X=u($.files.map(m));Z=`db-migration:${$.tool}:${X.join(",")}`;break}case"cloudflare-change":{let X=u($.files.map(m));Z=`cloudflare-change:${$.area}:${X.join(",")}`;break}case"test-change":{let X=u($.files.map(m));Z=`test-change:${$.framework}:${X.join(",")}`;break}case"security-file":{let X=u($.files.map(m)),K=u($.reasons);Z=`security-file:${X.join(",")}:${K.join(",")}`;break}case"file-category":{Z=`file-category:${Object.entries($.categories).map(([K,Y])=>`${K}:${u(Y.map(m)).join(",")}`).sort().join("|")}`;break}case"file-summary":{let X=u($.added.map(m)).join(","),K=u($.modified.map(m)).join(","),Y=u($.deleted.map(m)).join(","),W=u($.renamed.map((q)=>`${m(q.from)}->${m(q.to)}`)).join(",");Z=`file-summary:${$.category}:a=${X}:m=${K}:d=${Y}:r=${W}`;break}case"convention-violation":{let X=u($.files.map(m));Z=`convention-violation:${$.message}:${X.join(",")}`;break}case"test-parity-violation":{let X=m($.sourceFile),K=u($.expectedTestLocations.map(m));Z=`test-parity-violation:${X}:${K.join(",")}`;break}case"impact-analysis":{let X=m($.sourceFile),K=u($.affectedFiles.map(m));Z=`impact-analysis:${X}:${K.join(",")}`;break}case"ci-workflow":{Z=`ci-workflow:${m($.file)}:${$.riskType}`;break}case"sql-risk":{Z=`sql-risk:${m($.file)}:${$.riskType}`;break}case"infra-change":{let X=u($.files.map(m));Z=`infra-change:${$.infraType}:${X.join(",")}`;break}case"api-contract-change":{Z=`api-contract-change:${u($.files.map(m)).join(",")}`;break}case"large-diff":{Z=`large-diff:${$.filesChanged}:${$.linesChanged}`;break}case"lockfile-mismatch":{Z=`lockfile-mismatch:${$.manifestChanged}:${$.lockfileChanged}`;break}case"test-gap":{Z=`test-gap:${$.prodFilesChanged}:${$.testFilesChanged}`;break}case"stencil-component-change":{let X=m($.file);Z=`stencil-component-change:${$.tag}:${$.change}:${X}:${$.fromTag||""}:${$.toTag||""}`;break}case"stencil-prop-change":{let X=m($.file);Z=`stencil-prop-change:${$.tag}:${$.propName}:${$.change}:${X}`;break}case"stencil-event-change":{let X=m($.file);Z=`stencil-event-change:${$.tag}:${$.eventName}:${$.change}:${X}`;break}case"stencil-method-change":{let X=m($.file);Z=`stencil-method-change:${$.tag}:${$.methodName}:${$.change}:${X}`;break}case"stencil-slot-change":{let X=m($.file);Z=`stencil-slot-change:${$.tag}:${$.slotName}:${$.change}:${X}`;break}case"risk-flag":{Z=`risk-flag:${$.risk}:${$.evidenceText}`;break}case"graphql-change":{let X=m($.file),K=u($.breakingChanges).join(","),Y=u($.addedElements).join(",");Z=`graphql-change:${X}:${$.isBreaking}:${K}:${Y}`;break}case"typescript-config":{let X=m($.file),K=u($.changedOptions.added).join(","),Y=u($.changedOptions.removed).join(","),W=u($.changedOptions.modified).join(",");Z=`typescript-config:${X}:${$.isBreaking}:a=${K}:r=${Y}:m=${W}`;break}case"tailwind-config":{let X=m($.file),K=u($.affectedSections).join(",");Z=`tailwind-config:${X}:${$.configType}:${$.isBreaking}:${K}`;break}case"monorepo-config":{let X=m($.file),K=u($.affectedFields).join(",");Z=`monorepo-config:${X}:${$.tool}:${K}`;break}case"package-exports":{let X=u($.addedExports).join(","),K=u($.removedExports).join(",");Z=`package-exports:${$.isBreaking}:a=${X}:r=${K}`;break}case"python-migration":{let X=u($.files.map(m));Z=`python-migration:${$.tool}:${$.risk}:${X.join(",")}`;break}case"python-config":{let X=m($.file),K=u($.affectedSections).join(",");Z=`python-config:${X}:${$.configType}:${$.isBreaking}:${K}`;break}default:throw Error(`Unknown finding type: ${$.type}`)}let Q=i8(Z);return`finding.${$.type}#${Q}`}function g($,Z){let Q=u(Z),X=`${$}:${Q.join(",")}`,K=i8(X);return`flag.${$}#${K}`}function $$($){let Z=d7($);return{...$,findingId:Z}}var P$=()=>{};function r7($,Z){let Q=0,X=0;for(let K of $.diffs)for(let Y of K.hunks)Q+=Y.additions.length,X+=Y.deletions.length;return{filesChanged:$.files.length,insertions:Q,deletions:X,skippedFilesCount:Z.length}}function s7($){return a7.has($.type)}function o7($){let Z=$.find((B)=>B.type==="file-summary"),Q=$.find((B)=>B.type==="file-category"),X=$.find((B)=>B.type==="large-diff"),K=$.find((B)=>B.type==="lockfile-mismatch"),Y={added:Z?.added??[],modified:Z?.modified??[],deleted:Z?.deleted??[],renamed:Z?.renamed??[]},W={product:[],tests:[],ci:[],infra:[],database:[],docs:[],dependencies:[],config:[],artifacts:[],other:[]},q=Q?.categories??W,V=Q?.summary??[],U=[];if(X)U.push({type:"large-diff",filesChanged:X.filesChanged,linesChanged:X.linesChanged});if(K)U.push({type:"lockfile-mismatch",manifestChanged:K.manifestChanged,lockfileChanged:K.lockfileChanged});let J=Z?.changeDescriptions;return{files:Y,byCategory:q,categorySummary:V,changeDescriptions:J,warnings:U}}async function M$($){let{changeSet:Z,findings:Q,riskScore:X,requestedProfile:K,detectedProfile:Y,profileConfidence:W,profileReasons:q,filters:V,skippedFiles:U,warnings:J,noTimestamp:B,repoRoot:G,isDirty:M,mode:H}=$,O=n8(Q);if(O=O.map($$),V?.maxFindings&&O.length>V.maxFindings)O=O.slice(0,V.maxFindings);if(V?.redact)O=O.map((r)=>({...r,evidence:N2(r.evidence.map(_5))}));else O=O.map((r)=>({...r,evidence:N2(r.evidence)}));let z,_;if(G!==void 0&&M!==void 0)z=G,_=M;else if(G!==void 0)z=G,_=await J$();else if(M!==void 0)z=await V$(),_=M;else[z,_]=await Promise.all([V$(),J$()]);let D={base:Z.base,head:Z.head,range:`${Z.base}..${Z.head}`,repoRoot:z,isDirty:_,mode:H},L={requested:K,detected:Y,confidence:W,reasons:q},w=U??[],T=r7(Z,w),A={defaultExcludes:O5,excludes:V?.excludes??[],includes:V?.includes??[],redact:V?.redact??!1,maxFileBytes:V?.maxFileBytes??1048576,maxDiffBytes:V?.maxDiffBytes??5242880,maxFindings:V?.maxFindings},b=o7(O),R=O.filter((r)=>!s7(r)),h=K0(R,X.factors),y=Y0(h),r1=r8(R),a1={byArea:y,highlights:r1},K$=q0(O,Y),Y$=J??[];return{schemaVersion:"2.1",generatedAt:B?void 0:new Date().toISOString(),git:D,profile:L,stats:T,filters:A,summary:a1,categories:h,changeset:b,risk:X,findings:R,actions:K$,skippedFiles:w,warnings:Y$}}var a7;var U0=x(()=>{a8();s$();B$();P$();a7=new Set(["file-summary","file-category","large-diff","lockfile-mismatch"])});import{readFile as n7}from"node:fs/promises";async function V0($){let Z=await n7($,"utf-8");return JSON.parse(Z)}function t8($){let Z={...$};return delete Z.generatedAt,Z}function i7($,Z){let Q=(X)=>{if(X===null||typeof X!=="object")return X;if(Array.isArray(X))return X.map(Q);let K={};return Object.keys(X).sort().forEach((Y)=>{K[Y]=Q(X[Y])}),K};return JSON.stringify(Q($))===JSON.stringify(Q(Z))}function e8($){let Z=new Map;for(let Q of $){let X=Q.findingId||Q.flagId;if(X)Z.set(X,Q)}return Z}function J0($){let Z=e8($.beforeItems),Q=e8($.afterItems),X=[],K=[],Y=[];for(let[W,q]of Q){let V=Z.get(W);if(!V)X.push(W);else{let U=t8(V),J=t8(q);if(!i7(U,J))Y.push({id:W,before:V,after:q})}}for(let W of Z.keys())if(!Q.has(W))K.push(W);return X.sort(),K.sort(),Y.sort((W,q)=>W.id.localeCompare(q.id)),{added:X,removed:K,changed:Y}}function B0($,Z){let Q=[];if($.mode!==Z.mode)Q.push({code:"scope-mismatch",message:`Previous run used mode=${$.mode}, current is mode=${Z.mode}`});if($.base!==Z.base)Q.push({code:"scope-mismatch",message:`Previous run used base=${$.base}, current is base=${Z.base}`});if($.head!==Z.head)Q.push({code:"scope-mismatch",message:`Previous run used head=${$.head}, current is head=${Z.head}`});if($.profile!==Z.profile)Q.push({code:"scope-mismatch",message:`Previous run used profile=${$.profile}, current is profile=${Z.profile}`});let X=JSON.stringify($.include||[]),K=JSON.stringify(Z.include||[]);if(X!==K)Q.push({code:"scope-mismatch",message:"Include filters differ between runs"});let Y=JSON.stringify($.exclude||[]),W=JSON.stringify(Z.exclude||[]);if(Y!==W)Q.push({code:"scope-mismatch",message:"Exclude filters differ between runs"});if($.only!==void 0||Z.only!==void 0){let q=JSON.stringify($.only||null),V=JSON.stringify(Z.only||null);if(q!==V)Q.push({code:"scope-mismatch",message:"Category filters differ between runs"})}return Q}function $9($){let Z;if($.git.mode)Z=$.git.mode;else Z=$.git.base?"branch":"unstaged";return{mode:Z,base:$.git.base||null,head:$.git.head||null,profile:$.profile.detected,include:$.filters.includes,exclude:$.filters.excludes}}function Z9($){let Z;if($.range.mode)Z=$.range.mode;else Z=$.range.base?"branch":"unstaged";return{mode:Z,base:$.range.base||null,head:$.range.head||null,only:$.filters?.only||null,exclude:$.filters?.exclude}}var T2=()=>{};var Q9={};A1(Q9,{computeFactsDelta:()=>x2});async function x2($){let{sincePath:Z,currentFacts:Q,mode:X,base:K,head:Y,profile:W,include:q,exclude:V,sinceStrict:U}=$,J;try{J=await V0(Z)}catch(L){let w=L instanceof Error?L.message:String(L);throw new v(`Failed to load previous facts from ${Z}: ${w}`,1)}if(!J.schemaVersion||!J.findings)throw new v(`File ${Z} does not appear to be a valid facts output`,1);let B={mode:X,base:K,head:Y,profile:W,include:q,exclude:V},G=$9(J),M=B0(G,B);if(U&&M.length>0)throw new v(`Scope mismatch detected (--since-strict): ${M.map((L)=>L.message).join("; ")}`,1);let{added:H,removed:O,changed:z}=J0({beforeItems:J.findings,afterItems:Q.findings}),_=z.map((L)=>({findingId:L.id,before:L.before,after:L.after})),D=["--mode",X];if(K)D.push("--base",K);if(Y)D.push("--head",Y);if(D.push("--since",Z),U)D.push("--since-strict");return{schemaVersion:"1.0",generatedAt:new Date().toISOString(),command:{name:"facts",args:D},since:{path:Z,schemaVersion:J.schemaVersion},current:{schemaVersion:Q.schemaVersion},scope:B,warnings:M,delta:{added:H,removed:O,changed:_},summary:{addedCount:H.length,removedCount:O.length,changedCount:_.length}}}var w2=x(()=>{T2();H1()});var X9={};A1(X9,{executeFacts:()=>t7,deriveActions:()=>q0,computeFactsDelta:()=>x2,buildSummaryByArea:()=>Y0,buildFacts:()=>M$,aggregateCategories:()=>K0});async function t7($){return M$($)}var K9=x(()=>{U0();U0();w2()});var q9={};A1(q9,{renderSarif:()=>ZQ,SARIF_RULES:()=>Y9});function $Q($){return"file:///"+$.replace(/\\/g,"/")+"/"}function ZQ($,Z){let Q=XQ($.findings,Z),X=new Set(Q.map((Y)=>Y.ruleId)),K=Array.from(X).sort().map((Y)=>{let W=Y9[Y];if(!W)throw Error(`Unknown SARIF rule ID: ${Y}`);return QQ(W)});return{version:"2.1.0",$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",runs:[{tool:{driver:{name:"branch-narrator",version:o2(),informationUri:"https://github.com/better-vibe/branch-narrator",rules:K}},results:Q,originalUriBaseIds:{SRCROOT:{uri:$Q($.git.repoRoot)}}}]}}function QQ($){return{id:$.id,name:$.name,shortDescription:{text:$.shortDescription},fullDescription:{text:$.fullDescription},defaultConfiguration:{level:$.defaultLevel},properties:{category:$.category}}}function XQ($,Z){let Q=[],X=[...$].sort((K,Y)=>{if(K.type!==Y.type)return K.type.localeCompare(Y.type);return(K.findingId||"").localeCompare(Y.findingId||"")});for(let K of X){let Y=KQ(K,Z);if(Y)Q.push(Y)}return Q}function KQ($,Z){switch($.type){case"db-migration":return YQ($);case"dependency-change":return qQ($);case"env-var":return WQ($,Z);case"cloudflare-change":return UQ($);case"route-change":return VQ($);case"ci-workflow":return JQ($);case"security-file":return BQ($);case"graphql-change":return GQ($);case"package-exports":return OQ($);case"stencil-component-change":return MQ($);case"stencil-prop-change":return HQ($);case"stencil-event-change":return _Q($);case"stencil-method-change":return zQ($);case"stencil-slot-change":return LQ($);case"typescript-config":return jQ($);case"sql-risk":return DQ($);case"infra-change":return AQ($);case"test-gap":return NQ($);case"large-diff":return RQ($);default:return null}}function YQ($){let Z=$.risk==="high"?"BNR001":"BNR002",Q=$.risk==="high"?"error":"warning",X=$.evidence.map((W)=>({physicalLocation:{artifactLocation:{uri:W.file,uriBaseId:"SRCROOT"},region:W.line?{startLine:W.line}:void 0}})),K=$.reasons.join(", "),Y=$.risk==="high"?`Dangerous SQL migration detected: ${K}`:`Database migration changed: ${K}`;return{ruleId:Z,level:Q,message:{text:Y},locations:X,partialFingerprints:{findingId:$.findingId||""},properties:{tool:$.tool,files:$.files,risk:$.risk}}}function qQ($){if($.impact!=="major"||!e7.includes($.name))return null;let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR003",level:"warning",message:{text:`Major version bump: ${$.name} ${$.from||"?"} → ${$.to||"?"}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{dependency:$.name,from:$.from,to:$.to,section:$.section}}}function WQ($,Z){let Q=[];for(let X of $.evidence){let K=X.line;if(K==null&&X.excerpt){let Y=Z.diffs.find((W)=>W.path===X.file);if(Y){let q=r0(Y).find((V)=>V.line.includes(X.excerpt));if(q)K=q.lineNumber}}Q.push({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:K!=null?{startLine:K}:void 0}})}return{ruleId:"BNR004",level:"warning",message:{text:`New environment variable referenced: ${$.name}`},locations:Q,partialFingerprints:{findingId:$.findingId||""},properties:{envVar:$.name,change:$.change,evidenceFiles:$.evidenceFiles}}}function UQ($){let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR005",level:"note",message:{text:`Cloudflare configuration changed in ${$.files.join(", ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{area:$.area,files:$.files}}}function VQ($){let Z=$.evidence.map((K)=>({physicalLocation:{artifactLocation:{uri:K.file,uriBaseId:"SRCROOT"},region:K.line?{startLine:K.line}:void 0}})),Q=$.methods?` (${$.methods.join(", ")})`:"";return{ruleId:"BNR006",level:"note",message:{text:`API endpoint ${$.change==="added"?"added":$.change==="deleted"?"deleted":"modified"}: ${$.routeId}${Q}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{routeId:$.routeId,file:$.file,change:$.change,routeType:$.routeType,methods:$.methods}}}function JQ($){if($.riskType!=="permissions_broadened"&&$.riskType!=="pull_request_target")return null;let Z=$.riskType==="permissions_broadened"?"BNR007":"BNR008",Q=$.evidence.map((K)=>({physicalLocation:{artifactLocation:{uri:K.file,uriBaseId:"SRCROOT"},region:K.line?{startLine:K.line}:void 0}})),X=$.riskType==="permissions_broadened"?`CI workflow permissions broadened in ${$.file}: ${$.details}`:`CI workflow uses pull_request_target in ${$.file}: ${$.details}`;return{ruleId:Z,level:"error",message:{text:X},locations:Q,partialFingerprints:{findingId:$.findingId||""},properties:{file:$.file,riskType:$.riskType,details:$.details}}}function BQ($){let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR009",level:"warning",message:{text:`Security-sensitive files changed: ${$.files.join(", ")}. Reasons: ${$.reasons.join(", ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{files:$.files,reasons:$.reasons}}}function GQ($){if(!$.isBreaking)return null;let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR010",level:"error",message:{text:`Breaking GraphQL schema changes in ${$.file}: ${$.breakingChanges.join(", ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{file:$.file,breakingChanges:$.breakingChanges,addedElements:$.addedElements}}}function OQ($){if(!$.isBreaking)return null;let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}})),Q=[];if($.removedExports.length>0)Q.push(`removed exports: ${$.removedExports.join(", ")}`);if($.binChanges.removed.length>0)Q.push(`removed bins: ${$.binChanges.removed.join(", ")}`);return{ruleId:"BNR011",level:"error",message:{text:`Breaking package exports changes: ${Q.join("; ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{removedExports:$.removedExports,addedExports:$.addedExports,binChanges:$.binChanges}}}function MQ($){if($.change!=="removed")return null;let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR012",level:"warning",message:{text:`Stencil component removed: <${$.tag}>`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{tag:$.tag,change:$.change,file:$.file}}}function HQ($){if($.change!=="removed")return null;let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR012",level:"warning",message:{text:`Stencil prop removed: <${$.tag}> @Prop() ${$.propName}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{tag:$.tag,propName:$.propName,change:$.change,file:$.file}}}function _Q($){if($.change!=="removed")return null;let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR012",level:"warning",message:{text:`Stencil event removed: <${$.tag}> @Event() ${$.eventName}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{tag:$.tag,eventName:$.eventName,change:$.change,file:$.file}}}function zQ($){if($.change!=="removed")return null;let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR012",level:"warning",message:{text:`Stencil method removed: <${$.tag}> @Method() ${$.methodName}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{tag:$.tag,methodName:$.methodName,change:$.change,file:$.file}}}function LQ($){if($.change!=="removed")return null;let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR012",level:"warning",message:{text:`Stencil ${$.slotName==="default"?"default slot":`slot "${$.slotName}"`} removed from <${$.tag}>`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{tag:$.tag,slotName:$.slotName,change:$.change,file:$.file}}}function jQ($){if(!$.isBreaking)return null;let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}})),Q=[];if($.strictnessChanges.length>0)Q.push($.strictnessChanges.join(", "));if($.changedOptions.removed.length>0)Q.push(`removed: ${$.changedOptions.removed.join(", ")}`);return{ruleId:"BNR013",level:"warning",message:{text:`Breaking TypeScript config changes in ${$.file}: ${Q.join("; ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{file:$.file,changedOptions:$.changedOptions,strictnessChanges:$.strictnessChanges}}}function DQ($){if($.riskType!=="destructive")return null;let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR014",level:"error",message:{text:`Destructive SQL operation in ${$.file}: ${$.details}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{file:$.file,riskType:$.riskType,details:$.details}}}function AQ($){let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR015",level:"warning",message:{text:`${{dockerfile:"Dockerfile",terraform:"Terraform",k8s:"Kubernetes"}[$.infraType]} configuration changed: ${$.files.join(", ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{infraType:$.infraType,files:$.files}}}function NQ($){let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR016",level:"note",message:{text:`Test coverage gap: ${$.prodFilesChanged} production files changed, ${$.testFilesChanged} test files changed`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{prodFilesChanged:$.prodFilesChanged,testFilesChanged:$.testFilesChanged}}}function RQ($){let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR017",level:"note",message:{text:`Large diff detected: ${$.filesChanged} files changed, ${$.linesChanged} lines modified`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{filesChanged:$.filesChanged,linesChanged:$.linesChanged}}}var Y9,e7;var W9=x(()=>{l$();Y9={BNR001:{id:"BNR001",name:"DangerousSqlInMigration",shortDescription:"Dangerous SQL detected in migration",fullDescription:"Database migration contains potentially destructive SQL operations (DROP, TRUNCATE, ALTER TYPE, etc.) that could cause data loss or service disruption.",defaultLevel:"error",category:"database"},BNR002:{id:"BNR002",name:"MigrationChanged",shortDescription:"Migration changed (non-destructive)",fullDescription:"Database migration file has been modified or added. Review schema changes for compatibility and rollback safety.",defaultLevel:"warning",category:"database"},BNR003:{id:"BNR003",name:"MajorDependencyBump",shortDescription:"Major bump in critical dependencies",fullDescription:"Major version bump detected in critical framework dependencies (e.g., @sveltejs/kit, svelte, vite, react, next). Major upgrades may introduce breaking changes.",defaultLevel:"warning",category:"dependencies"},BNR004:{id:"BNR004",name:"NewEnvVarReference",shortDescription:"New environment variable reference detected",fullDescription:"Code references a new environment variable. Ensure this variable is documented and configured in all deployment environments.",defaultLevel:"warning",category:"config_env"},BNR005:{id:"BNR005",name:"CloudflareConfigChanged",shortDescription:"Cloudflare configuration changed",fullDescription:"Cloudflare configuration files (wrangler.toml, Pages workflows) have been modified. Review deployment settings and worker configurations.",defaultLevel:"note",category:"infra"},BNR006:{id:"BNR006",name:"EndpointChanged",shortDescription:"API endpoint changed",fullDescription:"API endpoint file has been added, modified, or deleted. Verify API contract compatibility and update client code if needed.",defaultLevel:"note",category:"api"},BNR007:{id:"BNR007",name:"CIWorkflowPermissionsBroadened",shortDescription:"CI workflow permissions broadened",fullDescription:"GitHub Actions workflow has broadened permissions, which could allow unauthorized access to secrets or repository data. Review the permission changes carefully.",defaultLevel:"error",category:"security"},BNR008:{id:"BNR008",name:"CIWorkflowPullRequestTarget",shortDescription:"CI workflow uses pull_request_target",fullDescription:"GitHub Actions workflow uses pull_request_target trigger, which runs with write permissions on the base repository. This can be exploited if the workflow checks out or runs code from the PR.",defaultLevel:"error",category:"security"},BNR009:{id:"BNR009",name:"SecurityFileChanged",shortDescription:"Security-sensitive file changed",fullDescription:"A file related to authentication, authorization, or security configuration has been modified. Review these changes carefully for potential vulnerabilities.",defaultLevel:"warning",category:"security"},BNR010:{id:"BNR010",name:"GraphQLBreakingChange",shortDescription:"Breaking change in GraphQL schema",fullDescription:"GraphQL schema contains breaking changes such as removed types, fields, or arguments. This may break existing clients consuming the API.",defaultLevel:"error",category:"api"},BNR011:{id:"BNR011",name:"PackageExportsBreakingChange",shortDescription:"Breaking change in package exports",fullDescription:"Package exports have breaking changes such as removed exports or modified bin entries. This may break downstream consumers of this package.",defaultLevel:"error",category:"api"},BNR012:{id:"BNR012",name:"StencilAPIBreakingChange",shortDescription:"Breaking change in Stencil component API",fullDescription:"Stencil web component has breaking API changes such as removed props, events, methods, or slots. This may break consumers of the component library.",defaultLevel:"warning",category:"api"},BNR013:{id:"BNR013",name:"TypeScriptConfigBreaking",shortDescription:"Breaking TypeScript configuration change",fullDescription:"TypeScript configuration has breaking changes that may cause compilation errors in the codebase, such as stricter type checking options.",defaultLevel:"warning",category:"config_env"},BNR014:{id:"BNR014",name:"DestructiveSQL",shortDescription:"Destructive SQL operation detected",fullDescription:"SQL file contains destructive operations (DROP, TRUNCATE, DELETE without WHERE) that could cause data loss. Review carefully before execution.",defaultLevel:"error",category:"database"},BNR015:{id:"BNR015",name:"InfrastructureChanged",shortDescription:"Infrastructure configuration changed",fullDescription:"Infrastructure files (Dockerfile, Terraform, Kubernetes) have been modified. Review for security implications and deployment impact.",defaultLevel:"warning",category:"infra"},BNR016:{id:"BNR016",name:"TestGapDetected",shortDescription:"Test coverage gap detected",fullDescription:"Production code was modified but no corresponding test files were changed. Consider adding tests to cover the new or modified functionality.",defaultLevel:"note",category:"quality"},BNR017:{id:"BNR017",name:"LargeDiff",shortDescription:"Large diff detected",fullDescription:"This change has a large number of modified files or lines, which may indicate a refactoring or generated code. Consider breaking into smaller PRs for easier review.",defaultLevel:"note",category:"quality"}},e7=["@sveltejs/kit","svelte","vite","react","react-dom","next","@stencil/core"]});function E2($){if($==="pnpm-lock.yaml"||$==="package-lock.json"||$==="yarn.lock"||$==="bun.lockb")return{skip:!0,reason:"lockfile"};if($.endsWith(".d.ts"))return{skip:!0,reason:"generated file"};if($.endsWith(".log"))return{skip:!0,reason:"log file"};let Z=["dist/","build/","coverage/",".turbo/",".next/","out/",".cache/"];for(let Q of Z)if($.includes(Q))return{skip:!0,reason:"build artifact"};return{skip:!1}}var TQ;var I2=x(()=>{TQ=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","**/*.d.ts","**/*.log","dist/**","build/**","coverage/**",".turbo/**",".next/**","out/**",".cache/**"]});function U9($){let Z=$;Z=Z.replace(EQ,"<redacted-github-token>");for(let{eqPattern:Q,colonPattern:X}of wQ)Q.lastIndex=0,X.lastIndex=0,Z=Z.replace(Q,(K,Y)=>`${Y}=<redacted>`),Z=Z.replace(X,(K,Y)=>`${Y}: <redacted>`);if(!Z.includes("<redacted")&&!Z.includes("hash")&&!Z.includes("checksum"))Z=Z.replace(IQ,"<redacted-value>");return Z}function b2($){return $.map(U9)}var xQ,wQ,EQ,IQ;var C2=x(()=>{xQ=[/token/i,/secret/i,/password/i,/api[_-]?key/i,/private[_-]?key/i,/access[_-]?key/i,/auth[_-]?token/i],wQ=xQ.map(($)=>({eqPattern:new RegExp(`(${$.source})\\s*=\\s*['"]?([^'"\\s}<]+)['"]?`,"gi"),colonPattern:new RegExp(`(${$.source})\\s*:\\s*['"]?([^'"\\s,}<]+)['"]?`,"gi")})),EQ=/(ghp_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9_]+)/g,IQ=/\b[a-zA-Z0-9+/=]{32,}\b/g});function bQ($){let Z={api:0,churn:0,ci:0,db:0,deps:0,infra:0,security:0,tests:0};for(let Q of $)Z[Q.category]+=Q.effectiveScore;for(let Q of Object.keys(Z))Z[Q]=Math.min(100,Z[Q]);return Z}function CQ($){let Z=Object.values($);if(Z.length===0)return 0;let Q=Math.max(...Z),K=[...Z].sort((q,V)=>V-q).slice(0,3);while(K.length<3)K.push(0);let Y=K.reduce((q,V)=>q+V,0)/3,W=0.6*Q+0.4*Y;return Math.round(Math.max(0,Math.min(100,W)))}function PQ($){if($>=81)return"critical";if($>=61)return"high";if($>=41)return"elevated";if($>=21)return"moderate";return"low"}function yQ($){let Q=Object.entries($).sort((U,J)=>J[1]-U[1]),X=Q.length>0?Q[0]:["security",0],K=Q.slice(0,3).map(([U,J])=>({category:U,score:J})),Y=X[1],W=K.map((U)=>U.score);while(W.length<3)W.push(0);let q=W.reduce((U,J)=>U+J,0)/3,V=`riskScore = round(0.6 * ${Y} + 0.4 * ${q.toFixed(2)})`;return{maxCategory:{category:X[0],score:Y},topCategories:K,formula:V}}function P2($,Z,Q){let X=$;if(Z&&Z.length>0)X=X.filter((K)=>Z.includes(K.category));if(Q&&Q.length>0)X=X.filter((K)=>!Q.includes(K.category));return X}function y2($,Z,Q,X,K){let Y=bQ(Q),W=CQ(Y),q=PQ(W),V={schemaVersion:"2.0",range:{base:$,head:Z,mode:K?.mode},riskScore:W,riskLevel:q,categoryScores:Y,flags:o8(Q),skippedFiles:X};if(!K?.noTimestamp)V.generatedAt=new Date().toISOString();if(K?.explainScore)V.scoreBreakdown=yQ(Y);if(K?.only||K?.exclude)V.filters={only:K.only,exclude:K.exclude};return V}var k2=()=>{};function V1($){return $.evidence.map((Z)=>({file:Z.file,hunk:Z.hunk?`@@ -${Z.hunk.oldStart},${Z.hunk.oldLines} +${Z.hunk.newStart},${Z.hunk.newLines} @@`:void 0,lines:Z.excerpt.split(`
|
|
47
|
-
`).slice(0,5)}))}function kQ($){let Z=[];for(let Q of $){let X=[Q.findingId];switch(Q.riskType){case"permissions_broadened":{Z.push({ruleKey:"security.workflow_permissions_broadened",flagId:g("security.workflow_permissions_broadened",X),relatedFindingIds:X,category:"security",score:35,confidence:0.9,title:"Workflow permissions broadened",summary:`Workflow ${Q.file} has broadened permissions (write access)`,evidence:V1(Q),suggestedChecks:["Review if write permissions are necessary","Ensure principle of least privilege","Check if GITHUB_TOKEN usage is secure"],effectiveScore:Math.round(31.5)});break}case"pull_request_target":{Z.push({ruleKey:"security.workflow_uses_pull_request_target",flagId:g("security.workflow_uses_pull_request_target",X),relatedFindingIds:X,category:"security",score:40,confidence:0.9,title:"Workflow uses pull_request_target",summary:`Workflow ${Q.file} uses pull_request_target event (can expose secrets)`,evidence:V1(Q),suggestedChecks:["Ensure no untrusted code is executed in this context","Review if pull_request_target is necessary (vs pull_request)","Verify secrets are not exposed to PR authors"],effectiveScore:Math.round(36)});break}case"remote_script_download":{Z.push({ruleKey:"security.workflow_downloads_remote_script",flagId:g("security.workflow_downloads_remote_script",X),relatedFindingIds:X,category:"security",score:45,confidence:0.85,title:"Workflow downloads and executes remote scripts",summary:`Workflow ${Q.file} downloads and pipes to shell (supply chain risk)`,evidence:V1(Q),suggestedChecks:["Pin script sources to specific commit SHAs","Verify script integrity with checksums","Consider vendoring the script instead"],effectiveScore:Math.round(38.25)});break}case"pipeline_changed":{Z.push({ruleKey:"ci.pipeline_changed",flagId:g("ci.pipeline_changed",X),relatedFindingIds:X,category:"ci",score:10,confidence:0.7,title:"CI/CD pipeline configuration changed",summary:`Pipeline ${Q.file} was modified`,evidence:V1(Q),suggestedChecks:["Review pipeline changes for security implications","Test pipeline changes in a non-production environment"],effectiveScore:Math.round(7)});break}}}return Z}function SQ($){let Z=[];for(let Q of $){let X=[Q.findingId];switch(Q.riskType){case"destructive":{Z.push({ruleKey:"db.destructive_sql",flagId:g("db.destructive_sql",X),relatedFindingIds:X,category:"db",score:45,confidence:0.9,title:"Destructive SQL detected",summary:`Migration ${Q.file} contains DROP TABLE/COLUMN or TRUNCATE`,evidence:V1(Q),suggestedChecks:["Backup data before running migration","Verify this is intentional data deletion","Test migration rollback procedure","Consider making column nullable instead of dropping"],effectiveScore:Math.round(40.5)});break}case"schema_change":{Z.push({ruleKey:"db.schema_change_risky",flagId:g("db.schema_change_risky",X),relatedFindingIds:X,category:"db",score:30,confidence:0.85,title:"Risky schema change detected",summary:`Migration ${Q.file} contains ALTER COLUMN or TYPE change`,evidence:V1(Q),suggestedChecks:["Test schema changes on production-like data","Check for data type compatibility","Monitor migration execution time (may lock table)"],effectiveScore:Math.round(25.5)});break}case"unscoped_modification":{Z.push({ruleKey:"db.unscoped_data_modification",flagId:g("db.unscoped_data_modification",X),relatedFindingIds:X,category:"db",score:35,confidence:0.75,title:"Unscoped data modification detected",summary:`Migration ${Q.file} contains UPDATE/DELETE without WHERE clause`,evidence:V1(Q),suggestedChecks:["Verify this affects all rows intentionally","Add WHERE clause if only subset should be modified","Test on staging data first"],effectiveScore:Math.round(26.25)});break}}}return Z}function vQ($){let Z=[],Q=$.filter((q)=>q.type==="stencil-component-change"),X=$.filter((q)=>q.type==="stencil-prop-change"),K=$.filter((q)=>q.type==="stencil-event-change"),Y=$.filter((q)=>q.type==="stencil-method-change"),W=$.filter((q)=>q.type==="stencil-slot-change");for(let q of Q){if(q.change==="tag-changed"){let U=[q.findingId];Z.push({ruleKey:"stencil.tag_changed",flagId:g("stencil.tag_changed",U),relatedFindingIds:U,category:"api",score:45,confidence:0.95,title:"Component tag changed",summary:`Tag changed from "${q.fromTag}" to "${q.toTag}"`,evidence:V1(q),suggestedChecks:["Update all usages of this component","This is a breaking change"],effectiveScore:Math.round(42.75)})}if(q.change==="shadow-changed"){let U=[q.findingId];Z.push({ruleKey:"stencil.shadow_changed",flagId:g("stencil.shadow_changed",U),relatedFindingIds:U,category:"api",score:25,confidence:0.9,title:"Shadow DOM configuration changed",summary:`Shadow DOM enabled changed from ${q.fromShadow} to ${q.toShadow}`,evidence:V1(q),suggestedChecks:["Check styles and global styling impact"],effectiveScore:Math.round(22.5)})}}for(let q of X)if(q.change==="removed"){let U=[q.findingId];Z.push({ruleKey:"stencil.prop_removed",flagId:g("stencil.prop_removed",U),relatedFindingIds:U,category:"api",score:40,confidence:0.95,title:"Component prop removed",summary:`Prop "${q.propName}" removed from <${q.tag}>`,evidence:V1(q),suggestedChecks:["This is a breaking change","Check usages"],effectiveScore:Math.round(38)})}else if(q.change==="changed"){let U=[q.findingId];Z.push({ruleKey:"stencil.prop_changed",flagId:g("stencil.prop_changed",U),relatedFindingIds:U,category:"api",score:35,confidence:0.9,title:"Component prop modified",summary:`Prop "${q.propName}" options changed`,evidence:V1(q),suggestedChecks:["Check for attribute/reflect/mutable changes"],effectiveScore:Math.round(31.5)})}for(let q of K)if(q.change==="removed"){let U=[q.findingId];Z.push({ruleKey:"stencil.event_removed",flagId:g("stencil.event_removed",U),relatedFindingIds:U,category:"api",score:40,confidence:0.95,title:"Component event removed",summary:`Event "${q.eventName}" removed from <${q.tag}>`,evidence:V1(q),suggestedChecks:["This is a breaking change","Check event listeners"],effectiveScore:Math.round(38)})}else if(q.change==="changed"){let U=[q.findingId];Z.push({ruleKey:"stencil.event_changed",flagId:g("stencil.event_changed",U),relatedFindingIds:U,category:"api",score:35,confidence:0.9,title:"Component event modified",summary:`Event "${q.eventName}" options changed`,evidence:V1(q),suggestedChecks:["Check bubbles/composed/cancelable options"],effectiveScore:Math.round(31.5)})}for(let q of Y)if(q.change==="removed"){let U=[q.findingId];Z.push({ruleKey:"stencil.method_removed",flagId:g("stencil.method_removed",U),relatedFindingIds:U,category:"api",score:40,confidence:0.95,title:"Component method removed",summary:`Method "${q.methodName}" removed from <${q.tag}>`,evidence:V1(q),suggestedChecks:["This is a breaking change","Check usages"],effectiveScore:Math.round(38)})}else if(q.change==="changed");for(let q of W)if(q.change==="removed"){let U=[q.findingId];Z.push({ruleKey:"stencil.slot_removed",flagId:g("stencil.slot_removed",U),relatedFindingIds:U,category:"api",score:35,confidence:0.9,title:"Component slot removed",summary:`Slot "${q.slotName}" removed from <${q.tag}>`,evidence:V1(q),suggestedChecks:["Check content projection usages"],effectiveScore:Math.round(31.5)})}return Z}function S2($){let Z=[],Q=$.filter((O)=>O.type==="ci-workflow"),X=$.filter((O)=>O.type==="sql-risk"),K=$.filter((O)=>O.type==="infra-change"),Y=$.filter((O)=>O.type==="api-contract-change"),W=$.filter((O)=>O.type==="large-diff"),q=$.filter((O)=>O.type==="lockfile-mismatch"),V=$.filter((O)=>O.type==="test-gap"),U=$.filter((O)=>O.type==="dependency-change"),J=$.filter((O)=>O.type==="db-migration"),B=$.filter((O)=>O.type==="test-change");Z.push(...kQ(Q)),Z.push(...SQ(X)),Z.push(...vQ($));for(let O of K){let z=[O.findingId],_=`infra.${O.infraType}_changed`,D={dockerfile:"Dockerfile changed",terraform:"Terraform configuration changed",k8s:"Kubernetes manifest changed"};Z.push({ruleKey:_,flagId:g(_,z),relatedFindingIds:z,category:"infra",score:20,confidence:0.8,title:D[O.infraType],summary:`${O.files.length} ${O.infraType} ${O.files.length===1?"file":"files"} changed`,evidence:O.files.slice(0,3).map((L)=>({file:L,lines:["File changed"]})),suggestedChecks:["Review infrastructure changes carefully","Test in staging environment","Verify no unintended resource changes"],effectiveScore:Math.round(16)})}if(Y.length>0){let O=Y.map((D)=>D.findingId),z="api.contract_changed",_=Y.flatMap((D)=>D.files);Z.push({ruleKey:"api.contract_changed",flagId:g("api.contract_changed",O),relatedFindingIds:O,category:"api",score:25,confidence:0.85,title:"API contract changed",summary:`${_.length} API ${_.length===1?"file":"files"} changed`,evidence:_.slice(0,3).map((D)=>({file:D,lines:["File changed"]})),suggestedChecks:["Verify backwards compatibility","Update API documentation","Notify API consumers of changes"],effectiveScore:Math.round(21.25)})}if(W.length>0){let O=W[0],z=[O.findingId],_="churn.large_diff";Z.push({ruleKey:"churn.large_diff",flagId:g("churn.large_diff",z),relatedFindingIds:z,category:"churn",score:15,confidence:0.9,title:"Large diff detected",summary:`${O.filesChanged} files changed, ${O.linesChanged} lines modified`,evidence:[],suggestedChecks:["Consider breaking into smaller PRs","Ensure adequate test coverage","Review carefully for unintended changes"],effectiveScore:Math.round(13.5)})}for(let O of q){let z=[O.findingId],_="deps.lockfile_without_manifest";Z.push({ruleKey:"deps.lockfile_without_manifest",flagId:g("deps.lockfile_without_manifest",z),relatedFindingIds:z,category:"deps",score:20,confidence:0.9,title:"Lockfile changed without manifest",summary:O.manifestChanged?"package.json changed without lockfile update":"Lockfile changed without package.json update",evidence:[],suggestedChecks:["Run package manager install to sync lockfile","Verify dependencies are correctly resolved"],effectiveScore:Math.round(18)})}for(let O of V){let z=[O.findingId],_="tests.possible_gap";Z.push({ruleKey:"tests.possible_gap",flagId:g("tests.possible_gap",z),relatedFindingIds:z,category:"tests",score:18,confidence:0.7,title:"Possible test coverage gap",summary:`${O.prodFilesChanged} production files changed with no test updates`,evidence:[],suggestedChecks:["Add tests for new functionality","Update existing tests if behavior changed"],effectiveScore:Math.round(12.6)})}let G=U.filter((O)=>O.section==="dependencies"&&!O.from);if(G.length>0){let O=G.map((_)=>_.findingId),z="deps.new_prod_dependency";Z.push({ruleKey:"deps.new_prod_dependency",flagId:g("deps.new_prod_dependency",O),relatedFindingIds:O,category:"deps",score:15,confidence:0.85,title:"New production dependencies added",summary:`${G.length} new production ${G.length===1?"dependency":"dependencies"} added`,evidence:G.slice(0,5).map((_)=>({file:"package.json",lines:[`+ "${_.name}": "${_.to}"`]})),suggestedChecks:["Review new dependencies for security vulnerabilities","Check license compatibility","Verify dependencies are actively maintained"],tags:G.map((_)=>_.name),effectiveScore:Math.round(12.75)})}let M=U.filter((O)=>O.impact==="major");if(M.length>0){let O=M.map((_)=>_.findingId),z="deps.major_version_bump";Z.push({ruleKey:"deps.major_version_bump",flagId:g("deps.major_version_bump",O),relatedFindingIds:O,category:"deps",score:25,confidence:0.9,title:"Major dependency version bump",summary:`${M.length} ${M.length===1?"dependency":"dependencies"} with major version changes`,evidence:M.slice(0,5).map((_)=>({file:"package.json",lines:[`"${_.name}": "${_.from}" -> "${_.to}"`]})),suggestedChecks:["Review breaking changes in dependency changelogs","Update code for API changes","Run full test suite"],tags:M.map((_)=>_.name),effectiveScore:Math.round(22.5)})}if(J.length>0){let O=J.map((_)=>_.findingId),z="db.migrations_changed";Z.push({ruleKey:"db.migrations_changed",flagId:g("db.migrations_changed",O),relatedFindingIds:O,category:"db",score:12,confidence:0.8,title:"Database migrations changed",summary:`${J.length} migration/SQL ${J.length===1?"file":"files"} changed`,evidence:J.slice(0,3).flatMap((_)=>_.files.map((D)=>({file:D,lines:["Migration file changed"]}))),suggestedChecks:["Test migrations on a staging database","Ensure migrations are reversible","Check for data loss or downtime impact"],effectiveScore:Math.round(9.600000000000001)})}if(B.length>0){let O=B.map((_)=>_.findingId),z="tests.changed";Z.push({ruleKey:"tests.changed",flagId:g("tests.changed",O),relatedFindingIds:O,category:"tests",score:5,confidence:0.8,title:"Test files changed",summary:`${B.length} test ${B.length===1?"file":"files"} modified`,evidence:B.slice(0,3).flatMap((_)=>_.files.map((D)=>({file:D,lines:["Test file changed"]}))),suggestedChecks:["Verify tests still pass","Review test coverage changes"],effectiveScore:Math.round(4)})}let H=$.filter((O)=>O.type==="test-parity-violation");if(H.length>0){let O=H.map((A)=>A.findingId),z="tests.missing_parity",_=H.filter((A)=>A.confidence==="high").length,D=H.filter((A)=>A.confidence==="medium").length,L=12+_*2+D*1,w=Math.min(L,25),T=_>D?0.85:0.7;Z.push({ruleKey:"tests.missing_parity",flagId:g("tests.missing_parity",O),relatedFindingIds:O,category:"tests",score:w,confidence:T,title:"Source files without test coverage",summary:`${H.length} source ${H.length===1?"file":"files"} modified without corresponding tests`,evidence:H.slice(0,5).map((A)=>({file:A.sourceFile,lines:[`No test file found (expected: ${A.expectedTestLocations[0]||"unknown"})`]})),suggestedChecks:["Add tests for new/changed code","Verify existing tests cover the changes","Consider if these files need unit tests"],effectiveScore:Math.round(w*T)})}return Z}var v2=x(()=>{P$()});function FQ($,Z=!1){return Z?JSON.stringify($,null,2):JSON.stringify($)}function mQ($){let Z=[];Z.push("# Risk Report"),Z.push(""),Z.push(`**Range:** \`${$.range.base}..${$.range.head}\``),Z.push("");let Q=hQ($.riskLevel);Z.push(`## Overall Risk: ${Q} ${$.riskLevel.toUpperCase()}`),Z.push(""),Z.push(`**Score:** ${$.riskScore}/100`),Z.push(""),Z.push("### Category Scores"),Z.push("");let X=Object.entries($.categoryScores).sort((K,Y)=>Y[1]-K[1]);for(let[K,Y]of X)if(Y>0){let W="█".repeat(Math.floor(Y/10));Z.push(`- **${K}**: ${Y}/100 ${W}`)}if(Z.push(""),$.flags.length>0){Z.push("## Risk Flags"),Z.push("");let K=gQ($.flags);for(let[Y,W]of Object.entries(K)){if(W.length===0)continue;Z.push(`### ${Y.toUpperCase()}`),Z.push("");for(let q of W){if(Z.push(`#### ${q.title}`),Z.push(""),Z.push(`**Rule:** \`${q.ruleKey}\``),Z.push(`**Flag ID:** \`${q.flagId}\``),Z.push(`**Score:** ${q.effectiveScore}/100 (base: ${q.score}, confidence: ${q.confidence})`),Z.push(""),Z.push(q.summary),Z.push(""),q.evidence.length>0){Z.push("**Evidence:**"),Z.push("");for(let V of q.evidence){if(Z.push(`- **${V.file}**`),V.hunk)Z.push(` \`${V.hunk}\``);if(V.lines.length>0){Z.push(" ```");for(let U of V.lines)Z.push(` ${U}`);Z.push(" ```")}}Z.push("")}if(q.suggestedChecks.length>0){Z.push("**Suggested Checks:**"),Z.push("");for(let V of q.suggestedChecks)Z.push(`- ${V}`);Z.push("")}}}}if($.scoreBreakdown){Z.push("## Score Breakdown"),Z.push(""),Z.push(`**Max Category:** ${$.scoreBreakdown.maxCategory.category} (${$.scoreBreakdown.maxCategory.score})`),Z.push(""),Z.push("**Top 3 Categories:**");for(let K of $.scoreBreakdown.topCategories)Z.push(`- ${K.category}: ${K.score}`);Z.push(""),Z.push(`**Formula:** \`${$.scoreBreakdown.formula}\``),Z.push("")}if($.skippedFiles.length>0){Z.push("## Skipped Files"),Z.push(""),Z.push(`${$.skippedFiles.length} files were skipped:`),Z.push("");for(let K of $.skippedFiles.slice(0,20))Z.push(`- \`${K.file}\` (${K.reason})`);if($.skippedFiles.length>20)Z.push(`- ... and ${$.skippedFiles.length-20} more`);Z.push("")}return Z.join(`
|
|
48
|
-
`)
|
|
49
|
-
`)
|
|
50
|
-
`)
|
|
51
|
-
`)),Z.push("```"),Z.push("")}}if($.relatedFindings&&$.relatedFindings.length>0){Z.push("## Related Findings"),Z.push("");for(let Q of $.relatedFindings)Z.push(`- **${Q.findingId}** (${Q.type}, ${Q.category})`);Z.push("")}if($.patchContext&&$.patchContext.length>0){Z.push("## Patch Context"),Z.push("");for(let Q of $.patchContext){Z.push(`### ${Q.file} (${Q.status})`),Z.push("");for(let X of Q.hunks)Z.push("```diff"),Z.push(`@@ -${X.oldStart},${X.oldLines} +${X.newStart},${X.newLines} @@`),Z.push(X.content),Z.push("```"),Z.push("")}}return Z.join(`
|
|
52
|
-
`)}function nQ($){if($.itemType==="finding")return iQ($);else return tQ($)}function iQ($){let Z=[];if(Z.push(`Finding: ${$.findingId}`),Z.push("=".repeat(60)),Z.push(""),Z.push(`Type: ${$.finding.type}`),Z.push(`Category: ${$.finding.category}`),Z.push(`Confidence: ${$.finding.confidence}`),Z.push(`Range: ${$.range.base}..${$.range.head}`),Z.push(""),$.evidence.length>0){Z.push("Evidence:"),Z.push("-".repeat(60));for(let Q of $.evidence){if(Z.push(`File: ${Q.file}`),Q.line!==void 0)Z.push(` Line: ${Q.line}`);if(Q.hunk)Z.push(` Hunk: @@ -${Q.hunk.oldStart},${Q.hunk.oldLines} +${Q.hunk.newStart},${Q.hunk.newLines} @@`);Z.push(""),Z.push(Q.excerpt),Z.push("")}}if($.patchContext&&$.patchContext.length>0){Z.push("Patch Context:"),Z.push("-".repeat(60));for(let Q of $.patchContext){Z.push(`File: ${Q.file} (${Q.status})`),Z.push("");for(let X of Q.hunks)Z.push(`@@ -${X.oldStart},${X.oldLines} +${X.newStart},${X.newLines} @@`),Z.push(X.content),Z.push("")}}return Z.join(`
|
|
53
|
-
`)}function
|
|
54
|
-
`))
|
|
55
|
-
`)}
|
|
43
|
+
`),U=w8(Q,q)??w8(Q,V);if(!U)continue;let J=b8(q,U),B=b8(V,U),G=new Set;for(let M of J){let _=A2(M.path,U);if(G.has(_))continue;G.add(_);let H=B.some((E)=>A2(E.path,U)===_)?"modified":"added",z=[],N=K.find((E)=>E.includes(M.path));if(N)z.push(A(Q,N));let j={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:z,routeId:_,file:Q,change:H,routeType:P8(U,M.path),methods:M.methods.length>0?M.methods:void 0};Z.push(j)}for(let M of B){let _=A2(M.path,U);if(G.has(_))continue;G.add(_);let O=[],H=W.find((N)=>N.includes(M.path));if(H)O.push(A(Q,H));let z={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:O,routeId:_,file:Q,change:"deleted",routeType:P8(U,M.path),methods:M.methods.length>0?M.methods:void 0};Z.push(z)}}return Z}}});function o3($){return r3.some((Z)=>Z.test($))}function i3($){return a3.test($)}function n3($){let Z=[];for(let{pattern:X,description:Q}of y8)if(X.test($))Z.push({description:Q});return Z}function t3($){let Z=[];for(let{pattern:X,description:Q}of s3)if(X.test($))Z.push({description:Q});return Z}function v8($,Z){let X=[],Q=[],Y=!1,K=!1;for(let W of $){let q=Z.diffs.find((G)=>G.path===W);if(!q)continue;let V=S(q),U=V.join(`
|
|
44
|
+
`),J=n3(U);for(let{description:G}of J){Y=!0,X.push(`${G} detected in ${W}`);let M=V.find((_)=>y8.some((O)=>O.pattern.test(_)));if(M)Q.push({file:W,excerpt:M.trim()})}let B=t3(U);for(let{description:G}of B)if(K=!0,!Y)X.push(`${G} detected in ${W}`)}if(Y)return{risk:"high",reasons:X,evidence:Q};if(K)return{risk:"medium",reasons:X.length>0?X:["Schema changes detected"],evidence:Q};return{risk:"low",reasons:["Migration files changed"],evidence:Q}}var r3,a3,y8,s3,T2;var m8=T(()=>{r3=[/alembic\/versions\/.*\.py$/,/migrations\/versions\/.*\.py$/,/db\/versions\/.*\.py$/],a3=/\/migrations\/\d{4}_.*\.py$/,y8=[{pattern:/op\.drop_table\s*\(/i,description:"drop_table"},{pattern:/op\.drop_column\s*\(/i,description:"drop_column"},{pattern:/op\.drop_index\s*\(/i,description:"drop_index"},{pattern:/op\.drop_constraint\s*\(/i,description:"drop_constraint"},{pattern:/op\.execute\s*\(\s*["'].*DROP/i,description:"raw DROP SQL"},{pattern:/op\.execute\s*\(\s*["'].*TRUNCATE/i,description:"raw TRUNCATE SQL"},{pattern:/op\.execute\s*\(\s*["'].*DELETE\s+FROM\s+\w+\s*["']\s*\)/i,description:"raw DELETE without WHERE"},{pattern:/DeleteModel\s*\(/i,description:"Django DeleteModel"},{pattern:/RemoveField\s*\(/i,description:"Django RemoveField"},{pattern:/AlterField.*null\s*=\s*False/i,description:"Django make field non-nullable"},{pattern:/migrations\.RunSQL\s*\(.*DROP/i,description:"Django raw DROP SQL"},{pattern:/migrations\.RunSQL\s*\(.*TRUNCATE/i,description:"Django raw TRUNCATE SQL"}],s3=[{pattern:/op\.alter_column\s*\(/i,description:"alter_column"},{pattern:/op\.create_table\s*\(/i,description:"create_table"},{pattern:/op\.add_column\s*\(/i,description:"add_column"},{pattern:/op\.create_index\s*\(/i,description:"create_index"},{pattern:/op\.create_foreign_key\s*\(/i,description:"create_foreign_key"},{pattern:/op\.create_unique_constraint\s*\(/i,description:"create_unique_constraint"},{pattern:/CreateModel\s*\(/i,description:"Django CreateModel"},{pattern:/AddField\s*\(/i,description:"Django AddField"},{pattern:/AlterField\s*\(/i,description:"Django AlterField"},{pattern:/RenameField\s*\(/i,description:"Django RenameField"},{pattern:/RenameModel\s*\(/i,description:"Django RenameModel"},{pattern:/AddIndex\s*\(/i,description:"Django AddIndex"},{pattern:/AddConstraint\s*\(/i,description:"Django AddConstraint"}];T2={name:"python-migrations",analyze($){let Z=[],X=[],Q=[];for(let Y of $.files)if(o3(Y.path))X.push(Y.path);else if(i3(Y.path))Q.push(Y.path);if(X.length>0){let{risk:Y,reasons:K,evidence:W}=v8(X,$),q=W.map((U)=>A(U.file,U.excerpt)),V={type:"python-migration",kind:"python-migration",category:"database",confidence:"high",evidence:q,tool:"alembic",files:X,risk:Y,reasons:K};if(Z.push(V),Y==="high"){let U={type:"risk-flag",kind:"risk-flag",category:"database",confidence:"high",evidence:q,risk:"high",evidenceText:`Destructive migration detected: ${K.join(", ")}`};Z.push(U)}}if(Q.length>0){let{risk:Y,reasons:K,evidence:W}=v8(Q,$),q=W.map((U)=>A(U.file,U.excerpt)),V={type:"python-migration",kind:"python-migration",category:"database",confidence:"high",evidence:q,tool:"django",files:Q,risk:Y,reasons:K};if(Z.push(V),Y==="high"){let U={type:"risk-flag",kind:"risk-flag",category:"database",confidence:"high",evidence:q,risk:"high",evidenceText:`Destructive migration detected: ${K.join(", ")}`};Z.push(U)}}return Z}}});function X7($){let Z=$.split("/").pop()??"";for(let{pattern:X,configType:Q,category:Y}of e3)if(X.test(Z))return{configType:Q,category:Y};return null}function Q7($){let Z=[];for(let{pattern:X,description:Q}of $7)if(X.test($))Z.push(Q);for(let X of Z7)if($.includes(X)){let Q=`${X} section modified`;if(!Z.some((Y)=>Y.includes(X)))Z.push(Q)}return Z}function Y7($){let Z=[],X=/^\s*\[([^\]]+)\]/gm,Q;while((Q=X.exec($))!==null){let Y=Q[1].trim();if(!Z.includes(Y))Z.push(Y)}return Z}var e3,$7,Z7,x2;var h8=T(()=>{e3=[{pattern:/^pyproject\.toml$/,configType:"pyproject",category:"build"},{pattern:/^setup\.cfg$/,configType:"setup",category:"build"},{pattern:/^setup\.py$/,configType:"setup",category:"build"},{pattern:/^MANIFEST\.in$/,configType:"manifest",category:"build"},{pattern:/^tox\.ini$/,configType:"tox",category:"testing"},{pattern:/^pytest\.ini$/,configType:"pytest",category:"testing"},{pattern:/^conftest\.py$/,configType:"pytest",category:"testing"},{pattern:/^\.coveragerc$/,configType:"coverage",category:"testing"},{pattern:/^\.noxfile\.py$/,configType:"nox",category:"testing"},{pattern:/^\.?mypy\.ini$/,configType:"mypy",category:"typing"},{pattern:/^pyrightconfig\.json$/,configType:"pyright",category:"typing"},{pattern:/^\.flake8$/,configType:"flake8",category:"linting"},{pattern:/^\.pylintrc$/,configType:"pylint",category:"linting"},{pattern:/^\.ruff\.toml$/,configType:"ruff",category:"linting"},{pattern:/^ruff\.toml$/,configType:"ruff",category:"linting"},{pattern:/^\.isort\.cfg$/,configType:"isort",category:"linting"},{pattern:/^\.bandit$/,configType:"bandit",category:"security"},{pattern:/^\.?black$/,configType:"black",category:"formatting"},{pattern:/^\.editorconfig$/,configType:"editorconfig",category:"formatting"},{pattern:/^\.pre-commit-config\.yaml$/,configType:"pre-commit",category:"hooks"},{pattern:/^\.python-version$/,configType:"python-version",category:"environment"},{pattern:/^runtime\.txt$/,configType:"runtime",category:"environment"}],$7=[{pattern:/python\s*=\s*["'][<>=!~]+\s*3\./i,description:"Python version constraint changed"},{pattern:/requires-python\s*=\s*["'][<>=!~]+/i,description:"requires-python changed"},{pattern:/\[tool\.poetry\.dependencies\]/i,description:"Poetry dependencies section changed"},{pattern:/\[project\.dependencies\]/i,description:"Project dependencies section changed"},{pattern:/\[build-system\]/i,description:"Build system configuration changed"},{pattern:/\[project\.scripts\]/i,description:"CLI scripts changed"},{pattern:/\[project\.entry-points\]/i,description:"Entry points changed"}],Z7=["[project]","[tool.poetry]","[build-system]","[project.scripts]","[project.entry-points]","[project.optional-dependencies]"];x2={name:"python-config",analyze($){let Z=[];for(let X of $.files){let Q=X7(X.path);if(!Q)continue;let Y=$.diffs.find((G)=>G.path===X.path),K=Y?S(Y):[],W=K.join(`
|
|
45
|
+
`),q=[];if(K.length>0){let G=F(K);if(G)q.push(A(X.path,G))}let V=!1,U=[];if(Q.configType==="pyproject")U=Q7(W),V=U.length>0;let J=Y7(W),B={type:"python-config",kind:"python-config",category:"config_env",confidence:"high",evidence:q,file:X.path,status:X.status,configType:Q.configType,configCategory:Q.category,isBreaking:V,affectedSections:J,breakingReasons:U};Z.push(B)}return Z}}});import{parse as K7}from"@babel/parser";import u8 from"@babel/traverse";import*as g from"@babel/types";function W7($){if(![".ts",".js"].some((Y)=>$.endsWith(Y)))return!1;let X=$.includes("-routing.module")||$.includes(".routing.module")||$.includes("app.routes")||$.includes(".routes.ts"),Q=$.includes(".module.")||$.includes(".component.");return X||Q}function E2($){let Z=$.replace(/\/+/g,"/");if(Z!=="/"&&Z.endsWith("/"))Z=Z.slice(0,-1);return Z}function U7($,Z){if(Z.startsWith("/"))return E2(Z);if(Z==="")return E2($);let X=$==="/"?`/${Z}`:`${$}/${Z}`;return E2(X)}function V7($){let Z={};for(let X of $.properties)if(g.isObjectProperty(X)&&g.isIdentifier(X.key)){if(X.key.name==="path"&&g.isStringLiteral(X.value))Z.path=X.value.value;else if(X.key.name==="redirectTo"&&g.isStringLiteral(X.value))Z.redirectTo=X.value.value;else if(X.key.name==="loadChildren")Z.loadChildren=!0;else if(X.key.name==="children"&&g.isArrayExpression(X.value))Z.children=X.value}return Z}function w2($,Z,X="/"){let Q=[];for(let Y of $.elements)if(g.isObjectExpression(Y)){let K=V7(Y);if(K.path!==void 0){let W=U7(X,K.path);if(Q.push({path:W,file:Z,loadChildren:K.loadChildren,redirectTo:K.redirectTo}),K.children){let q=w2(K.children,Z,W);Q.push(...q)}}}return Q}function J7($){if(!$)return!1;let Z=$.typeAnnotation||$;if(g.isTSTypeReference(Z)&&g.isIdentifier(Z.typeName))return Z.typeName.name==="Routes";if(g.isTSArrayType(Z)){let X=Z.elementType;if(g.isTSTypeReference(X)&&g.isIdentifier(X.typeName))return X.typeName.name==="Route"}return!1}function B7($,Z){let X=[],Q=new Map,Y=new Set;if(u8($,{VariableDeclarator(K){if(g.isIdentifier(K.node.id)&&g.isArrayExpression(K.node.init)){let W=J7(K.node.id.typeAnnotation),q=/routes/i.test(K.node.id.name);if(W||q)Q.set(K.node.id.name,K.node.init)}}}),u8($,{CallExpression(K){let W=null,q=null;if(g.isMemberExpression(K.node.callee)){let V=K.node.callee.object,U=K.node.callee.property;if(g.isIdentifier(V)&&V.name==="RouterModule"&&g.isIdentifier(U)&&(U.name==="forRoot"||U.name==="forChild")){let J=K.node.arguments[0];if(g.isArrayExpression(J))W=J;else if(g.isIdentifier(J)){q=J.name;let B=Q.get(J.name);if(B)W=B}}}else if(g.isIdentifier(K.node.callee)){if(K.node.callee.name==="provideRouter"){let V=K.node.arguments[0];if(g.isArrayExpression(V))W=V;else if(g.isIdentifier(V)){q=V.name;let U=Q.get(V.name);if(U)W=U}}}if(W){let V=w2(W,Z);if(X.push(...V),q)Y.add(q)}}}),X.length===0){for(let[K,W]of Q)if(!Y.has(K)){let q=w2(W,Z);X.push(...q)}}return X}function g8($,Z){try{let X=K7($,{sourceType:"module",plugins:["typescript","decorators-legacy"]});return B7(X,Z)}catch(X){return[]}}var q7,I2;var b2=T(()=>{U0();q7={batchGetFileContent:z$};I2={name:"angular-routes",async analyze($){let Z=[],X=$.files.filter((W)=>{return W7(W.path)});if(X.length===0)return[];let Q=[];for(let W of X)Q.push({ref:$.base,path:W.path}),Q.push({ref:$.head,path:W.path});let Y=await q7.batchGetFileContent(Q);for(let W of X){let q=`${$.base}:${W.path}`,V=`${$.head}:${W.path}`,U=Y.get(q),J=Y.get(V),B=(H)=>H.includes("RouterModule")||H.includes("provideRouter")||H.includes("Routes")||H.includes("@angular/router");if(U&&!B(U)&&J&&!B(J))continue;let G=U?g8(U,W.path):[],M=J?g8(J,W.path):[],_=new Set(G.map((H)=>H.path)),O=new Set(M.map((H)=>H.path));for(let H of M)if(!_.has(H.path)){let z=H.loadChildren?"lazy":H.redirectTo?"redirect":"page",N=H.redirectTo?`Route: ${H.path} → ${H.redirectTo}`:`Route: ${H.path}`,j={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:[A(W.path,N)],routeId:H.path,file:W.path,change:"added",routeType:z};Z.push(j)}for(let H of G)if(!O.has(H.path)){let z=H.loadChildren?"lazy":H.redirectTo?"redirect":"page",N=H.redirectTo?`Route: ${H.path} → ${H.redirectTo}`:`Route: ${H.path}`,j={type:"route-change",kind:"route-change",category:"routes",confidence:"high",evidence:[A(W.path,N)],routeId:H.path,file:W.path,change:"deleted",routeType:z};Z.push(j)}}return Array.from(new Map(Z.map((W)=>{return[`${W.routeId}-${W.change}-${W.file}`,W]})).values()).sort((W,q)=>{let V=W.routeId,U=q.routeId;return V.localeCompare(U)})}}});import{parse as G7}from"@babel/parser";import O7 from"@babel/traverse";import*as _1 from"@babel/types";function M7($){if(![".ts",".js"].some((Q)=>$.endsWith(Q)))return!1;return[".component.",".module.",".service.",".directive.",".pipe.",".guard.",".interceptor."].some((Q)=>$.includes(Q))}function _7($){if($.includes(".component."))return"component";if($.includes(".module."))return"module";if($.includes(".service."))return"service";if($.includes(".directive."))return"directive";if($.includes(".pipe."))return"pipe";if($.includes(".guard."))return"guard";if($.includes(".interceptor."))return"interceptor";return"unknown"}function H7($){let Z=$.match(/@(Component|NgModule|Injectable|Directive|Pipe)\s*\(\s*\{/);if(!Z)return null;let X={name:Z[1]},Q=$.match(/selector\s*:\s*['"]([^'"]+)['"]/);if(Q)X.selector=Q[1];let Y=$.match(/standalone\s*:\s*(true|false)/);if(Y)X.standalone=Y[1]==="true";return X}function z7($){try{let Z=G7($,{sourceType:"module",plugins:["typescript","decorators-legacy"]}),X=null;if(O7(Z,{ClassDeclaration(Q){let Y=Q.node.decorators||[];for(let K of Y){let W=K.expression;if(_1.isCallExpression(W)&&_1.isIdentifier(W.callee)){let q=W.callee.name;if(["Component","NgModule","Injectable","Directive","Pipe"].includes(q)){let V={name:q},U=W.arguments[0];if(_1.isObjectExpression(U)){for(let J of U.properties)if(_1.isObjectProperty(J)&&_1.isIdentifier(J.key)){if(J.key.name==="selector"&&_1.isStringLiteral(J.value))V.selector=J.value.value;else if(J.key.name==="standalone"&&_1.isBooleanLiteral(J.value))V.standalone=J.value.value;else if(J.key.name==="providers"&&_1.isArrayExpression(J.value))V.providers=J.value.elements.map((B)=>{if(_1.isIdentifier(B))return B.name;return null}).filter((B)=>B!==null)}}X=V;break}}}}}),X)return X}catch(Z){}return H7($)}var P2;var C2=T(()=>{P2={name:"angular-components",analyze($){let Z=[];for(let X of $.files){if(!M7(X.path))continue;let Q=_7(X.path),Y=$.diffs.find((B)=>B.path===X.path),K=Y?S(Y):[],W=F(K),q=[];if(W)q.push(A(X.path,W));let V=K.join(`
|
|
46
|
+
`),U=z7(V),J={type:"angular-component-change",kind:"angular-component-change",category:"api",confidence:"high",evidence:q,file:X.path,change:X.status==="added"?"added":X.status==="deleted"?"deleted":"modified",componentType:Q,selector:U?.selector,standalone:U?.standalone,providers:U?.providers};Z.push(J)}return Z}}});function A7($){return L7.some((Z)=>Z.test($))}function R7($){let Z=new Set,X=$.join(`
|
|
47
|
+
`);for(let Q of j7)if(new RegExp(`\\b${Q}\\s*[:{]`,"i").test(X))Z.add(Q);for(let Q of D7)if(new RegExp(`\\b${Q}\\s*[:{]`,"i").test(X))Z.add(`build.${Q}`);for(let Q of N7)if(new RegExp(`\\b${Q}\\s*[:{]`,"i").test(X))Z.add(`server.${Q}`);return Array.from(Z)}function T7($,Z){let X=[],Q=$.join(`
|
|
48
|
+
`),Y=Z.join(`
|
|
49
|
+
`);if(/\bbase\s*[:{]/.test(Y)||/\bbase\s*[:{]/.test(Q)){if(Z.length>0&&$.length>0)X.push("Base path changed (affects all asset URLs)")}if(/\boutDir\s*[:{]/.test(Y)||/\boutDir\s*[:{]/.test(Q))X.push("Output directory changed (may affect deployment)");if(/\btarget\s*[:{]/.test(Y)||/\btarget\s*[:{]/.test(Q))X.push("Build target changed (affects browser compatibility)");if(/plugins\s*[:{]/.test(Y)&&Z.some((K)=>K.includes("import(")||K.includes("require(")))X.push("Plugins modified (may affect build behavior)");if(/resolve\s*[:{]/.test(Y)&&/alias\s*[:{]/.test(Y))X.push("Path aliases modified (may break imports)");if(/\benvPrefix\s*[:{]/.test(Y)||/\benvPrefix\s*[:{]/.test(Q))X.push("Environment prefix changed (affects env variable exposure)");if(/\bdefine\s*[:{]/.test(Y))X.push("Build-time constants modified");if(/\bsourcemap\s*[:{]/.test(Q)||/\bsourcemap\s*[:{]/.test(Y))X.push("Sourcemap configuration changed");if(/\bssr\s*[:{]/.test(Y)||/\bssr\s*[:{]/.test(Q))X.push("SSR configuration changed (affects server rendering)");return{isBreaking:X.length>0,reasons:X}}function x7($,Z){let X=[],Q=[...$,...Z].join(`
|
|
50
|
+
`),Y=[{pattern:/@vitejs\/plugin-react/,name:"React"},{pattern:/@vitejs\/plugin-vue/,name:"Vue"},{pattern:/@vitejs\/plugin-vue-jsx/,name:"Vue JSX"},{pattern:/@vitejs\/plugin-legacy/,name:"Legacy Browser Support"},{pattern:/@sveltejs\/vite-plugin-svelte/,name:"Svelte"},{pattern:/vite-plugin-pwa/,name:"PWA"},{pattern:/vite-tsconfig-paths/,name:"TypeScript Paths"},{pattern:/vitest/,name:"Vitest"},{pattern:/@angular\/build/,name:"Angular"},{pattern:/vite-plugin-solid/,name:"Solid"},{pattern:/vite-plugin-qwik/,name:"Qwik"}];for(let{pattern:K,name:W}of Y)if(K.test(Q))X.push(W);return X}var L7,j7,D7,N7,S2;var f8=T(()=>{L7=[/^vite\.config\.(js|cjs|mjs|ts|mts)$/],j7=["build","server","preview","resolve","plugins","define","base","publicDir","envPrefix","optimizeDeps","esbuild","ssr"],D7=["target","outDir","assetsDir","assetsInlineLimit","cssCodeSplit","sourcemap","minify","rollupOptions","lib","manifest","cssMinify","modulePreload","chunkSizeWarningLimit"],N7=["host","port","proxy","cors","https","hmr","watch","middlewareMode"];S2={name:"vite-config",analyze($){let Z=[];for(let X of $.diffs){if(!A7(X.path))continue;let Q=S(X),Y=z1(X),K=R7([...Q,...Y]),{isBreaking:W,reasons:q}=T7(Q,Y),V=x7(Q,Y),U=W?"high":K.length>0?"medium":"low",J=F(Q.length>0?Q:Y),B={type:"vite-config",kind:"vite-config",category:"config_env",confidence:U,evidence:[A(X.path,J)],file:X.path,status:X.status,isBreaking:W,affectedSections:K,breakingReasons:q,pluginsDetected:V};Z.push(B)}return Z}}});var E1=T(()=>{r5();B8();J2();B2();f1();l1();O2();_2();z2();D2();E8();F8();m8();h8();b2();C2();f8();b5();Y0();q0();m5();h5();u5();$2();f5();Q2();J0();e5();$8();X8();Q8();Y8();K8();q8();W8()});var k2;var l8=T(()=>{E1();k2={name:"auto",analyzers:[r,a,$1,J1,Z1,X1,Q1,s,v$,o,i,n,Y1,t,K1,e]}});var c8;var p8=T(()=>{E1();l1();c8={name:"sveltekit",analyzers:[r,a,F5,y5,$1,J1,Z1,X1,Q1,s,j1,o,i,n,Y1,t,K1,e]}});var d8;var r8=T(()=>{E1();l1();f1();d8={name:"react",analyzers:[r,a,K2,$1,J1,Z1,X1,Q1,s,j1,L1,o,i,n,Y1,t,K1,e]}});var a8;var s8=T(()=>{E1();f1();a8={name:"stencil",analyzers:[r,a,U2,$1,J1,Z1,X1,Q1,s,L1,o,i,n,Y1,t,K1,e]}});var o8;var i8=T(()=>{E1();J2();l1();o8={name:"next",analyzers:[r,a,V2,$1,J1,Z1,X1,Q1,s,j1,o,i,n,Y1,t,K1,e]}});var n8;var t8=T(()=>{E1();z2();l1();f1();n8={name:"vue",analyzers:[r,a,H2,$1,J1,Z1,X1,Q1,s,j1,L1,o,i,n,Y1,t,K1,e]}});var e8;var $9=T(()=>{E1();D2();l1();f1();e8={name:"astro",analyzers:[r,a,j2,$1,J1,Z1,X1,Q1,s,j1,L1,o,i,n,Y1,t,K1,e]}});var Z9;var X9=T(()=>{E1();b2();C2();l1();f1();B2();Z9={name:"angular",analyzers:[r,a,I2,P2,$1,J1,Z1,X1,Q1,s,j1,L1,v$,o,i,n,Y1,t,K1,e]}});var Q9;var Y9=T(()=>{E1();_2();f1();O2();Q9={name:"library",analyzers:[r,a,M2,L1,X1,Z1,s,G2,o,i,n,t,e]}});var K9;var q9=T(()=>{E1();K9={name:"python",analyzers:[r,a,N2,R2,T2,x2,$1,Q1,s,o,i,n,Y1,t,K1,e]}});var W9;var U9=T(()=>{E1();l1();f1();W9={name:"vite",analyzers:[r,a,$1,J1,Z1,X1,Q1,s,S2,j1,L1,o,i,n,Y1,t,K1,e]}});import{existsSync as G1}from"node:fs";import{join as O1}from"node:path";function E7($=process.cwd()){if(G1(O1($,"src","routes")))return!0;return!1}function w7($){if(!$)return!1;let{dependencies:Z,devDependencies:X}=$;return Boolean(Z?.["@sveltejs/kit"]||X?.["@sveltejs/kit"])}function I7($){if(!$)return!1;let{dependencies:Z,devDependencies:X}=$;return Boolean(Z?.react&&Z?.["react-dom"]||X?.react&&X?.["react-dom"])}function b7($){if(!$)return!1;let{dependencies:Z,devDependencies:X}=$;return Boolean(Z?.["react-router"]||Z?.["react-router-dom"]||X?.["react-router"]||X?.["react-router-dom"])}function P7($){if(!$)return!1;let{dependencies:Z,devDependencies:X}=$;return Boolean(Z?.next||X?.next)}function C7($){if(!$)return!1;let{dependencies:Z,devDependencies:X}=$;return Boolean(Z?.["@stencil/core"]||X?.["@stencil/core"])}function S7($=process.cwd()){return G1(O1($,"stencil.config.ts"))||G1(O1($,"stencil.config.js"))}function k7($=process.cwd()){if(G1(O1($,"app")))return!0;if(G1(O1($,"src","app")))return!0;return!1}function F7($){if(!$)return!1;let{dependencies:Z,devDependencies:X}=$;return Boolean(Z?.vue||X?.vue)}function v7($){if(!$)return!1;let{dependencies:Z,devDependencies:X}=$;return Boolean(Z?.nuxt||X?.nuxt)}function y7($=process.cwd()){return G1(O1($,"pages"))||G1(O1($,"src","pages"))}function m7($){if(!$)return!1;let{dependencies:Z,devDependencies:X}=$;return Boolean(Z?.astro||X?.astro)}function h7($){if(!$)return!1;let{dependencies:Z,devDependencies:X}=$;return Boolean(Z?.["@angular/core"]||Z?.["@angular/common"]||X?.["@angular/core"]||X?.["@angular/common"])}function u7($=process.cwd()){return G1(O1($,"angular.json"))||G1(O1($,".angular-cli.json"))}function g7($=process.cwd()){return G1(O1($,"astro.config.mjs"))||G1(O1($,"astro.config.ts"))||G1(O1($,"astro.config.js"))}function f7($){if(!$)return!1;if($.exports)return!0;if($.publishConfig)return!0;if($.private===!1)return!0;if($.bin)return!0;return!1}function l7($=process.cwd()){return["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","poetry.lock"].some((X)=>G1(O1($,X)))}function c7($){if(!$)return!1;let{dependencies:Z,devDependencies:X}=$;return Boolean(Z?.vite||X?.vite)}function p7($=process.cwd()){return G1(O1($,"vite.config.ts"))||G1(O1($,"vite.config.js"))||G1(O1($,"vite.config.mjs"))||G1(O1($,"vite.config.mts"))}function d7($=process.cwd()){return["manage.py","app/main.py","src/main.py","app/__init__.py"].some((X)=>G1(O1($,X)))}function r7($){for(let Z of $.files){if(Z.path.includes("/migrations/")&&Z.path.endsWith(".py"))return"django";if(Z.path==="manage.py"||Z.path.includes("urls.py"))return"django";if(Z.path.includes("routers/")||Z.path.includes("endpoints/"))return"fastapi";if(Z.path.includes("alembic/versions/"))return"alembic"}return null}function y$($,Z=process.cwd()){let X=[],Q=E7(Z),Y=w7($.headPackageJson);if(Q||Y){if(Q)X.push("Found src/routes/ directory (SvelteKit file-based routing)");if(Y)X.push("Found @sveltejs/kit in package.json dependencies");return{profile:"sveltekit",confidence:Q&&Y?"high":"high",reasons:X}}let K=C7($.headPackageJson),W=S7(Z);if(K||W){if(K)X.push("Found @stencil/core in package.json dependencies");if(W)X.push("Found stencil.config.ts or stencil.config.js");return{profile:"stencil",confidence:K&&W?"high":"high",reasons:X}}let q=P7($.headPackageJson),V=k7(Z);if(q&&V)return X.push("Found next in package.json dependencies"),X.push("Found app/ directory (Next.js App Router)"),{profile:"next",confidence:"high",reasons:X};if(q)return X.push("Found next in package.json dependencies"),{profile:"next",confidence:"medium",reasons:X};let U=I7($.headPackageJson),J=b7($.headPackageJson);if(U&&J)return X.push("Found react and react-dom in package.json dependencies"),X.push("Found react-router or react-router-dom in package.json dependencies"),{profile:"react",confidence:"high",reasons:X};let B=F7($.headPackageJson),G=v7($.headPackageJson),M=y7(Z);if(G||B&&M){if(G)X.push("Found nuxt in package.json dependencies");if(B)X.push("Found vue in package.json dependencies");if(M)X.push("Found pages/ directory (Nuxt file-based routing)");return{profile:"vue",confidence:"high",reasons:X}}if(B)return X.push("Found vue in package.json dependencies"),{profile:"vue",confidence:"medium",reasons:X};let _=m7($.headPackageJson),O=g7(Z);if(_||O){if(_)X.push("Found astro in package.json dependencies");if(O)X.push("Found astro.config.{mjs,ts,js}");return{profile:"astro",confidence:_&&O?"high":"medium",reasons:X}}let H=h7($.headPackageJson),z=u7(Z);if(H||z){if(H)X.push("Found @angular/core or @angular/common in package.json dependencies");if(z)X.push("Found angular.json or .angular-cli.json");return{profile:"angular",confidence:H&&z?"high":"medium",reasons:X}}let N=c7($.headPackageJson),j=p7(Z);if(N&&j)return X.push("Found vite in package.json dependencies"),X.push("Found vite.config.{ts,js,mjs,mts}"),{profile:"vite",confidence:"high",reasons:X};if(N)return X.push("Found vite in package.json dependencies"),{profile:"vite",confidence:"medium",reasons:X};if(f7($.headPackageJson)){if($.headPackageJson?.exports)X.push("Found exports field in package.json");if($.headPackageJson?.publishConfig)X.push("Found publishConfig in package.json");if($.headPackageJson?.bin)X.push("Found bin field in package.json (CLI tool)");if($.headPackageJson?.private===!1)X.push("Package marked as public (private: false)");return{profile:"library",confidence:"medium",reasons:X}}let x=l7(Z),R=d7(Z),b=r7($);if(x||R||b){if(x)X.push("Found Python project files (pyproject.toml, requirements.txt, etc.)");if(R)X.push("Found Python web framework markers (manage.py, main.py, etc.)");if(b)X.push(`Detected ${b} framework from changed files`);return{profile:"python",confidence:x&&(R||b)?"high":"medium",reasons:X}}return X.push("No framework-specific markers detected, using default analyzers"),{profile:"auto",confidence:"medium",reasons:X}}function a7($,Z=process.cwd()){return y$($,Z).profile}function h1($){switch($){case"sveltekit":return c8;case"react":return d8;case"stencil":return a8;case"next":return o8;case"vue":return n8;case"astro":return e8;case"angular":return Z9;case"library":return Q9;case"python":return K9;case"vite":return W9;case"auto":return k2;default:return k2}}function Y$($,Z,X=process.cwd()){if($==="auto")return a7(Z,X);return $}var m$=T(()=>{l8();p8();r8();s8();i8();t8();$9();X9();Y9();q9();U9()});function j$($){let Z=[],X=0,Q=(D,C)=>{Z.push({text:D,priority:C,order:X++})},Y=$.filter((D)=>D.type==="impact-analysis"),K=Y.filter((D)=>D.blastRadius==="high"),W=Y.filter((D)=>D.blastRadius==="medium");if(K.length>0)Q(`${K.length} file(s) with high blast radius`,m.HIGH_BLAST_RADIUS);if(W.length>0)Q(`${W.length} file(s) with medium blast radius`,m.MEDIUM_BLAST_RADIUS);let q=$.filter((D)=>D.type==="typescript-config");if(q.length>0){let D=q.some((C)=>C.isBreaking);Q(D?"TypeScript config changed (breaking)":"TypeScript config modified",D?m.BREAKING_CONFIG:m.NON_BREAKING_CONFIG)}let V=$.filter((D)=>D.type==="tailwind-config");if(V.length>0){let D=V.some((C)=>C.isBreaking);Q(D?"Tailwind config changed (breaking)":"Tailwind config modified",D?m.BREAKING_CONFIG:m.NON_BREAKING_CONFIG)}let U=$.filter((D)=>D.type==="graphql-change");if(U.length>0){let D=U.some((C)=>C.isBreaking);Q(D?"GraphQL schema changed (breaking)":"GraphQL schema modified",D?m.BREAKING_CONFIG:m.NON_BREAKING_CONFIG)}let J=$.filter((D)=>D.type==="package-exports");if(J.length>0){if(J.some((C)=>C.isBreaking))Q("Package exports changed (breaking)",m.BREAKING_CONFIG);else if(J.filter((H1)=>H1.binChanges&&(H1.binChanges.added.length>0||H1.binChanges.removed.length>0)).length>0)Q("Package bin/exports modified",m.NON_BREAKING_CONFIG)}let G=$.filter((D)=>D.type==="risk-flag").filter((D)=>D.risk==="high");if(G.length>0)Q(`${G.length} high-risk condition(s) detected`,m.HIGH_RISK_FLAGS);let _=$.filter((D)=>D.type==="sql-risk").filter((D)=>D.riskType==="destructive");if(_.length>0)Q(`Destructive SQL detected in ${_.length} file(s)`,m.DESTRUCTIVE_SQL);let O=$.filter((D)=>D.type==="db-migration");if(O.length>0){let D=O.some((C)=>C.risk==="high");Q(D?"Database migrations (HIGH RISK)":"Database migrations",D?m.HIGH_RISK_DB_MIGRATION:m.DB_MIGRATION)}let H=$.filter((D)=>D.type==="ci-workflow");if(H.length>0)if(H.filter((C)=>C.riskType==="permissions_broadened"||C.riskType==="pull_request_target").length>0)Q("CI workflow security changes detected",m.CI_SECURITY);else Q(`${H.length} CI workflow(s) modified`,m.CI_WORKFLOW);if($.filter((D)=>D.type==="security-file").length>0)Q("Security-sensitive files changed",m.SECURITY_FILES);let N=$.find((D)=>D.type==="lockfile-mismatch");if(N){if(N.manifestChanged&&!N.lockfileChanged)Q("Lockfile mismatch: package.json changed but lockfile not updated",m.LOCKFILE_MISMATCH);else if(!N.manifestChanged&&N.lockfileChanged)Q("Lockfile mismatch: lockfile changed but package.json not updated",m.LOCKFILE_MISMATCH)}let j=$.filter((D)=>D.type==="infra-change");if(j.length>0){let D=[...new Set(j.map((C)=>C.infraType))];Q(`Infrastructure changes: ${D.join(", ")}`,m.INFRA_CHANGES)}let E=$.filter((D)=>D.type==="dependency-change"),x=E.filter((D)=>D.impact==="major");if(x.length>0)Q(`${x.length} major dependency update(s)`,m.MAJOR_DEPS);let R=$.filter((D)=>D.type==="route-change");if(R.length>0)Q(`${R.length} route(s) changed`,m.ROUTE_CHANGES);let b=$.filter((D)=>D.type==="api-contract-change");if(b.length>0)Q(`${b.length} API contract(s) modified`,m.API_CONTRACTS);let w=$.filter((D)=>D.type==="cloudflare-change");if(w.length>0){let D=[...new Set(w.map((C)=>C.area))];Q(`Cloudflare ${D.join("/")} configuration changed`,m.CLOUDFLARE)}let p=$.filter((D)=>D.type==="stencil-component-change"||D.type==="stencil-prop-change"||D.type==="stencil-event-change"||D.type==="stencil-method-change"||D.type==="stencil-slot-change");if(p.length>0){let D=new Set(p.map((C)=>C.tag));Q(`${D.size} Stencil component(s) with API changes`,m.STENCIL_API)}let P=$.filter((D)=>D.type==="monorepo-config");if(P.length>0){let D=[...new Set(P.map((C)=>C.tool))];Q(`Monorepo config changed: ${D.join(", ")}`,m.MONOREPO_CONFIG)}let N1=$.filter((D)=>D.type==="env-var");if(N1.length>0){let D=N1.filter((C)=>C.change==="added");Q(D.length>0?`${D.length} new environment variable(s)`:`${N1.length} environment variable(s) touched`,m.ENV_VARS)}let U1=E.filter((D)=>D.impact==="new");if(U1.length>0)Q(`${U1.length} new dependency(ies) added`,m.NEW_DEPS);let A1=$.filter((D)=>D.type==="test-change");if(A1.length>0){let D=A1.reduce(($$,Z$)=>$$+Z$.added.length,0),C=A1.reduce(($$,Z$)=>$$+Z$.modified.length,0),H1=A1.reduce(($$,Z$)=>$$+Z$.deleted.length,0),g1=[];if(D>0)g1.push(`${D} added`);if(C>0)g1.push(`${C} modified`);if(H1>0)g1.push(`${H1} deleted`);if(g1.length>0)Q(`Test files: ${g1.join(", ")}`,m.TEST_CHANGES);else{let $$=A1.flatMap((Z$)=>Z$.files).length;Q(`${$$} test file(s) changed`,m.TEST_CHANGES)}}let a1=$.filter((D)=>D.type==="convention-violation");if(a1.length>0){let D=a1.reduce((C,H1)=>C+H1.files.length,0);Q(`${D} source file(s) missing corresponding tests`,m.CONVENTION_VIOLATIONS)}let V1=$.filter((D)=>D.type==="test-gap");if(V1.length>0){let D=V1.reduce((C,H1)=>C+H1.prodFilesChanged,0);Q(`${D} modified file(s) lack test coverage`,m.TEST_GAPS)}if(Z.length===0&&$.length>0){let D=$.find((C)=>C.type==="file-summary");if(D){let C=D.added.length+D.modified.length+D.deleted.length+D.renamed.length;if(C>0)Q(`${C} ${D.category} file(s) changed`,m.FALLBACK)}if(Z.length===0&&Y.length>0){let C=Y.reduce((H1,g1)=>H1+g1.affectedFiles.length,0);Q(`${Y.length} file(s) analyzed, ${C} dependent file(s)`,m.FALLBACK)}if(Z.length===0)Q(`${$.length} finding(s) detected`,m.FALLBACK)}return Z.sort((D,C)=>{if(C.priority!==D.priority)return C.priority-D.priority;return D.order-C.order}),Z.map((D)=>D.text)}var m;var G0=T(()=>{m={HIGH_BLAST_RADIUS:100,MEDIUM_BLAST_RADIUS:95,BREAKING_CONFIG:90,HIGH_RISK_FLAGS:85,DESTRUCTIVE_SQL:85,HIGH_RISK_DB_MIGRATION:85,CI_SECURITY:85,SECURITY_FILES:85,LOCKFILE_MISMATCH:80,INFRA_CHANGES:70,MAJOR_DEPS:70,ROUTE_CHANGES:70,API_CONTRACTS:70,CLOUDFLARE:70,STENCIL_API:60,MONOREPO_CONFIG:60,ENV_VARS:60,NEW_DEPS:60,NON_BREAKING_CONFIG:60,DB_MIGRATION:55,CI_WORKFLOW:55,TEST_CHANGES:50,TEST_GAPS:50,CONVENTION_VIOLATIONS:50,FALLBACK:10}});function RX($){let Z=$.find((K)=>K.type==="file-category");if(!Z)return{isLowRisk:!1,category:null};let{categories:X}=Z;if(["product","infra","ci","dependencies"].some((K)=>X[K].length>0))return{isLowRisk:!1,category:null};if(X.docs.length>0&&X.tests.length===0)return{isLowRisk:!0,category:"docs"};if(X.tests.length>0&&X.docs.length===0)return{isLowRisk:!0,category:"tests"};if(X.config.length>0&&X.docs.length===0&&X.tests.length===0)return{isLowRisk:!0,category:"config"};if(X.docs.length>0||X.tests.length>0||X.config.length>0)return{isLowRisk:!0,category:"docs/tests/config"};return{isLowRisk:!1,category:null}}function D$($){let Z=0,X=[],Q=[],{isLowRisk:Y,category:K}=RX($);if(Y&&K){let J={docs:-15,tests:-10,config:-5,"docs/tests/config":-10}[K]??0;Z+=J,X.push(`✅ Changes are only in ${K} (lower risk)`),Q.push({kind:"low-risk-category",weight:J,explanation:`Changes are only in ${K} (lower risk)`,evidence:[]})}for(let U of $)switch(U.type){case"risk-flag":{let J=U.risk==="high"?40:U.risk==="medium"?20:5;Z+=J;let B=U.risk==="high"?"⚠️":U.risk==="medium"?"⚡":"ℹ️";X.push(`${B} ${U.evidenceText}`),Q.push({kind:`risk-${U.risk}`,weight:J,explanation:U.evidenceText,evidence:U.evidence})}break;case"db-migration":{let J=U.risk==="high"?30:U.risk==="medium"?15:0;if(J>0){Z+=J;let B=U.risk==="high"?`High-risk database migration: ${U.reasons.join(", ")}`:`Database migration detected: ${U.files.join(", ")}`;X.push(U.risk==="high"?`⚠️ ${B}`:`⚡ ${B}`),Q.push({kind:"db-migration",weight:J,explanation:B,evidence:U.evidence})}}break;case"route-change":if(U.change==="added")Z+=5,Q.push({kind:"route-added",weight:5,explanation:`Route added: ${U.routeId}`,evidence:U.evidence});else if(U.change==="deleted")Z+=10,X.push(`ℹ️ Route deleted: ${U.routeId}`),Q.push({kind:"route-deleted",weight:10,explanation:`Route deleted: ${U.routeId}`,evidence:U.evidence});break;case"dependency-change":{let J=0;if(U.impact==="major")J=15;else if(U.impact==="minor")J=5;if(U.riskCategory&&U.impact==="new")J+=10;if(J>0)Z+=J,Q.push({kind:`dependency-${U.impact}`,weight:J,explanation:`${U.name}: ${U.from??"new"} → ${U.to??"removed"}`,evidence:U.evidence})}break;case"env-var":if(U.change==="added")Z+=5,X.push(`ℹ️ New env var: ${U.name}`),Q.push({kind:"env-var-added",weight:5,explanation:`New env var: ${U.name}`,evidence:U.evidence});break;case"security-file":Z+=15,Q.push({kind:"security-file",weight:15,explanation:`Security-sensitive files changed: ${U.files.length} file(s)`,evidence:U.evidence});break;case"convention-violation":{let J=U,B=J.files.length;if(B>5)Z+=10,X.push(`⚡ ${B} source files lack test coverage`),Q.push({kind:"test-coverage-gap",weight:10,explanation:`${B} source files lack test coverage`,evidence:J.evidence.slice(0,3)})}break;case"large-diff":{let J=U,B=J.linesChanged>1000?15:J.linesChanged>500?10:5;Z+=B,X.push(`ℹ️ Large diff: ${J.filesChanged} files, ${J.linesChanged} lines`),Q.push({kind:"large-diff",weight:B,explanation:`Large diff: ${J.filesChanged} files, ${J.linesChanged} lines`,evidence:J.evidence})}break}let W=[/\/types\.ts$/,/\/core\/.*\.ts$/,/\/index\.ts$/],q=$.find((U)=>U.type==="file-summary");if(q){let U=q.modified.filter((J)=>W.some((B)=>B.test(J)));if(U.length>0)Z+=10,X.push(`ℹ️ Core module files modified: ${U.join(", ")}`),Q.push({kind:"core-module-change",weight:10,explanation:`Core module files modified (types.ts, index.ts): ${U.length} file(s)`,evidence:[]})}Z=Math.max(0,Math.min(Z,100));let V;if(Z>=50)V="high";else if(Z>=20)V="medium";else V="low";return{score:Z,level:V,factors:Q,evidenceBullets:X}}function dX($){if($.includes("db-migration")||$.includes("database")||$.includes("sql"))return"database";if($.includes("dependency")||$.includes("deps"))return"dependencies";if($.includes("route"))return"routes";if($.includes("env-var")||$.includes("config"))return"config_env";if($.includes("security")||$.includes("infra")||$.includes("docker")||$.includes("k8s")||$.includes("terraform"))return"infra";if($.includes("cloudflare")||$.includes("wrangler")||$.includes("workers"))return"cloudflare";if($.includes("ci")||$.includes("workflow")||$.includes("pipeline"))return"ci";if($.includes("test")&&!$.includes("test-gap")&&!$.includes("test-coverage"))return"tests";if($.includes("test-gap")||$.includes("test-coverage")||$.includes("quality"))return"quality";if($.includes("api")||$.includes("contract"))return"api";if($.includes("core-module")||$.includes("impact")||$.includes("blast-radius")||$.includes("large-diff")||$.includes("churn"))return"impact";if($.includes("doc"))return"docs";return"unknown"}function B9($){let Z=$.excerpt.toLowerCase(),X=0;if(/\d+/.test(Z))X+=10;if(Z.includes("blast radius"))X+=15;if(Z.includes("high"))X+=5;if(Z.includes("critical"))X+=8;if(Z.includes("breaking"))X+=8;if(Z.includes("added")||Z.includes("removed")||Z.includes("modified"))X+=3;if(Z==="imports module")X-=10;if(Z.startsWith("depends on"))X-=5;return X}function O0($,Z){let X=new Map;for(let Y of $){if(Y.kind==="file-summary"||Y.kind==="file-category")continue;let K=Y.category;if(!X.has(K))X.set(K,{count:0,riskWeight:0,evidence:[]});let W=X.get(K);W.count+=1,W.evidence.push(...Y.evidence)}for(let Y of Z){let K="unknown";for(let q of $)if(q.evidence.length>0&&Y.evidence.length>0){let V=new Set(q.evidence.map((B)=>B.file)),U=new Set(Y.evidence.map((B)=>B.file));if(Array.from(V).some((B)=>U.has(B))){K=q.category;break}}if(K==="unknown")K=dX(Y.kind);if(!X.has(K))X.set(K,{count:0,riskWeight:0,evidence:[]});let W=X.get(K);W.riskWeight+=Y.weight,W.evidence.push(...Y.evidence)}let Q=Array.from(X.entries()).filter(([Y,K])=>K.count>0).map(([Y,K])=>{let W=[...K.evidence].sort((U,J)=>{let B=B9(U),G=B9(J);if(G!==B)return G-B;return U.file.localeCompare(J.file)}),q=new Set,V=[];for(let U of W){if(!q.has(U.file))q.add(U.file),V.push(U);if(V.length>=3)break}return{id:Y,count:K.count,riskWeight:K.riskWeight,topEvidence:V}});return Q.sort((Y,K)=>{if(K.riskWeight!==Y.riskWeight)return K.riskWeight-Y.riskWeight;if(K.count!==Y.count)return K.count-Y.count;return Y.id.localeCompare(K.id)}),Q}function M0($){let Z={};for(let X of $)Z[X.id]=X.count;return Z}function _0($,Z){let X=[];if(Z==="sveltekit"){let U=$.some((J)=>J.type==="route-change");if(U||$.length>0){let J=[];if(U)J.push("Route files changed");if($.length>0&&!U)J.push("Source files changed");X.push({id:"sveltekit-check",category:"types",blocking:!0,reason:"Run SvelteKit type checker to verify no type errors were introduced",triggers:J})}}let Q=$.filter((U)=>U.type==="test-change"),Y=Q.length>0;if(Y||$.length>0){let U=[];if(Y){let J=Q.reduce((B,G)=>B+G.files.length,0);U.push(`${J} test file(s) changed`)}if($.length>0&&!Y)U.push("Source files changed without corresponding test changes");X.push({id:"run-tests",category:"tests",blocking:!0,reason:"Run test suite to verify functionality and catch regressions",triggers:U})}let K=$.filter((U)=>U.type==="db-migration");if(K.length>0){let U=K.some((M)=>M.risk==="high"),J=K.flatMap((M)=>M.files),B=[...new Set(K.flatMap((M)=>M.reasons))],G=[`${J.length} migration file(s) changed`,...B];if(U)G.push("DANGEROUS SQL DETECTED (DROP, TRUNCATE, or destructive operations)");if(X.push({id:"apply-migrations",category:"database",blocking:U,reason:U?"Apply database migrations in a safe environment and verify data integrity before production":"Apply and test database migrations in development environment",triggers:G}),U)X.push({id:"backup-db",category:"database",blocking:!0,reason:"Create database backup before applying destructive migrations",triggers:["High-risk SQL operations detected in migrations"]})}let W=$.filter((U)=>U.type==="cloudflare-change");if(W.length>0){let U=[...new Set(W.map((B)=>B.area))],J=W.flatMap((B)=>B.files);X.push({id:"verify-cloudflare-config",category:"cloudflare",blocking:!1,reason:"Verify Cloudflare configuration and bindings match across environments",triggers:[`Cloudflare ${U.join(", ")} configuration changed`,`Files: ${J.join(", ")}`]})}let q=$.filter((U)=>U.type==="env-var");if(q.length>0){let U=q.map((G)=>G.name),J=q.filter((G)=>G.change==="added"),B=[];if(J.length>0)B.push(`New environment variable(s): ${J.map((G)=>G.name).join(", ")}`);if(q.length>J.length)B.push(`Modified environment variable(s): ${U.filter((G)=>!J.some((M)=>M.name===G)).join(", ")}`);X.push({id:"update-env-docs",category:"environment",blocking:!1,reason:"Update .env.example and documentation with new or changed environment variables",triggers:B})}let V=$.filter((U)=>U.type==="dependency-change"&&U.impact==="major");if(V.length>0){let U=V.map((J)=>{let B=J.from||"new",G=J.to||"removed";return`${J.name} (${B} → ${G})`});X.push({id:"review-dependencies",category:"dependencies",blocking:!1,reason:"Review major dependency changes for breaking changes and update migration guides if needed",triggers:[`Major version changes: ${U.join(", ")}`,"Check CHANGELOG and migration guides for breaking changes"]})}return X.sort((U,J)=>{if(U.blocking!==J.blocking)return U.blocking?-1:1;return U.id.localeCompare(J.id)}),X}function G9($){return $.replace(/\\/g,"/").toLowerCase()}function H0($,Z){let X=G9($),Q=G9(Z);return X.localeCompare(Q)}function O9($){return[...$].sort((Z,X)=>{let Q=Z.category.localeCompare(X.category);if(Q!==0)return Q;let Y=X.effectiveScore-Z.effectiveScore;if(Y!==0)return Y;let K=Z.ruleKey.localeCompare(X.ruleKey);if(K!==0)return K;return Z.flagId.localeCompare(X.flagId)})}function M9($){return[...$].sort((Z,X)=>{let Q=Z.type.localeCompare(X.type);if(Q!==0)return Q;let Y=(J)=>{if(J.evidence&&J.evidence.length>0)return J.evidence[0].file;return""},K=Y(Z),W=Y(X);if(K&&W){let J=H0(K,W);if(J!==0)return J}let q=(J)=>{if(J.evidence&&J.evidence.length>0){let B=J.evidence[0];if(B.line!==void 0)return B.line;if(B.hunk?.newStart!==void 0)return B.hunk.newStart}return 0},V=q(Z),U=q(X);return V-U})}function m2($){return[...$].sort((Z,X)=>{let Q=H0(Z.file,X.file);if(Q!==0)return Q;let Y=Z.line??(Z.hunk?.newStart??0),K=X.line??(X.hunk?.newStart??0);return Y-K})}function h2($){return[...$].sort((Z,X)=>{let Q=H0(Z.file,X.file);if(Q!==0)return Q;if(Z.hunk&&X.hunk){let Y=(K)=>{let W=K.match(/\+(\d+)/);return W?parseInt(W[1],10):0};return Y(Z.hunk)-Y(X.hunk)}return 0})}function FV($){return[...$].sort(H0)}function vV($){let Z=[...$].sort((Q,Y)=>Q[0].localeCompare(Y[0])),X={};for(let[Q,Y]of Z)X[Q]=Y;return X}import{createHash as rX}from"node:crypto";function h($){return $.replace(/\\/g,"/")}function _9($){return rX("sha256").update($).digest("hex").slice(0,12)}function u($){return[...$].sort()}function aX($){let Z;switch($.type){case"env-var":{let Q=u($.evidenceFiles.map(h));Z=`env-var:${$.name}:${Q.join(",")}`;break}case"dependency-change":{Z=`dependency-change:${$.name}:${$.from||"null"}:${$.to||"null"}:${$.section}`;break}case"route-change":{Z=`route-change:${h($.routeId)}:${$.change}:${$.routeType}`;break}case"db-migration":{let Q=u($.files.map(h));Z=`db-migration:${$.tool}:${Q.join(",")}`;break}case"cloudflare-change":{let Q=u($.files.map(h));Z=`cloudflare-change:${$.area}:${Q.join(",")}`;break}case"test-change":{let Q=u($.files.map(h));Z=`test-change:${$.framework}:${Q.join(",")}`;break}case"security-file":{let Q=u($.files.map(h)),Y=u($.reasons);Z=`security-file:${Q.join(",")}:${Y.join(",")}`;break}case"file-category":{Z=`file-category:${Object.entries($.categories).map(([Y,K])=>`${Y}:${u(K.map(h)).join(",")}`).sort().join("|")}`;break}case"file-summary":{let Q=u($.added.map(h)).join(","),Y=u($.modified.map(h)).join(","),K=u($.deleted.map(h)).join(","),W=u($.renamed.map((q)=>`${h(q.from)}->${h(q.to)}`)).join(",");Z=`file-summary:${$.category}:a=${Q}:m=${Y}:d=${K}:r=${W}`;break}case"convention-violation":{let Q=u($.files.map(h));Z=`convention-violation:${$.message}:${Q.join(",")}`;break}case"test-parity-violation":{let Q=h($.sourceFile),Y=u($.expectedTestLocations.map(h));Z=`test-parity-violation:${Q}:${Y.join(",")}`;break}case"impact-analysis":{let Q=h($.sourceFile),Y=u($.affectedFiles.map(h));Z=`impact-analysis:${Q}:${Y.join(",")}`;break}case"ci-workflow":{Z=`ci-workflow:${h($.file)}:${$.riskType}`;break}case"sql-risk":{Z=`sql-risk:${h($.file)}:${$.riskType}`;break}case"infra-change":{let Q=u($.files.map(h));Z=`infra-change:${$.infraType}:${Q.join(",")}`;break}case"api-contract-change":{Z=`api-contract-change:${u($.files.map(h)).join(",")}`;break}case"large-diff":{Z=`large-diff:${$.filesChanged}:${$.linesChanged}`;break}case"lockfile-mismatch":{Z=`lockfile-mismatch:${$.manifestChanged}:${$.lockfileChanged}`;break}case"test-gap":{Z=`test-gap:${$.prodFilesChanged}:${$.testFilesChanged}`;break}case"stencil-component-change":{let Q=h($.file);Z=`stencil-component-change:${$.tag}:${$.change}:${Q}:${$.fromTag||""}:${$.toTag||""}`;break}case"stencil-prop-change":{let Q=h($.file);Z=`stencil-prop-change:${$.tag}:${$.propName}:${$.change}:${Q}`;break}case"stencil-event-change":{let Q=h($.file);Z=`stencil-event-change:${$.tag}:${$.eventName}:${$.change}:${Q}`;break}case"stencil-method-change":{let Q=h($.file);Z=`stencil-method-change:${$.tag}:${$.methodName}:${$.change}:${Q}`;break}case"stencil-slot-change":{let Q=h($.file);Z=`stencil-slot-change:${$.tag}:${$.slotName}:${$.change}:${Q}`;break}case"risk-flag":{Z=`risk-flag:${$.risk}:${$.evidenceText}`;break}case"graphql-change":{let Q=h($.file),Y=u($.breakingChanges).join(","),K=u($.addedElements).join(",");Z=`graphql-change:${Q}:${$.isBreaking}:${Y}:${K}`;break}case"typescript-config":{let Q=h($.file),Y=u($.changedOptions.added).join(","),K=u($.changedOptions.removed).join(","),W=u($.changedOptions.modified).join(",");Z=`typescript-config:${Q}:${$.isBreaking}:a=${Y}:r=${K}:m=${W}`;break}case"tailwind-config":{let Q=h($.file),Y=u($.affectedSections).join(",");Z=`tailwind-config:${Q}:${$.configType}:${$.isBreaking}:${Y}`;break}case"monorepo-config":{let Q=h($.file),Y=u($.affectedFields).join(",");Z=`monorepo-config:${Q}:${$.tool}:${Y}`;break}case"package-exports":{let Q=u($.addedExports).join(","),Y=u($.removedExports).join(",");Z=`package-exports:${$.isBreaking}:a=${Q}:r=${Y}`;break}case"python-migration":{let Q=u($.files.map(h));Z=`python-migration:${$.tool}:${$.risk}:${Q.join(",")}`;break}case"python-config":{let Q=h($.file),Y=u($.affectedSections).join(",");Z=`python-config:${Q}:${$.configType}:${$.isBreaking}:${Y}`;break}case"angular-component-change":{Z=`angular-component-change:${h($.file)}:${$.change}:${$.componentType}:${$.selector||""}`;break}case"vite-config":{let Q=h($.file),Y=u($.affectedSections).join(","),K=u($.pluginsDetected).join(",");Z=`vite-config:${Q}:${$.isBreaking}:${Y}:${K}`;break}default:throw Error(`Unknown finding type: ${$.type}`)}let X=_9(Z);return`finding.${$.type}#${X}`}function f($,Z){let X=u(Z),Q=`${$}:${X.join(",")}`,Y=_9(Q);return`flag.${$}#${Y}`}function K$($){let Z=aX($);return{...$,findingId:Z}}var h$=()=>{};function sX($,Z){let X=0,Q=0;for(let Y of $.diffs)for(let K of Y.hunks)X+=K.additions.length,Q+=K.deletions.length;return{filesChanged:$.files.length,insertions:X,deletions:Q,skippedFilesCount:Z.length}}function iX($){return oX.has($.type)}function nX($){let Z=$.find((B)=>B.type==="file-summary"),X=$.find((B)=>B.type==="file-category"),Q=$.find((B)=>B.type==="large-diff"),Y=$.find((B)=>B.type==="lockfile-mismatch"),K={added:Z?.added??[],modified:Z?.modified??[],deleted:Z?.deleted??[],renamed:Z?.renamed??[]},W={product:[],tests:[],ci:[],infra:[],database:[],docs:[],dependencies:[],config:[],artifacts:[],other:[]},q=X?.categories??W,V=X?.summary??[],U=[];if(Q)U.push({type:"large-diff",filesChanged:Q.filesChanged,linesChanged:Q.linesChanged});if(Y)U.push({type:"lockfile-mismatch",manifestChanged:Y.manifestChanged,lockfileChanged:Y.lockfileChanged});let J=Z?.changeDescriptions;return{files:K,byCategory:q,categorySummary:V,changeDescriptions:J,warnings:U}}async function N$($){let{changeSet:Z,findings:X,riskScore:Q,requestedProfile:Y,detectedProfile:K,profileConfidence:W,profileReasons:q,filters:V,skippedFiles:U,warnings:J,noTimestamp:B,repoRoot:G,isDirty:M,mode:_}=$,O=M9(X);if(O=O.map(K$),V?.maxFindings&&O.length>V.maxFindings)O=O.slice(0,V.maxFindings);if(V?.redact)O=O.map((V1)=>({...V1,evidence:m2(V1.evidence.map(C5))}));else O=O.map((V1)=>({...V1,evidence:m2(V1.evidence)}));let H,z;if(G!==void 0&&M!==void 0)H=G,z=M;else if(G!==void 0)H=G,z=await _$();else if(M!==void 0)H=await M$(),z=M;else[H,z]=await Promise.all([M$(),_$()]);let N={base:Z.base,head:Z.head,range:`${Z.base}..${Z.head}`,repoRoot:H,isDirty:z,mode:_},j={requested:Y,detected:K,confidence:W,reasons:q},E=U??[],x=sX(Z,E),R={defaultExcludes:I5,excludes:V?.excludes??[],includes:V?.includes??[],redact:V?.redact??!1,maxFileBytes:V?.maxFileBytes??1048576,maxDiffBytes:V?.maxDiffBytes??5242880,maxFindings:V?.maxFindings},b=nX(O),w=O.filter((V1)=>!iX(V1)),p=O0(w,Q.factors),P=M0(p),N1=j$(w),U1={byArea:P,highlights:N1},A1=_0(O,K),a1=J??[];return{schemaVersion:"2.1",generatedAt:B?void 0:new Date().toISOString(),git:N,profile:j,stats:x,filters:R,summary:U1,categories:p,changeset:b,risk:Q,findings:w,actions:A1,skippedFiles:E,warnings:a1}}var oX;var z0=T(()=>{G0();X0();H$();h$();oX=new Set(["file-summary","file-category","large-diff","lockfile-mismatch"])});import{readFile as tX}from"node:fs/promises";async function L0($){let Z=await tX($,"utf-8");return JSON.parse(Z)}function H9($){let Z={...$};return delete Z.generatedAt,Z}function eX($,Z){let X=(Q)=>{if(Q===null||typeof Q!=="object")return Q;if(Array.isArray(Q))return Q.map(X);let Y={};return Object.keys(Q).sort().forEach((K)=>{Y[K]=X(Q[K])}),Y};return JSON.stringify(X($))===JSON.stringify(X(Z))}function z9($){let Z=new Map;for(let X of $){let Q=X.findingId||X.flagId;if(Q)Z.set(Q,X)}return Z}function j0($){let Z=z9($.beforeItems),X=z9($.afterItems),Q=[],Y=[],K=[];for(let[W,q]of X){let V=Z.get(W);if(!V)Q.push(W);else{let U=H9(V),J=H9(q);if(!eX(U,J))K.push({id:W,before:V,after:q})}}for(let W of Z.keys())if(!X.has(W))Y.push(W);return Q.sort(),Y.sort(),K.sort((W,q)=>W.id.localeCompare(q.id)),{added:Q,removed:Y,changed:K}}function D0($,Z){let X=[];if($.mode!==Z.mode)X.push({code:"scope-mismatch",message:`Previous run used mode=${$.mode}, current is mode=${Z.mode}`});if($.base!==Z.base)X.push({code:"scope-mismatch",message:`Previous run used base=${$.base}, current is base=${Z.base}`});if($.head!==Z.head)X.push({code:"scope-mismatch",message:`Previous run used head=${$.head}, current is head=${Z.head}`});if($.profile!==Z.profile)X.push({code:"scope-mismatch",message:`Previous run used profile=${$.profile}, current is profile=${Z.profile}`});let Q=JSON.stringify($.include||[]),Y=JSON.stringify(Z.include||[]);if(Q!==Y)X.push({code:"scope-mismatch",message:"Include filters differ between runs"});let K=JSON.stringify($.exclude||[]),W=JSON.stringify(Z.exclude||[]);if(K!==W)X.push({code:"scope-mismatch",message:"Exclude filters differ between runs"});if($.only!==void 0||Z.only!==void 0){let q=JSON.stringify($.only||null),V=JSON.stringify(Z.only||null);if(q!==V)X.push({code:"scope-mismatch",message:"Category filters differ between runs"})}return X}function L9($){let Z;if($.git.mode)Z=$.git.mode;else Z=$.git.base?"branch":"unstaged";return{mode:Z,base:$.git.base||null,head:$.git.head||null,profile:$.profile.detected,include:$.filters.includes,exclude:$.filters.excludes}}function j9($){let Z;if($.range.mode)Z=$.range.mode;else Z=$.range.base?"branch":"unstaged";return{mode:Z,base:$.range.base||null,head:$.range.head||null,only:$.filters?.only||null,exclude:$.filters?.exclude}}var u2=()=>{};var D9={};P1(D9,{computeFactsDelta:()=>g2});async function g2($){let{sincePath:Z,currentFacts:X,mode:Q,base:Y,head:K,profile:W,include:q,exclude:V,sinceStrict:U}=$,J;try{J=await L0(Z)}catch(j){let E=j instanceof Error?j.message:String(j);throw new y(`Failed to load previous facts from ${Z}: ${E}`,1)}if(!J.schemaVersion||!J.findings)throw new y(`File ${Z} does not appear to be a valid facts output`,1);let B={mode:Q,base:Y,head:K,profile:W,include:q,exclude:V},G=L9(J),M=D0(G,B);if(U&&M.length>0)throw new y(`Scope mismatch detected (--since-strict): ${M.map((j)=>j.message).join("; ")}`,1);let{added:_,removed:O,changed:H}=j0({beforeItems:J.findings,afterItems:X.findings}),z=H.map((j)=>({findingId:j.id,before:j.before,after:j.after})),N=["--mode",Q];if(Y)N.push("--base",Y);if(K)N.push("--head",K);if(N.push("--since",Z),U)N.push("--since-strict");return{schemaVersion:"1.0",generatedAt:new Date().toISOString(),command:{name:"facts",args:N},since:{path:Z,schemaVersion:J.schemaVersion},current:{schemaVersion:X.schemaVersion},scope:B,warnings:M,delta:{added:_,removed:O,changed:z},summary:{addedCount:_.length,removedCount:O.length,changedCount:z.length}}}var f2=T(()=>{u2();x1()});var N9={};P1(N9,{executeFacts:()=>$Q,deriveActions:()=>_0,computeFactsDelta:()=>g2,buildSummaryByArea:()=>M0,buildFacts:()=>N$,aggregateCategories:()=>O0});async function $Q($){return N$($)}var A9=T(()=>{z0();z0();f2()});var T9={};P1(T9,{renderSarif:()=>QQ,SARIF_RULES:()=>R9});function XQ($){return"file:///"+$.replace(/\\/g,"/")+"/"}function QQ($,Z){let X=KQ($.findings,Z),Q=new Set(X.map((K)=>K.ruleId)),Y=Array.from(Q).sort().map((K)=>{let W=R9[K];if(!W)throw Error(`Unknown SARIF rule ID: ${K}`);return YQ(W)});return{version:"2.1.0",$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",runs:[{tool:{driver:{name:"branch-narrator",version:J5(),informationUri:"https://github.com/better-vibe/branch-narrator",rules:Y}},results:X,originalUriBaseIds:{SRCROOT:{uri:XQ($.git.repoRoot)}}}]}}function YQ($){return{id:$.id,name:$.name,shortDescription:{text:$.shortDescription},fullDescription:{text:$.fullDescription},defaultConfiguration:{level:$.defaultLevel},properties:{category:$.category}}}function KQ($,Z){let X=[],Q=[...$].sort((Y,K)=>{if(Y.type!==K.type)return Y.type.localeCompare(K.type);return(Y.findingId||"").localeCompare(K.findingId||"")});for(let Y of Q){let K=qQ(Y,Z);if(K)X.push(K)}return X}function qQ($,Z){switch($.type){case"db-migration":return WQ($);case"dependency-change":return UQ($);case"env-var":return VQ($,Z);case"cloudflare-change":return JQ($);case"route-change":return BQ($);case"ci-workflow":return GQ($);case"security-file":return OQ($);case"graphql-change":return MQ($);case"package-exports":return _Q($);case"stencil-component-change":return HQ($);case"stencil-prop-change":return zQ($);case"stencil-event-change":return LQ($);case"stencil-method-change":return jQ($);case"stencil-slot-change":return DQ($);case"typescript-config":return NQ($);case"sql-risk":return AQ($);case"infra-change":return RQ($);case"test-gap":return TQ($);case"large-diff":return xQ($);default:return null}}function WQ($){let Z=$.risk==="high"?"BNR001":"BNR002",X=$.risk==="high"?"error":"warning",Q=$.evidence.map((W)=>({physicalLocation:{artifactLocation:{uri:W.file,uriBaseId:"SRCROOT"},region:W.line?{startLine:W.line}:void 0}})),Y=$.reasons.join(", "),K=$.risk==="high"?`Dangerous SQL migration detected: ${Y}`:`Database migration changed: ${Y}`;return{ruleId:Z,level:X,message:{text:K},locations:Q,partialFingerprints:{findingId:$.findingId||""},properties:{tool:$.tool,files:$.files,risk:$.risk}}}function UQ($){if($.impact!=="major"||!ZQ.includes($.name))return null;let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR003",level:"warning",message:{text:`Major version bump: ${$.name} ${$.from||"?"} → ${$.to||"?"}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{dependency:$.name,from:$.from,to:$.to,section:$.section}}}function VQ($,Z){let X=[];for(let Q of $.evidence){let Y=Q.line;if(Y==null&&Q.excerpt){let K=Z.diffs.find((W)=>W.path===Q.file);if(K){let q=e0(K).find((V)=>V.line.includes(Q.excerpt));if(q)Y=q.lineNumber}}X.push({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Y!=null?{startLine:Y}:void 0}})}return{ruleId:"BNR004",level:"warning",message:{text:`New environment variable referenced: ${$.name}`},locations:X,partialFingerprints:{findingId:$.findingId||""},properties:{envVar:$.name,change:$.change,evidenceFiles:$.evidenceFiles}}}function JQ($){let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR005",level:"note",message:{text:`Cloudflare configuration changed in ${$.files.join(", ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{area:$.area,files:$.files}}}function BQ($){let Z=$.evidence.map((Y)=>({physicalLocation:{artifactLocation:{uri:Y.file,uriBaseId:"SRCROOT"},region:Y.line?{startLine:Y.line}:void 0}})),X=$.methods?` (${$.methods.join(", ")})`:"";return{ruleId:"BNR006",level:"note",message:{text:`API endpoint ${$.change==="added"?"added":$.change==="deleted"?"deleted":"modified"}: ${$.routeId}${X}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{routeId:$.routeId,file:$.file,change:$.change,routeType:$.routeType,methods:$.methods}}}function GQ($){if($.riskType!=="permissions_broadened"&&$.riskType!=="pull_request_target")return null;let Z=$.riskType==="permissions_broadened"?"BNR007":"BNR008",X=$.evidence.map((Y)=>({physicalLocation:{artifactLocation:{uri:Y.file,uriBaseId:"SRCROOT"},region:Y.line?{startLine:Y.line}:void 0}})),Q=$.riskType==="permissions_broadened"?`CI workflow permissions broadened in ${$.file}: ${$.details}`:`CI workflow uses pull_request_target in ${$.file}: ${$.details}`;return{ruleId:Z,level:"error",message:{text:Q},locations:X,partialFingerprints:{findingId:$.findingId||""},properties:{file:$.file,riskType:$.riskType,details:$.details}}}function OQ($){let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR009",level:"warning",message:{text:`Security-sensitive files changed: ${$.files.join(", ")}. Reasons: ${$.reasons.join(", ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{files:$.files,reasons:$.reasons}}}function MQ($){if(!$.isBreaking)return null;let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR010",level:"error",message:{text:`Breaking GraphQL schema changes in ${$.file}: ${$.breakingChanges.join(", ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{file:$.file,breakingChanges:$.breakingChanges,addedElements:$.addedElements}}}function _Q($){if(!$.isBreaking)return null;let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}})),X=[];if($.removedExports.length>0)X.push(`removed exports: ${$.removedExports.join(", ")}`);if($.binChanges.removed.length>0)X.push(`removed bins: ${$.binChanges.removed.join(", ")}`);return{ruleId:"BNR011",level:"error",message:{text:`Breaking package exports changes: ${X.join("; ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{removedExports:$.removedExports,addedExports:$.addedExports,binChanges:$.binChanges}}}function HQ($){if($.change!=="removed")return null;let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR012",level:"warning",message:{text:`Stencil component removed: <${$.tag}>`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{tag:$.tag,change:$.change,file:$.file}}}function zQ($){if($.change!=="removed")return null;let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR012",level:"warning",message:{text:`Stencil prop removed: <${$.tag}> @Prop() ${$.propName}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{tag:$.tag,propName:$.propName,change:$.change,file:$.file}}}function LQ($){if($.change!=="removed")return null;let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR012",level:"warning",message:{text:`Stencil event removed: <${$.tag}> @Event() ${$.eventName}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{tag:$.tag,eventName:$.eventName,change:$.change,file:$.file}}}function jQ($){if($.change!=="removed")return null;let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR012",level:"warning",message:{text:`Stencil method removed: <${$.tag}> @Method() ${$.methodName}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{tag:$.tag,methodName:$.methodName,change:$.change,file:$.file}}}function DQ($){if($.change!=="removed")return null;let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR012",level:"warning",message:{text:`Stencil ${$.slotName==="default"?"default slot":`slot "${$.slotName}"`} removed from <${$.tag}>`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{tag:$.tag,slotName:$.slotName,change:$.change,file:$.file}}}function NQ($){if(!$.isBreaking)return null;let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}})),X=[];if($.strictnessChanges.length>0)X.push($.strictnessChanges.join(", "));if($.changedOptions.removed.length>0)X.push(`removed: ${$.changedOptions.removed.join(", ")}`);return{ruleId:"BNR013",level:"warning",message:{text:`Breaking TypeScript config changes in ${$.file}: ${X.join("; ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{file:$.file,changedOptions:$.changedOptions,strictnessChanges:$.strictnessChanges}}}function AQ($){if($.riskType!=="destructive")return null;let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR014",level:"error",message:{text:`Destructive SQL operation in ${$.file}: ${$.details}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{file:$.file,riskType:$.riskType,details:$.details}}}function RQ($){let Z=$.evidence.map((Q)=>({physicalLocation:{artifactLocation:{uri:Q.file,uriBaseId:"SRCROOT"},region:Q.line?{startLine:Q.line}:void 0}}));return{ruleId:"BNR015",level:"warning",message:{text:`${{dockerfile:"Dockerfile",terraform:"Terraform",k8s:"Kubernetes"}[$.infraType]} configuration changed: ${$.files.join(", ")}`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{infraType:$.infraType,files:$.files}}}function TQ($){let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR016",level:"note",message:{text:`Test coverage gap: ${$.prodFilesChanged} production files changed, ${$.testFilesChanged} test files changed`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{prodFilesChanged:$.prodFilesChanged,testFilesChanged:$.testFilesChanged}}}function xQ($){let Z=$.evidence.map((X)=>({physicalLocation:{artifactLocation:{uri:X.file,uriBaseId:"SRCROOT"},region:X.line?{startLine:X.line}:void 0}}));return{ruleId:"BNR017",level:"note",message:{text:`Large diff detected: ${$.filesChanged} files changed, ${$.linesChanged} lines modified`},locations:Z,partialFingerprints:{findingId:$.findingId||""},properties:{filesChanged:$.filesChanged,linesChanged:$.linesChanged}}}var R9,ZQ;var x9=T(()=>{s$();R9={BNR001:{id:"BNR001",name:"DangerousSqlInMigration",shortDescription:"Dangerous SQL detected in migration",fullDescription:"Database migration contains potentially destructive SQL operations (DROP, TRUNCATE, ALTER TYPE, etc.) that could cause data loss or service disruption.",defaultLevel:"error",category:"database"},BNR002:{id:"BNR002",name:"MigrationChanged",shortDescription:"Migration changed (non-destructive)",fullDescription:"Database migration file has been modified or added. Review schema changes for compatibility and rollback safety.",defaultLevel:"warning",category:"database"},BNR003:{id:"BNR003",name:"MajorDependencyBump",shortDescription:"Major bump in critical dependencies",fullDescription:"Major version bump detected in critical framework dependencies (e.g., @sveltejs/kit, svelte, vite, react, next). Major upgrades may introduce breaking changes.",defaultLevel:"warning",category:"dependencies"},BNR004:{id:"BNR004",name:"NewEnvVarReference",shortDescription:"New environment variable reference detected",fullDescription:"Code references a new environment variable. Ensure this variable is documented and configured in all deployment environments.",defaultLevel:"warning",category:"config_env"},BNR005:{id:"BNR005",name:"CloudflareConfigChanged",shortDescription:"Cloudflare configuration changed",fullDescription:"Cloudflare configuration files (wrangler.toml, Pages workflows) have been modified. Review deployment settings and worker configurations.",defaultLevel:"note",category:"infra"},BNR006:{id:"BNR006",name:"EndpointChanged",shortDescription:"API endpoint changed",fullDescription:"API endpoint file has been added, modified, or deleted. Verify API contract compatibility and update client code if needed.",defaultLevel:"note",category:"api"},BNR007:{id:"BNR007",name:"CIWorkflowPermissionsBroadened",shortDescription:"CI workflow permissions broadened",fullDescription:"GitHub Actions workflow has broadened permissions, which could allow unauthorized access to secrets or repository data. Review the permission changes carefully.",defaultLevel:"error",category:"security"},BNR008:{id:"BNR008",name:"CIWorkflowPullRequestTarget",shortDescription:"CI workflow uses pull_request_target",fullDescription:"GitHub Actions workflow uses pull_request_target trigger, which runs with write permissions on the base repository. This can be exploited if the workflow checks out or runs code from the PR.",defaultLevel:"error",category:"security"},BNR009:{id:"BNR009",name:"SecurityFileChanged",shortDescription:"Security-sensitive file changed",fullDescription:"A file related to authentication, authorization, or security configuration has been modified. Review these changes carefully for potential vulnerabilities.",defaultLevel:"warning",category:"security"},BNR010:{id:"BNR010",name:"GraphQLBreakingChange",shortDescription:"Breaking change in GraphQL schema",fullDescription:"GraphQL schema contains breaking changes such as removed types, fields, or arguments. This may break existing clients consuming the API.",defaultLevel:"error",category:"api"},BNR011:{id:"BNR011",name:"PackageExportsBreakingChange",shortDescription:"Breaking change in package exports",fullDescription:"Package exports have breaking changes such as removed exports or modified bin entries. This may break downstream consumers of this package.",defaultLevel:"error",category:"api"},BNR012:{id:"BNR012",name:"StencilAPIBreakingChange",shortDescription:"Breaking change in Stencil component API",fullDescription:"Stencil web component has breaking API changes such as removed props, events, methods, or slots. This may break consumers of the component library.",defaultLevel:"warning",category:"api"},BNR013:{id:"BNR013",name:"TypeScriptConfigBreaking",shortDescription:"Breaking TypeScript configuration change",fullDescription:"TypeScript configuration has breaking changes that may cause compilation errors in the codebase, such as stricter type checking options.",defaultLevel:"warning",category:"config_env"},BNR014:{id:"BNR014",name:"DestructiveSQL",shortDescription:"Destructive SQL operation detected",fullDescription:"SQL file contains destructive operations (DROP, TRUNCATE, DELETE without WHERE) that could cause data loss. Review carefully before execution.",defaultLevel:"error",category:"database"},BNR015:{id:"BNR015",name:"InfrastructureChanged",shortDescription:"Infrastructure configuration changed",fullDescription:"Infrastructure files (Dockerfile, Terraform, Kubernetes) have been modified. Review for security implications and deployment impact.",defaultLevel:"warning",category:"infra"},BNR016:{id:"BNR016",name:"TestGapDetected",shortDescription:"Test coverage gap detected",fullDescription:"Production code was modified but no corresponding test files were changed. Consider adding tests to cover the new or modified functionality.",defaultLevel:"note",category:"quality"},BNR017:{id:"BNR017",name:"LargeDiff",shortDescription:"Large diff detected",fullDescription:"This change has a large number of modified files or lines, which may indicate a refactoring or generated code. Consider breaking into smaller PRs for easier review.",defaultLevel:"note",category:"quality"}},ZQ=["@sveltejs/kit","svelte","vite","react","react-dom","next","@stencil/core"]});function l2($){if($==="pnpm-lock.yaml"||$==="package-lock.json"||$==="yarn.lock"||$==="bun.lockb")return{skip:!0,reason:"lockfile"};if($.endsWith(".d.ts"))return{skip:!0,reason:"generated file"};if($.endsWith(".log"))return{skip:!0,reason:"log file"};let Z=["dist/","build/","coverage/",".turbo/",".next/","out/",".cache/"];for(let X of Z)if($.includes(X))return{skip:!0,reason:"build artifact"};return{skip:!1}}var EQ;var c2=T(()=>{EQ=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","**/*.d.ts","**/*.log","dist/**","build/**","coverage/**",".turbo/**",".next/**","out/**",".cache/**"]});function E9($){let Z=$;Z=Z.replace(bQ,"<redacted-github-token>");for(let{eqPattern:X,colonPattern:Q}of IQ)X.lastIndex=0,Q.lastIndex=0,Z=Z.replace(X,(Y,K)=>`${K}=<redacted>`),Z=Z.replace(Q,(Y,K)=>`${K}: <redacted>`);if(!Z.includes("<redacted")&&!Z.includes("hash")&&!Z.includes("checksum"))Z=Z.replace(PQ,"<redacted-value>");return Z}function p2($){return $.map(E9)}var wQ,IQ,bQ,PQ;var d2=T(()=>{wQ=[/token/i,/secret/i,/password/i,/api[_-]?key/i,/private[_-]?key/i,/access[_-]?key/i,/auth[_-]?token/i],IQ=wQ.map(($)=>({eqPattern:new RegExp(`(${$.source})\\s*=\\s*['"]?([^'"\\s}<]+)['"]?`,"gi"),colonPattern:new RegExp(`(${$.source})\\s*:\\s*['"]?([^'"\\s,}<]+)['"]?`,"gi")})),bQ=/(ghp_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9_]+)/g,PQ=/\b[a-zA-Z0-9+/=]{32,}\b/g});function CQ($){let Z={api:0,churn:0,ci:0,db:0,deps:0,infra:0,security:0,tests:0};for(let X of $)Z[X.category]+=X.effectiveScore;for(let X of Object.keys(Z))Z[X]=Math.min(100,Z[X]);return Z}function SQ($){let Z=Object.values($);if(Z.length===0)return 0;let X=Math.max(...Z),Y=[...Z].sort((q,V)=>V-q).slice(0,3);while(Y.length<3)Y.push(0);let K=Y.reduce((q,V)=>q+V,0)/3,W=0.6*X+0.4*K;return Math.round(Math.max(0,Math.min(100,W)))}function kQ($){if($>=81)return"critical";if($>=61)return"high";if($>=41)return"elevated";if($>=21)return"moderate";return"low"}function FQ($){let X=Object.entries($).sort((U,J)=>J[1]-U[1]),Q=X.length>0?X[0]:["security",0],Y=X.slice(0,3).map(([U,J])=>({category:U,score:J})),K=Q[1],W=Y.map((U)=>U.score);while(W.length<3)W.push(0);let q=W.reduce((U,J)=>U+J,0)/3,V=`riskScore = round(0.6 * ${K} + 0.4 * ${q.toFixed(2)})`;return{maxCategory:{category:Q[0],score:K},topCategories:Y,formula:V}}function r2($,Z,X){let Q=$;if(Z&&Z.length>0)Q=Q.filter((Y)=>Z.includes(Y.category));if(X&&X.length>0)Q=Q.filter((Y)=>!X.includes(Y.category));return Q}function a2($,Z,X,Q,Y){let K=CQ(X),W=SQ(K),q=kQ(W),V={schemaVersion:"2.0",range:{base:$,head:Z,mode:Y?.mode},riskScore:W,riskLevel:q,categoryScores:K,flags:O9(X),skippedFiles:Q};if(!Y?.noTimestamp)V.generatedAt=new Date().toISOString();if(Y?.explainScore)V.scoreBreakdown=FQ(K);if(Y?.only||Y?.exclude)V.filters={only:Y.only,exclude:Y.exclude};return V}var s2=()=>{};function D1($){return $.evidence.map((Z)=>({file:Z.file,hunk:Z.hunk?`@@ -${Z.hunk.oldStart},${Z.hunk.oldLines} +${Z.hunk.newStart},${Z.hunk.newLines} @@`:void 0,lines:Z.excerpt.split(`
|
|
51
|
+
`).slice(0,5)}))}function vQ($){let Z=[];for(let X of $){let Q=[X.findingId];switch(X.riskType){case"permissions_broadened":{Z.push({ruleKey:"security.workflow_permissions_broadened",flagId:f("security.workflow_permissions_broadened",Q),relatedFindingIds:Q,category:"security",score:35,confidence:0.9,title:"Workflow permissions broadened",summary:`Workflow ${X.file} has broadened permissions (write access)`,evidence:D1(X),suggestedChecks:["Review if write permissions are necessary","Ensure principle of least privilege","Check if GITHUB_TOKEN usage is secure"],effectiveScore:Math.round(31.5)});break}case"pull_request_target":{Z.push({ruleKey:"security.workflow_uses_pull_request_target",flagId:f("security.workflow_uses_pull_request_target",Q),relatedFindingIds:Q,category:"security",score:40,confidence:0.9,title:"Workflow uses pull_request_target",summary:`Workflow ${X.file} uses pull_request_target event (can expose secrets)`,evidence:D1(X),suggestedChecks:["Ensure no untrusted code is executed in this context","Review if pull_request_target is necessary (vs pull_request)","Verify secrets are not exposed to PR authors"],effectiveScore:Math.round(36)});break}case"remote_script_download":{Z.push({ruleKey:"security.workflow_downloads_remote_script",flagId:f("security.workflow_downloads_remote_script",Q),relatedFindingIds:Q,category:"security",score:45,confidence:0.85,title:"Workflow downloads and executes remote scripts",summary:`Workflow ${X.file} downloads and pipes to shell (supply chain risk)`,evidence:D1(X),suggestedChecks:["Pin script sources to specific commit SHAs","Verify script integrity with checksums","Consider vendoring the script instead"],effectiveScore:Math.round(38.25)});break}case"pipeline_changed":{Z.push({ruleKey:"ci.pipeline_changed",flagId:f("ci.pipeline_changed",Q),relatedFindingIds:Q,category:"ci",score:10,confidence:0.7,title:"CI/CD pipeline configuration changed",summary:`Pipeline ${X.file} was modified`,evidence:D1(X),suggestedChecks:["Review pipeline changes for security implications","Test pipeline changes in a non-production environment"],effectiveScore:Math.round(7)});break}}}return Z}function yQ($){let Z=[];for(let X of $){let Q=[X.findingId];switch(X.riskType){case"destructive":{Z.push({ruleKey:"db.destructive_sql",flagId:f("db.destructive_sql",Q),relatedFindingIds:Q,category:"db",score:45,confidence:0.9,title:"Destructive SQL detected",summary:`Migration ${X.file} contains DROP TABLE/COLUMN or TRUNCATE`,evidence:D1(X),suggestedChecks:["Backup data before running migration","Verify this is intentional data deletion","Test migration rollback procedure","Consider making column nullable instead of dropping"],effectiveScore:Math.round(40.5)});break}case"schema_change":{Z.push({ruleKey:"db.schema_change_risky",flagId:f("db.schema_change_risky",Q),relatedFindingIds:Q,category:"db",score:30,confidence:0.85,title:"Risky schema change detected",summary:`Migration ${X.file} contains ALTER COLUMN or TYPE change`,evidence:D1(X),suggestedChecks:["Test schema changes on production-like data","Check for data type compatibility","Monitor migration execution time (may lock table)"],effectiveScore:Math.round(25.5)});break}case"unscoped_modification":{Z.push({ruleKey:"db.unscoped_data_modification",flagId:f("db.unscoped_data_modification",Q),relatedFindingIds:Q,category:"db",score:35,confidence:0.75,title:"Unscoped data modification detected",summary:`Migration ${X.file} contains UPDATE/DELETE without WHERE clause`,evidence:D1(X),suggestedChecks:["Verify this affects all rows intentionally","Add WHERE clause if only subset should be modified","Test on staging data first"],effectiveScore:Math.round(26.25)});break}}}return Z}function mQ($){let Z=[],X=$.filter((q)=>q.type==="stencil-component-change"),Q=$.filter((q)=>q.type==="stencil-prop-change"),Y=$.filter((q)=>q.type==="stencil-event-change"),K=$.filter((q)=>q.type==="stencil-method-change"),W=$.filter((q)=>q.type==="stencil-slot-change");for(let q of X){if(q.change==="tag-changed"){let U=[q.findingId];Z.push({ruleKey:"stencil.tag_changed",flagId:f("stencil.tag_changed",U),relatedFindingIds:U,category:"api",score:45,confidence:0.95,title:"Component tag changed",summary:`Tag changed from "${q.fromTag}" to "${q.toTag}"`,evidence:D1(q),suggestedChecks:["Update all usages of this component","This is a breaking change"],effectiveScore:Math.round(42.75)})}if(q.change==="shadow-changed"){let U=[q.findingId];Z.push({ruleKey:"stencil.shadow_changed",flagId:f("stencil.shadow_changed",U),relatedFindingIds:U,category:"api",score:25,confidence:0.9,title:"Shadow DOM configuration changed",summary:`Shadow DOM enabled changed from ${q.fromShadow} to ${q.toShadow}`,evidence:D1(q),suggestedChecks:["Check styles and global styling impact"],effectiveScore:Math.round(22.5)})}}for(let q of Q)if(q.change==="removed"){let U=[q.findingId];Z.push({ruleKey:"stencil.prop_removed",flagId:f("stencil.prop_removed",U),relatedFindingIds:U,category:"api",score:40,confidence:0.95,title:"Component prop removed",summary:`Prop "${q.propName}" removed from <${q.tag}>`,evidence:D1(q),suggestedChecks:["This is a breaking change","Check usages"],effectiveScore:Math.round(38)})}else if(q.change==="changed"){let U=[q.findingId];Z.push({ruleKey:"stencil.prop_changed",flagId:f("stencil.prop_changed",U),relatedFindingIds:U,category:"api",score:35,confidence:0.9,title:"Component prop modified",summary:`Prop "${q.propName}" options changed`,evidence:D1(q),suggestedChecks:["Check for attribute/reflect/mutable changes"],effectiveScore:Math.round(31.5)})}for(let q of Y)if(q.change==="removed"){let U=[q.findingId];Z.push({ruleKey:"stencil.event_removed",flagId:f("stencil.event_removed",U),relatedFindingIds:U,category:"api",score:40,confidence:0.95,title:"Component event removed",summary:`Event "${q.eventName}" removed from <${q.tag}>`,evidence:D1(q),suggestedChecks:["This is a breaking change","Check event listeners"],effectiveScore:Math.round(38)})}else if(q.change==="changed"){let U=[q.findingId];Z.push({ruleKey:"stencil.event_changed",flagId:f("stencil.event_changed",U),relatedFindingIds:U,category:"api",score:35,confidence:0.9,title:"Component event modified",summary:`Event "${q.eventName}" options changed`,evidence:D1(q),suggestedChecks:["Check bubbles/composed/cancelable options"],effectiveScore:Math.round(31.5)})}for(let q of K)if(q.change==="removed"){let U=[q.findingId];Z.push({ruleKey:"stencil.method_removed",flagId:f("stencil.method_removed",U),relatedFindingIds:U,category:"api",score:40,confidence:0.95,title:"Component method removed",summary:`Method "${q.methodName}" removed from <${q.tag}>`,evidence:D1(q),suggestedChecks:["This is a breaking change","Check usages"],effectiveScore:Math.round(38)})}else if(q.change==="changed");for(let q of W)if(q.change==="removed"){let U=[q.findingId];Z.push({ruleKey:"stencil.slot_removed",flagId:f("stencil.slot_removed",U),relatedFindingIds:U,category:"api",score:35,confidence:0.9,title:"Component slot removed",summary:`Slot "${q.slotName}" removed from <${q.tag}>`,evidence:D1(q),suggestedChecks:["Check content projection usages"],effectiveScore:Math.round(31.5)})}return Z}function o2($){let Z=[],X=$.filter((O)=>O.type==="ci-workflow"),Q=$.filter((O)=>O.type==="sql-risk"),Y=$.filter((O)=>O.type==="infra-change"),K=$.filter((O)=>O.type==="api-contract-change"),W=$.filter((O)=>O.type==="large-diff"),q=$.filter((O)=>O.type==="lockfile-mismatch"),V=$.filter((O)=>O.type==="test-gap"),U=$.filter((O)=>O.type==="dependency-change"),J=$.filter((O)=>O.type==="db-migration"),B=$.filter((O)=>O.type==="test-change");Z.push(...vQ(X)),Z.push(...yQ(Q)),Z.push(...mQ($));for(let O of Y){let H=[O.findingId],z=`infra.${O.infraType}_changed`,N={dockerfile:"Dockerfile changed",terraform:"Terraform configuration changed",k8s:"Kubernetes manifest changed"};Z.push({ruleKey:z,flagId:f(z,H),relatedFindingIds:H,category:"infra",score:20,confidence:0.8,title:N[O.infraType],summary:`${O.files.length} ${O.infraType} ${O.files.length===1?"file":"files"} changed`,evidence:O.files.slice(0,3).map((j)=>({file:j,lines:["File changed"]})),suggestedChecks:["Review infrastructure changes carefully","Test in staging environment","Verify no unintended resource changes"],effectiveScore:Math.round(16)})}if(K.length>0){let O=K.map((N)=>N.findingId),H="api.contract_changed",z=K.flatMap((N)=>N.files);Z.push({ruleKey:"api.contract_changed",flagId:f("api.contract_changed",O),relatedFindingIds:O,category:"api",score:25,confidence:0.85,title:"API contract changed",summary:`${z.length} API ${z.length===1?"file":"files"} changed`,evidence:z.slice(0,3).map((N)=>({file:N,lines:["File changed"]})),suggestedChecks:["Verify backwards compatibility","Update API documentation","Notify API consumers of changes"],effectiveScore:Math.round(21.25)})}if(W.length>0){let O=W[0],H=[O.findingId],z="churn.large_diff";Z.push({ruleKey:"churn.large_diff",flagId:f("churn.large_diff",H),relatedFindingIds:H,category:"churn",score:15,confidence:0.9,title:"Large diff detected",summary:`${O.filesChanged} files changed, ${O.linesChanged} lines modified`,evidence:[],suggestedChecks:["Consider breaking into smaller PRs","Ensure adequate test coverage","Review carefully for unintended changes"],effectiveScore:Math.round(13.5)})}for(let O of q){let H=[O.findingId],z="deps.lockfile_without_manifest";Z.push({ruleKey:"deps.lockfile_without_manifest",flagId:f("deps.lockfile_without_manifest",H),relatedFindingIds:H,category:"deps",score:20,confidence:0.9,title:"Lockfile changed without manifest",summary:O.manifestChanged?"package.json changed without lockfile update":"Lockfile changed without package.json update",evidence:[],suggestedChecks:["Run package manager install to sync lockfile","Verify dependencies are correctly resolved"],effectiveScore:Math.round(18)})}for(let O of V){let H=[O.findingId],z="tests.possible_gap";Z.push({ruleKey:"tests.possible_gap",flagId:f("tests.possible_gap",H),relatedFindingIds:H,category:"tests",score:18,confidence:0.7,title:"Possible test coverage gap",summary:`${O.prodFilesChanged} production files changed with no test updates`,evidence:[],suggestedChecks:["Add tests for new functionality","Update existing tests if behavior changed"],effectiveScore:Math.round(12.6)})}let G=U.filter((O)=>O.section==="dependencies"&&!O.from);if(G.length>0){let O=G.map((z)=>z.findingId),H="deps.new_prod_dependency";Z.push({ruleKey:"deps.new_prod_dependency",flagId:f("deps.new_prod_dependency",O),relatedFindingIds:O,category:"deps",score:15,confidence:0.85,title:"New production dependencies added",summary:`${G.length} new production ${G.length===1?"dependency":"dependencies"} added`,evidence:G.slice(0,5).map((z)=>({file:"package.json",lines:[`+ "${z.name}": "${z.to}"`]})),suggestedChecks:["Review new dependencies for security vulnerabilities","Check license compatibility","Verify dependencies are actively maintained"],tags:G.map((z)=>z.name),effectiveScore:Math.round(12.75)})}let M=U.filter((O)=>O.impact==="major");if(M.length>0){let O=M.map((z)=>z.findingId),H="deps.major_version_bump";Z.push({ruleKey:"deps.major_version_bump",flagId:f("deps.major_version_bump",O),relatedFindingIds:O,category:"deps",score:25,confidence:0.9,title:"Major dependency version bump",summary:`${M.length} ${M.length===1?"dependency":"dependencies"} with major version changes`,evidence:M.slice(0,5).map((z)=>({file:"package.json",lines:[`"${z.name}": "${z.from}" -> "${z.to}"`]})),suggestedChecks:["Review breaking changes in dependency changelogs","Update code for API changes","Run full test suite"],tags:M.map((z)=>z.name),effectiveScore:Math.round(22.5)})}if(J.length>0){let O=J.map((z)=>z.findingId),H="db.migrations_changed";Z.push({ruleKey:"db.migrations_changed",flagId:f("db.migrations_changed",O),relatedFindingIds:O,category:"db",score:12,confidence:0.8,title:"Database migrations changed",summary:`${J.length} migration/SQL ${J.length===1?"file":"files"} changed`,evidence:J.slice(0,3).flatMap((z)=>z.files.map((N)=>({file:N,lines:["Migration file changed"]}))),suggestedChecks:["Test migrations on a staging database","Ensure migrations are reversible","Check for data loss or downtime impact"],effectiveScore:Math.round(9.600000000000001)})}if(B.length>0){let O=B.map((z)=>z.findingId),H="tests.changed";Z.push({ruleKey:"tests.changed",flagId:f("tests.changed",O),relatedFindingIds:O,category:"tests",score:5,confidence:0.8,title:"Test files changed",summary:`${B.length} test ${B.length===1?"file":"files"} modified`,evidence:B.slice(0,3).flatMap((z)=>z.files.map((N)=>({file:N,lines:["Test file changed"]}))),suggestedChecks:["Verify tests still pass","Review test coverage changes"],effectiveScore:Math.round(4)})}let _=$.filter((O)=>O.type==="test-parity-violation");if(_.length>0){let O=_.map((R)=>R.findingId),H="tests.missing_parity",z=_.filter((R)=>R.confidence==="high").length,N=_.filter((R)=>R.confidence==="medium").length,j=12+z*2+N*1,E=Math.min(j,25),x=z>N?0.85:0.7;Z.push({ruleKey:"tests.missing_parity",flagId:f("tests.missing_parity",O),relatedFindingIds:O,category:"tests",score:E,confidence:x,title:"Source files without test coverage",summary:`${_.length} source ${_.length===1?"file":"files"} modified without corresponding tests`,evidence:_.slice(0,5).map((R)=>({file:R.sourceFile,lines:[`No test file found (expected: ${R.expectedTestLocations[0]||"unknown"})`]})),suggestedChecks:["Add tests for new/changed code","Verify existing tests cover the changes","Consider if these files need unit tests"],effectiveScore:Math.round(E*x)})}return Z}var i2=T(()=>{h$()});function hQ($,Z=!1){return Z?JSON.stringify($,null,2):JSON.stringify($)}function uQ($){let Z=[];Z.push("# Risk Report"),Z.push(""),Z.push(`**Range:** \`${$.range.base}..${$.range.head}\``),Z.push("");let X=fQ($.riskLevel);Z.push(`## Overall Risk: ${X} ${$.riskLevel.toUpperCase()}`),Z.push(""),Z.push(`**Score:** ${$.riskScore}/100`),Z.push(""),Z.push("### Category Scores"),Z.push("");let Q=Object.entries($.categoryScores).sort((Y,K)=>K[1]-Y[1]);for(let[Y,K]of Q)if(K>0){let W="█".repeat(Math.floor(K/10));Z.push(`- **${Y}**: ${K}/100 ${W}`)}if(Z.push(""),$.flags.length>0){Z.push("## Risk Flags"),Z.push("");let Y=lQ($.flags);for(let[K,W]of Object.entries(Y)){if(W.length===0)continue;Z.push(`### ${K.toUpperCase()}`),Z.push("");for(let q of W){if(Z.push(`#### ${q.title}`),Z.push(""),Z.push(`**Rule:** \`${q.ruleKey}\``),Z.push(`**Flag ID:** \`${q.flagId}\``),Z.push(`**Score:** ${q.effectiveScore}/100 (base: ${q.score}, confidence: ${q.confidence})`),Z.push(""),Z.push(q.summary),Z.push(""),q.evidence.length>0){Z.push("**Evidence:**"),Z.push("");for(let V of q.evidence){if(Z.push(`- **${V.file}**`),V.hunk)Z.push(` \`${V.hunk}\``);if(V.lines.length>0){Z.push(" ```");for(let U of V.lines)Z.push(` ${U}`);Z.push(" ```")}}Z.push("")}if(q.suggestedChecks.length>0){Z.push("**Suggested Checks:**"),Z.push("");for(let V of q.suggestedChecks)Z.push(`- ${V}`);Z.push("")}}}}if($.scoreBreakdown){Z.push("## Score Breakdown"),Z.push(""),Z.push(`**Max Category:** ${$.scoreBreakdown.maxCategory.category} (${$.scoreBreakdown.maxCategory.score})`),Z.push(""),Z.push("**Top 3 Categories:**");for(let Y of $.scoreBreakdown.topCategories)Z.push(`- ${Y.category}: ${Y.score}`);Z.push(""),Z.push(`**Formula:** \`${$.scoreBreakdown.formula}\``),Z.push("")}if($.skippedFiles.length>0){Z.push("## Skipped Files"),Z.push(""),Z.push(`${$.skippedFiles.length} files were skipped:`),Z.push("");for(let Y of $.skippedFiles.slice(0,20))Z.push(`- \`${Y.file}\` (${Y.reason})`);if($.skippedFiles.length>20)Z.push(`- ... and ${$.skippedFiles.length-20} more`);Z.push("")}return Z.join(`
|
|
52
|
+
`)}function gQ($){let Z=[];Z.push("RISK REPORT"),Z.push("=".repeat(60)),Z.push(""),Z.push(`Range: ${$.range.base}..${$.range.head}`),Z.push(""),Z.push(`Overall Risk: ${$.riskLevel.toUpperCase()}`),Z.push(`Score: ${$.riskScore}/100`),Z.push(""),Z.push("Category Scores:"),Z.push("-".repeat(40));let X=Object.entries($.categoryScores).sort((Q,Y)=>Y[1]-Q[1]);for(let[Q,Y]of X)if(Y>0){let K="#".repeat(Math.floor(Y/5));Z.push(` ${Q.padEnd(12)} ${Y.toString().padStart(3)}/100 ${K}`)}if(Z.push(""),$.flags.length>0){Z.push("Risk Flags:"),Z.push("-".repeat(40));for(let Q of $.flags)if(Z.push(""),Z.push(`[${Q.ruleKey}] ${Q.title}`),Z.push(` Score: ${Q.effectiveScore}/100`),Z.push(` ${Q.summary}`),Q.evidence.length>0){Z.push(` Evidence: ${Q.evidence.length} location(s)`);for(let Y of Q.evidence.slice(0,2))Z.push(` - ${Y.file}`)}Z.push("")}if($.skippedFiles.length>0)Z.push(`Skipped Files: ${$.skippedFiles.length}`),Z.push("");return Z.join(`
|
|
53
|
+
`)}function fQ($){switch($){case"critical":return"\uD83D\uDD34";case"high":return"\uD83D\uDFE0";case"elevated":return"\uD83D\uDFE1";case"moderate":return"\uD83D\uDD35";case"low":return"\uD83D\uDFE2";default:return"⚪"}}function lQ($){let Z={};for(let X of $){if(!Z[X.category])Z[X.category]=[];Z[X.category].push(X)}return Z}var w9={};P1(w9,{computeRiskReportDelta:()=>n2});async function n2($){let{sincePath:Z,currentReport:X,mode:Q,base:Y,head:K,only:W,exclude:q,sinceStrict:V}=$,U;try{U=await L0(Z)}catch(j){let E=j instanceof Error?j.message:String(j);throw new y(`Failed to load previous risk report from ${Z}: ${E}`,1)}if(!U.schemaVersion||!U.flags||U.riskScore===void 0)throw new y(`File ${Z} does not appear to be a valid risk report output`,1);let J={mode:Q,base:Y,head:K,only:W},B=j9(U),G=D0(B,J);if(V&&G.length>0)throw new y(`Scope mismatch detected (--since-strict): ${G.map((j)=>j.message).join("; ")}`,1);let{added:M,removed:_,changed:O}=j0({beforeItems:U.flags,afterItems:X.flags}),H=O.map((j)=>({flagId:j.id,before:j.before,after:j.after})),z={from:U.riskScore,to:X.riskScore,delta:X.riskScore-U.riskScore},N=["--mode",Q];if(Y)N.push("--base",Y);if(K)N.push("--head",K);if(W)N.push("--only",W.join(","));if(q)N.push("--exclude",q.join(","));if(N.push("--since",Z),V)N.push("--since-strict");return{schemaVersion:"1.0",generatedAt:new Date().toISOString(),command:{name:"risk-report",args:N},since:{path:Z,schemaVersion:U.schemaVersion},current:{schemaVersion:X.schemaVersion},scope:J,delta:{riskScore:z,flags:{added:M,removed:_,changed:H}},summary:{flagAddedCount:M.length,flagRemovedCount:_.length,flagChangedCount:H.length}}}var t2=T(()=>{u2();x1()});var I9={};P1(I9,{shouldSkipFile:()=>l2,renderRiskReportText:()=>gQ,renderRiskReportMarkdown:()=>uQ,renderRiskReportJSON:()=>hQ,redactLines:()=>p2,redactLine:()=>E9,generateRiskReport:()=>A$,findingsToFlags:()=>o2,filterFlagsByCategory:()=>r2,executeRiskReport:()=>cQ,computeRiskReportDelta:()=>n2,computeRiskReport:()=>a2,DEFAULT_EXCLUSIONS:()=>EQ});async function A$($,Z={}){let{only:X,exclude:Q,maxEvidenceLines:Y=5,redact:K=!1,explainScore:W=!1,noTimestamp:q=!1,profile:V="auto",cwd:U=process.cwd(),mode:J,testParity:B=!1}=Z,G=[];for(let N of $.files){let j=l2(N.path);if(j.skip)G.push({file:N.path,reason:j.reason||"excluded"})}let M=Y$(V,$,U),_=h1(M),O=await v1(_.analyzers,$);if(B){let{testParityAnalyzer:N}=await Promise.resolve().then(() => (J0(),W2)),j=await N.analyze($);O.push(...j)}let H=O.map(K$),z=o2(H);if(z=r2(z,X,Q),K||Y!==5)z=z.map((N)=>({...N,evidence:h2(N.evidence.map((j)=>({...j,lines:K?p2(j.lines.slice(0,Y)):j.lines.slice(0,Y)})))}));else z=z.map((N)=>({...N,evidence:h2(N.evidence)}));return a2($.base,$.head,z,G,{explainScore:W,noTimestamp:q,mode:J,only:X,exclude:Q})}async function cQ($,Z={}){return await A$($,Z)}var N0=T(()=>{c2();d2();s2();m$();h$();i2();t2();c2();d2();s2();i2()});var P9={};P1(P9,{executeZoom:()=>pQ});async function pQ($,Z){if(Z.findingId&&Z.flagId)throw new y("Cannot specify both --finding and --flag. Use only one.",1);if(!Z.findingId&&!Z.flagId)throw new y("Must specify either --finding <id> or --flag <id>",1);if(Z.findingId)return dQ($,Z);else return rQ($,Z)}async function dQ($,Z){let X=Z.findingId,Q=Y$(Z.profile,$,process.cwd()),Y=h1(Q),q=(await v1(Y.analyzers,$)).map(K$).find((B)=>B.findingId===X);if(!q)throw new y(`Finding not found: ${X}. Run 'facts' or 'risk-report' to see available findings.`,1);let V=q.evidence.slice(0,Z.maxEvidenceLines).map((B)=>({file:B.file,excerpt:Z.redact?K0(B.excerpt):B.excerpt,line:B.line,hunk:B.hunk})),U;if(Z.includePatch)U=await aQ($,q,Z.unified,Z.redact);return{schemaVersion:"1.0",generatedAt:Z.noTimestamp?void 0:new Date().toISOString(),range:{base:$.base,head:$.head},itemType:"finding",findingId:X,finding:q,evidence:V,patchContext:U}}async function rQ($,Z){let X=Z.flagId,Q=Y$(Z.profile,$,process.cwd()),Y=h1(Q),W=(await v1(Y.analyzers,$)).map(K$),V=(await A$($,{profile:Z.profile,redact:Z.redact,maxEvidenceLines:Z.maxEvidenceLines,noTimestamp:Z.noTimestamp})).flags.find((G)=>G.flagId===X);if(!V)throw new y(`Flag not found: ${X}. Run 'risk-report' to see available flags.`,1);let U=W.filter((G)=>V.relatedFindingIds.includes(G.findingId)),J;if(Z.includePatch&&V.evidence.length>0)J=await b9($,V.evidence.map((G)=>G.file),Z.unified,Z.redact);return{schemaVersion:"1.0",generatedAt:Z.noTimestamp?void 0:new Date().toISOString(),range:{base:$.base,head:$.head},itemType:"flag",flagId:X,flag:V,evidence:V.evidence.slice(0,Z.maxEvidenceLines),relatedFindings:U,patchContext:J}}async function aQ($,Z,X,Q){let Y=new Set;for(let K of Z.evidence)Y.add(K.file);return b9($,Array.from(Y),X,Q)}async function b9($,Z,X,Q){let Y=[];for(let K of Z){let W=$.diffs.find((q)=>q.path===K);if(!W)continue;Y.push({file:W.path,status:W.status,hunks:W.hunks.map((q)=>({oldStart:q.oldStart,oldLines:q.oldLines,newStart:q.newStart,newLines:q.newLines,content:Q?K0(q.content):q.content}))})}return Y}var C9=T(()=>{x1();m$();h$();N0()});var S9={};P1(S9,{renderZoomText:()=>tQ,renderZoomMarkdown:()=>oQ,renderZoomJSON:()=>sQ});function sQ($,Z){return Z?JSON.stringify($,null,2):JSON.stringify($)}function oQ($){if($.itemType==="finding")return iQ($);else return nQ($)}function iQ($){let Z=[];if(Z.push(`# Finding: ${$.findingId}`),Z.push(""),Z.push(`**Type:** ${$.finding.type}`),Z.push(`**Category:** ${$.finding.category}`),Z.push(`**Confidence:** ${$.finding.confidence}`),Z.push(""),Z.push(`**Range:** ${$.range.base}..${$.range.head}`),Z.push(""),Z.push("## Details"),Z.push(""),Z.push("```json"),Z.push(JSON.stringify($.finding,null,2)),Z.push("```"),Z.push(""),$.evidence.length>0){Z.push("## Evidence"),Z.push("");for(let X of $.evidence){if(Z.push(`### ${X.file}`),X.line!==void 0)Z.push(`Line ${X.line}`);if(X.hunk)Z.push(`Hunk: @@ -${X.hunk.oldStart},${X.hunk.oldLines} +${X.hunk.newStart},${X.hunk.newLines} @@`);Z.push(""),Z.push("```"),Z.push(X.excerpt),Z.push("```"),Z.push("")}}if($.patchContext&&$.patchContext.length>0){Z.push("## Patch Context"),Z.push("");for(let X of $.patchContext){Z.push(`### ${X.file} (${X.status})`),Z.push("");for(let Q of X.hunks)Z.push("```diff"),Z.push(`@@ -${Q.oldStart},${Q.oldLines} +${Q.newStart},${Q.newLines} @@`),Z.push(Q.content),Z.push("```"),Z.push("")}}return Z.join(`
|
|
54
|
+
`)}function nQ($){let Z=[];if(Z.push(`# Flag: ${$.flagId}`),Z.push(""),Z.push(`**Rule:** ${$.flag.ruleKey}`),Z.push(`**Category:** ${$.flag.category}`),Z.push(`**Score:** ${$.flag.effectiveScore} (base: ${$.flag.score}, confidence: ${$.flag.confidence})`),Z.push(""),Z.push(`**Range:** ${$.range.base}..${$.range.head}`),Z.push(""),Z.push("## Details"),Z.push(""),Z.push(`**Title:** ${$.flag.title}`),Z.push(""),Z.push(`**Summary:** ${$.flag.summary}`),Z.push(""),$.flag.suggestedChecks&&$.flag.suggestedChecks.length>0){Z.push("### Suggested Checks"),Z.push("");for(let X of $.flag.suggestedChecks)Z.push(`- ${X}`);Z.push("")}if($.evidence.length>0){Z.push("## Evidence"),Z.push("");for(let X of $.evidence){if(Z.push(`### ${X.file}`),X.hunk)Z.push(`Hunk: ${X.hunk}`);Z.push(""),Z.push("```"),Z.push(X.lines.join(`
|
|
55
|
+
`)),Z.push("```"),Z.push("")}}if($.relatedFindings&&$.relatedFindings.length>0){Z.push("## Related Findings"),Z.push("");for(let X of $.relatedFindings)Z.push(`- **${X.findingId}** (${X.type}, ${X.category})`);Z.push("")}if($.patchContext&&$.patchContext.length>0){Z.push("## Patch Context"),Z.push("");for(let X of $.patchContext){Z.push(`### ${X.file} (${X.status})`),Z.push("");for(let Q of X.hunks)Z.push("```diff"),Z.push(`@@ -${Q.oldStart},${Q.oldLines} +${Q.newStart},${Q.newLines} @@`),Z.push(Q.content),Z.push("```"),Z.push("")}}return Z.join(`
|
|
56
|
+
`)}function tQ($){if($.itemType==="finding")return eQ($);else return $Y($)}function eQ($){let Z=[];if(Z.push(`Finding: ${$.findingId}`),Z.push("=".repeat(60)),Z.push(""),Z.push(`Type: ${$.finding.type}`),Z.push(`Category: ${$.finding.category}`),Z.push(`Confidence: ${$.finding.confidence}`),Z.push(`Range: ${$.range.base}..${$.range.head}`),Z.push(""),$.evidence.length>0){Z.push("Evidence:"),Z.push("-".repeat(60));for(let X of $.evidence){if(Z.push(`File: ${X.file}`),X.line!==void 0)Z.push(` Line: ${X.line}`);if(X.hunk)Z.push(` Hunk: @@ -${X.hunk.oldStart},${X.hunk.oldLines} +${X.hunk.newStart},${X.hunk.newLines} @@`);Z.push(""),Z.push(X.excerpt),Z.push("")}}if($.patchContext&&$.patchContext.length>0){Z.push("Patch Context:"),Z.push("-".repeat(60));for(let X of $.patchContext){Z.push(`File: ${X.file} (${X.status})`),Z.push("");for(let Q of X.hunks)Z.push(`@@ -${Q.oldStart},${Q.oldLines} +${Q.newStart},${Q.newLines} @@`),Z.push(Q.content),Z.push("")}}return Z.join(`
|
|
57
|
+
`)}function $Y($){let Z=[];if(Z.push(`Flag: ${$.flagId}`),Z.push("=".repeat(60)),Z.push(""),Z.push(`Rule: ${$.flag.ruleKey}`),Z.push(`Category: ${$.flag.category}`),Z.push(`Score: ${$.flag.effectiveScore} (base: ${$.flag.score}, confidence: ${$.flag.confidence})`),Z.push(`Range: ${$.range.base}..${$.range.head}`),Z.push(""),Z.push(`Title: ${$.flag.title}`),Z.push(`Summary: ${$.flag.summary}`),Z.push(""),$.flag.suggestedChecks&&$.flag.suggestedChecks.length>0){Z.push("Suggested Checks:");for(let X of $.flag.suggestedChecks)Z.push(` - ${X}`);Z.push("")}if($.evidence.length>0){Z.push("Evidence:"),Z.push("-".repeat(60));for(let X of $.evidence){if(Z.push(`File: ${X.file}`),X.hunk)Z.push(` Hunk: ${X.hunk}`);Z.push(""),Z.push(X.lines.join(`
|
|
58
|
+
`)),Z.push("")}}if($.relatedFindings&&$.relatedFindings.length>0){Z.push("Related Findings:"),Z.push("-".repeat(60));for(let X of $.relatedFindings)Z.push(` - ${X.findingId} (${X.type}, ${X.category})`);Z.push("")}if($.patchContext&&$.patchContext.length>0){Z.push("Patch Context:"),Z.push("-".repeat(60));for(let X of $.patchContext){Z.push(`File: ${X.file} (${X.status})`),Z.push("");for(let Q of X.hunks)Z.push(`@@ -${Q.oldStart},${Q.oldLines} +${Q.newStart},${Q.newLines} @@`),Z.push(Q.content),Z.push("")}}return Z.join(`
|
|
59
|
+
`)}var w1=`# branch-narrator CLI Reference
|
|
56
60
|
|
|
57
61
|
Use \`branch-narrator\` to get deterministic, repo-grounded context about changes
|
|
58
62
|
between git refs. It does not use an LLM and will not invent intent.
|
|
@@ -199,10 +203,10 @@ Before risky/experimental changes → run \`snap save\`
|
|
|
199
203
|
|
|
200
204
|
## Default Behavior
|
|
201
205
|
|
|
202
|
-
- **Mode:** Defaults to \`unstaged\` (local
|
|
206
|
+
- **Mode:** Defaults to \`unstaged\` (local unstaged changes) if no mode specified
|
|
203
207
|
- **Base/Head:** For branch mode, defaults to \`main\` and \`HEAD\` if not specified
|
|
204
208
|
- **For PR descriptions:** Always use \`--mode branch\`
|
|
205
|
-
`,
|
|
209
|
+
`,e2=`# PR Description (use branch-narrator)
|
|
206
210
|
|
|
207
211
|
When the user asks to write a PR description, generate a Markdown PR body they
|
|
208
212
|
can copy-paste directly. Ground everything in the repo diff; do not invent
|
|
@@ -251,317 +255,405 @@ Env vars, migrations, infrastructure changes (if applicable).
|
|
|
251
255
|
|
|
252
256
|
### Risks & Mitigations
|
|
253
257
|
Concrete risks with evidence and verification steps.
|
|
254
|
-
`;import{stat as
|
|
258
|
+
`;import{stat as k9}from"node:fs/promises";async function q$($){try{return(await k9($)).isFile()}catch{return!1}}async function W$($){try{return(await k9($)).isDirectory()}catch{return!1}}var R$=()=>{};import{join as ZY}from"node:path";var F9="CLAUDE.md",v9;var y9=T(()=>{R$();v9={name:"claude",description:"Integrate with CLAUDE.md (Claude Code)",detect:async($)=>q$(ZY($,F9)),generate:()=>{let $=`
|
|
255
259
|
|
|
256
260
|
## Branch Narrator Usage
|
|
257
261
|
|
|
258
|
-
${
|
|
262
|
+
${w1}`;return[{path:F9,content:$}]}}});import{readdir as XY}from"node:fs/promises";import{join as h9}from"node:path";async function QY($){try{let Z=h9($,".cursor","rules");return(await XY(Z)).some((Y)=>Y.endsWith(".mdc"))?"mdc":"md"}catch{return"md"}}function m9($){return`---
|
|
259
263
|
alwaysApply: true
|
|
260
264
|
---
|
|
261
265
|
|
|
262
|
-
${$}`}var
|
|
266
|
+
${$}`}var A0;var $5=T(()=>{R$();A0={name:"cursor",description:"Generate Cursor rules (.cursor/rules/*.md or *.mdc)",detect:async($)=>W$(h9($,".cursor","rules")),generate:async($)=>{let Z=await QY($),X=Z==="mdc"?".mdc":".md",Q=Z==="mdc"?m9(w1):w1,Y=Z==="mdc"?m9(e2):e2;return[{path:`.cursor/rules/branch-narrator${X}`,content:Q},{path:`.cursor/rules/pr-description${X}`,content:Y}]}}});import{join as YY}from"node:path";var u9;var g9=T(()=>{R$();u9={name:"jules-rules",description:"Generate Jules rules in .jules/rules/branch-narrator.md",detect:async($)=>W$(YY($,".jules")),generate:()=>[{path:".jules/rules/branch-narrator.md",content:w1}]}});import{join as KY}from"node:path";var f9;var l9=T(()=>{R$();f9={name:"jules",description:"Integrate with AGENTS.md (Jules)",detect:async($)=>q$(KY($,"AGENTS.md")),generate:()=>{return[{path:"AGENTS.md",content:`
|
|
263
267
|
|
|
264
268
|
## Branch Narrator Usage
|
|
265
269
|
|
|
266
|
-
${
|
|
270
|
+
${w1}`}]}}});import{join as R0}from"node:path";async function qY($){for(let Z of c9)if(await q$(R0($,Z)))return{path:Z,useSection:!0};if(await W$(R0($,".opencode")))return{path:".opencode/branch-narrator.md",useSection:!1};return{path:"OPENCODE.md",useSection:!0}}var c9,p9;var d9=T(()=>{R$();c9=["OPENCODE.md","opencode.md"];p9={name:"opencode",description:"Integrate with OPENCODE.md or .opencode/",detect:async($)=>{for(let Z of c9)if(await q$(R0($,Z)))return!0;return W$(R0($,".opencode"))},generate:async($)=>{let Z=await qY($),X=Z.useSection?`
|
|
267
271
|
|
|
268
272
|
## Branch Narrator Usage
|
|
269
273
|
|
|
270
|
-
${
|
|
274
|
+
${w1}`:w1;return[{path:Z.path,content:X}]}}});async function r9(){return await A0.generate("")}var a9=T(()=>{$5()});var i9={};P1(i9,{generateCursorRules:()=>r9,executeIntegrate:()=>_Y});import{mkdir as WY,writeFile as s9,access as UY,readFile as VY}from"node:fs/promises";import{dirname as JY,join as BY}from"node:path";async function GY($){try{return await UY($),!0}catch{return!1}}async function OY($,Z,X){for(let Q of $){let Y=BY(Z,Q.path),K=await GY(Y);if(await WY(JY(Y),{recursive:!0}),K&&!X){let W=await VY(Y,"utf-8"),q=W.endsWith(`
|
|
271
275
|
`)?"":`
|
|
272
|
-
`,V=W+q+
|
|
273
|
-
Supported targets: ${Q.join(", ")}`,1);await P9(X,$,Z)}var H0;var k9=x(()=>{H1();L9();h2();N9();T9();E9();b9();H0={cursor:O0,jules:R9,claude:z9,"jules-rules":A9,opencode:w9}});import{mkdir as _0,readFile as y$,writeFile as k$,readdir as FV,rm as mV,stat as MX}from"node:fs/promises";import{join as E1,dirname as HX}from"node:path";import{createHash as S9}from"node:crypto";function S$($=process.cwd()){return E1($,_X,zX)}function m9($=process.cwd()){return E1(S$($),LX)}function p1($,Z=process.cwd()){return E1(S$(Z),$)}function c2($,Z=process.cwd()){return E1(p1($,Z),jX)}function AX($,Z=process.cwd()){return E1(p1($,Z),v9)}function NX($,Z=process.cwd()){return E1(p1($,Z),F9)}function u9($,Z=process.cwd()){return E1(p1($,Z),g2)}function h9($,Z=process.cwd()){return E1(u9($,Z),l2)}function g9($,Z=process.cwd()){return E1(u9($,Z),DX)}function l9($,Z,Q=process.cwd()){return E1(g9($,Q),Z)}function S1($){return S9("sha256").update($).digest("hex")}function z0($,Z,Q,X){let K=`${$}:${Z}:${Q}:${X}`;return S9("sha256").update(K).digest("hex").slice(0,12)}async function RX($=process.cwd()){await _0(S$($),{recursive:!0})}async function L0($,Z=process.cwd()){let Q=p1($,Z);await _0(Q,{recursive:!0}),await _0(g9($,Z),{recursive:!0})}async function v1($,Z=process.cwd()){try{let Q=c2($,Z);return await MX(Q),!0}catch{return!1}}async function v$($=process.cwd()){try{let Z=m9($),Q=await y$(Z,"utf-8");return JSON.parse(Q)}catch{return{schemaVersion:"1.0",snapshots:[]}}}async function TX($,Z=process.cwd()){await RX(Z);let Q=m9(Z);await k$(Q,JSON.stringify($,null,2),"utf-8")}async function c9($,Z=process.cwd()){let Q=await v$(Z);Q.snapshots=Q.snapshots.filter((X)=>X.snapshotId!==$.snapshotId),Q.snapshots.push($),Q.snapshots.sort((X,K)=>K.createdAt.localeCompare(X.createdAt)),await TX(Q,Z)}async function F1($,Z=process.cwd()){let Q=c2($,Z),X=await y$(Q,"utf-8");return JSON.parse(X)}async function f9($,Z,Q=process.cwd()){await L0($,Q);let X=c2($,Q);await k$(X,JSON.stringify(Z,null,2),"utf-8")}async function f2($,Z,Q,X=process.cwd()){await L0($,X);let K=Z==="staged"?v9:F9,Y=E1(p1($,X),K);return await k$(Y,Q),{path:K,sha256:S1(Q),bytes:Q.length}}async function p2($,Z,Q=process.cwd()){let X=Z==="staged"?AX($,Q):NX($,Q);return await y$(X)}async function F$($,Z=process.cwd()){try{let Q=h9($,Z),X=await y$(Q,"utf-8");return JSON.parse(X)}catch{return{entries:[]}}}async function p9($,Z,Q=process.cwd()){await L0($,Q);let X=h9($,Q);await _0(HX(X),{recursive:!0}),await k$(X,JSON.stringify(Z,null,2),"utf-8")}async function d9($,Z,Q=process.cwd()){await L0($,Q);let X=S1(Z),K=l9($,X,Q);return await k$(K,Z),X}async function r9($,Z,Q=process.cwd()){let X=l9($,Z,Q);return await y$(X)}function a9($){return{snapshotId:$.snapshotId,label:$.label,createdAt:$.createdAt,headSha:$.git.headSha,branch:$.git.branch,filesChanged:$.analysis.facts.stats.filesChanged,riskScore:$.analysis.riskReport.riskScore,flagCount:$.analysis.riskReport.flags.length,findingCount:$.analysis.facts.findings.length}}function d2(){return new Date().toISOString().replace(/[:.]/g,"-")}function s9(){return`auto/pre-restore/${d2()}`}var _X=".branch-narrator",zX="snapshots",LX="index.json",jX="snapshot.json",v9="staged.patch",F9="unstaged.patch",g2="untracked",l2="manifest.json",DX="blobs";var X$=()=>{};import{execa as d1}from"execa";import{readFile as xX,stat as wX,chmod as EX,unlink as fV,readdir as pV,rmdir as dV}from"node:fs/promises";import{join as r2,dirname as IX}from"node:path";async function z$($=process.cwd()){try{return(await d1("git",["rev-parse","HEAD"],{cwd:$})).stdout.trim()}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new d("git rev-parse HEAD",String(Z.stderr));throw Z}}async function j0($=process.cwd()){try{let Q=(await d1("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:$})).stdout.trim();return Q==="HEAD"?"":Q}catch{return""}}async function L$($=process.cwd()){try{let Z=await d1("git",["diff","--binary","--staged"],{cwd:$,maxBuffer:104857600});return Buffer.from(Z.stdout,"utf-8")}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new d("git diff --binary --staged",String(Z.stderr));throw Z}}async function j$($=process.cwd()){try{let Z=await d1("git",["diff","--binary"],{cwd:$,maxBuffer:104857600});return Buffer.from(Z.stdout,"utf-8")}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new d("git diff --binary",String(Z.stderr));throw Z}}async function D0($,Z={},Q=process.cwd()){if($.length===0)return;let X=["apply"];if(Z.cached)X.push("--cached");if(Z.check)X.push("--check");X.push("-");try{await d1("git",X,{cwd:Q,input:$})}catch(K){if(K instanceof Error&&"stderr"in K)throw new d(`git ${X.join(" ")}`,String(K.stderr));throw K}}async function A0($=process.cwd()){try{let Q=(await d1("git",["ls-files","--others","--exclude-standard","-z"],{cwd:$})).stdout;if(!Q)return[];return Q.split("\x00").filter(Boolean)}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new d("git ls-files --others --exclude-standard -z",String(Z.stderr));throw Z}}async function o9($,Z=process.cwd()){let Q=r2(Z,$);return await xX(Q)}async function n9($,Z=process.cwd()){let Q=r2(Z,$);return(await wX(Q)).mode}async function i9($=process.cwd()){try{await d1("git",["reset","--hard","HEAD"],{cwd:$})}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new d("git reset --hard HEAD",String(Z.stderr));throw Z}}async function t9($=process.cwd()){try{await d1("git",["clean","-fd","--exclude=.branch-narrator"],{cwd:$})}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new d("git clean -fd --exclude=.branch-narrator",String(Z.stderr));throw Z}}async function e9($,Z,Q,X=process.cwd()){let{writeFile:K,mkdir:Y}=await import("node:fs/promises"),W=r2(X,$);await Y(IX(W),{recursive:!0}),await K(W,Z),await EX(W,Q)}var N0=x(()=>{H1()});import{writeFile as bX,mkdir as CX}from"node:fs/promises";import{dirname as PX}from"node:path";async function R0($={}){let Z=$.cwd??process.cwd(),Q=$.label??`snapshot-${d2()}`,[X,K]=await Promise.all([z$(Z),j0(Z)]),[Y,W]=await Promise.all([L$(Z),j$(Z)]),q=await A0(Z),V={entries:[]},U=new Map,J=0;for(let r of q)try{let j=await o9(r,Z),C=await n9(r,Z),O1=S1(j),I0={path:r,blobSha256:O1,mode:C,bytes:j.length};V.entries.push(I0),U.set(O1,j),J+=j.length}catch{continue}V.entries.sort((r,j)=>r.path.localeCompare(j.path));let B=S1(Y),G=S1(W),M=JSON.stringify(V),H=z0(X,B,G,M),O=await l1({mode:"all",cwd:Z,includeUntracked:!0}),[z,_]=await Promise.all([V$(Z),J$(Z)]),D="auto",L=b$(O,Z),w=L.profile,T=y1(w),A=await I1(T.analyzers,O),b=O$(A),R=await M$({changeSet:O,findings:A,riskScore:b,requestedProfile:D,detectedProfile:w,profileConfidence:L.confidence,profileReasons:L.reasons,filters:{excludes:[],includes:[],redact:!1,maxFileBytes:1048576,maxDiffBytes:5242880},skippedFiles:[],warnings:[],noTimestamp:!0,repoRoot:z,isDirty:_,mode:"all"}),h=await H$(O,{noTimestamp:!0,mode:"all",cwd:Z}),y=await g$(),r1=new Date().toISOString(),a1={schemaVersion:"1.0",snapshotId:H,label:Q,createdAt:r1,tool:{name:"branch-narrator",version:y},git:{headSha:X,branch:K},workspace:{patches:{staged:{path:"staged.patch",sha256:B,bytes:Y.length},unstaged:{path:"unstaged.patch",sha256:G,bytes:W.length}},untracked:{manifestPath:`${g2}/${l2}`,fileCount:V.entries.length,totalBytes:J}},analysis:{facts:R,riskReport:h}};await f2(H,"staged",Y,Z),await f2(H,"unstaged",W,Z),await p9(H,V,Z);for(let[,r]of U)await d9(H,r,Z);await f9(H,a1,Z);let K$=a9(a1);await c9(K$,Z);let Y$={snapshotId:H,label:Q,snapshotPath:`.branch-narrator/snapshots/${H}`};if($.out)await CX(PX($.out),{recursive:!0}),await bX($.out,H,"utf-8");return Y$}var a2=x(()=>{X$();N0();l$();B$();C$();U0();G0();B$()});async function $Z($={}){let Z=$.cwd??process.cwd(),Q=await v$(Z);return Q.snapshots.sort((X,K)=>K.createdAt.localeCompare(X.createdAt)),Q}function ZZ($,Z=!1){return Z?JSON.stringify($,null,2):JSON.stringify($)}var QZ=x(()=>{X$()});async function XZ($,Z={}){let Q=Z.cwd??process.cwd();if(!await v1($,Q))throw new m1($);return await F1($,Q)}function KZ($,Z=!1){return Z?JSON.stringify($,null,2):JSON.stringify($)}var m1;var T0=x(()=>{X$();H1();m1=class m1 extends v{constructor($){super(`Snapshot not found: ${$}`,1);this.name="SnapshotNotFoundError"}}});async function YZ($,Z,Q={}){let X=Q.cwd??process.cwd();if(!await v1($,X))throw new m1($);if(!await v1(Z,X))throw new m1(Z);let[K,Y]=await Promise.all([F1($,X),F1(Z,X)]),[W,q]=await Promise.all([F$($,X),F$(Z,X)]),V=yX(K.analysis.facts.findings,Y.analysis.facts.findings),U=kX(K.analysis.riskReport.flags,Y.analysis.riskReport.flags),J=SX(K,Y,W.entries,q.entries);return{schemaVersion:"1.0",from:$,to:Z,delta:{riskScore:{from:K.analysis.riskReport.riskScore,to:Y.analysis.riskReport.riskScore,delta:Y.analysis.riskReport.riskScore-K.analysis.riskReport.riskScore},findings:V,flags:U,files:J},summary:{findingsAdded:V.added.length,findingsRemoved:V.removed.length,findingsChanged:V.changed.length,flagsAdded:U.added.length,flagsRemoved:U.removed.length,flagsChanged:U.changed.length,filesAdded:J.added.length,filesRemoved:J.removed.length,filesModified:J.modified.length}}}function yX($,Z){let Q=new Map,X=new Map;for(let q of $)if(q.findingId)Q.set(q.findingId,q);for(let q of Z)if(q.findingId)X.set(q.findingId,q);let K=[],Y=[],W=[];for(let q of Q.keys())if(!X.has(q))Y.push(q);for(let[q,V]of X){let U=Q.get(q);if(!U)K.push(q);else if(!x0(U,V))W.push({findingId:q,before:U,after:V})}return K.sort(),Y.sort(),W.sort((q,V)=>q.findingId.localeCompare(V.findingId)),{added:K,removed:Y,changed:W}}function kX($,Z){let Q=new Map,X=new Map;for(let q of $)if(q.flagId)Q.set(q.flagId,q);for(let q of Z)if(q.flagId)X.set(q.flagId,q);let K=[],Y=[],W=[];for(let q of Q.keys())if(!X.has(q))Y.push(q);for(let[q,V]of X){let U=Q.get(q);if(!U)K.push(q);else if(!x0(U,V))W.push({flagId:q,before:U,after:V})}return K.sort(),Y.sort(),W.sort((q,V)=>q.flagId.localeCompare(V.flagId)),{added:K,removed:Y,changed:W}}function SX($,Z,Q,X){let K=new Set,Y=new Set,W=new Map,q=new Map,V=$.analysis.facts.changeset,U=Z.analysis.facts.changeset;for(let M of V.files.added)K.add(M),W.set(M,"added");for(let M of V.files.modified)K.add(M),W.set(M,"modified");for(let M of V.files.deleted)K.add(M),W.set(M,"deleted");for(let{from:M,to:H}of V.files.renamed)K.add(M),K.add(H),W.set(M,`renamed:${H}`);for(let M of U.files.added)Y.add(M),q.set(M,"added");for(let M of U.files.modified)Y.add(M),q.set(M,"modified");for(let M of U.files.deleted)Y.add(M),q.set(M,"deleted");for(let{from:M,to:H}of U.files.renamed)Y.add(M),Y.add(H),q.set(M,`renamed:${H}`);for(let M of Q)K.add(M.path),W.set(M.path,M.blobSha256);for(let M of X)Y.add(M.path),q.set(M.path,M.blobSha256);let J=[],B=[],G=[];for(let M of K)if(!Y.has(M))B.push(M);for(let M of Y)if(!K.has(M))J.push(M);else{let H=W.get(M),O=q.get(M);if(H!==O)G.push(M)}return J.sort(),B.sort(),G.sort(),{added:J,removed:B,modified:G}}function x0($,Z){if($===Z)return!0;if($===null||Z===null)return!1;if(typeof $!=="object"||typeof Z!=="object")return!1;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let K=0;K<$.length;K++)if(!x0($[K],Z[K]))return!1;return!0}if(Array.isArray($)||Array.isArray(Z))return!1;let Q=Object.keys($).sort(),X=Object.keys(Z).sort();if(Q.length!==X.length)return!1;if(!Q.every((K,Y)=>K===X[Y]))return!1;for(let K of Q)if(!x0($[K],Z[K]))return!1;return!0}function qZ($,Z=!1){return Z?JSON.stringify($,null,2):JSON.stringify($)}var WZ=x(()=>{X$();T0()});async function UZ($,Z={}){let Q=Z.cwd??process.cwd();if(!await v1($,Q))throw new m1($);let X=await F1($,Q),K=await z$(Q);if(K!==X.git.headSha)throw new w0(X.git.headSha,K);let Y=s9(),W=await R0({label:Y,cwd:Q});await i9(Q),await t9(Q);let q=await p2($,"staged",Q);if(q.length>0)try{await D0(q,{cached:!0},Q),await D0(q,{},Q)}catch(B){throw new m$("staged",B instanceof Error?B.message:String(B))}let V=await p2($,"unstaged",Q);if(V.length>0)try{await D0(V,{},Q)}catch(B){throw new m$("unstaged",B instanceof Error?B.message:String(B))}let U=await F$($,Q);for(let B of U.entries){let G=await r9($,B.blobSha256,Q);await e9(B.path,G,B.mode,Q)}let J=await vX(X,Q);return{snapshotId:$,backupSnapshotId:W.snapshotId,success:!0,verified:J}}async function vX($,Z){try{let[Q,X]=await Promise.all([L$(Z),j$(Z)]),K=S1(Q),Y=S1(X),W=K===$.workspace.patches.staged.sha256,q=Y===$.workspace.patches.unstaged.sha256;return W&&q}catch{return!1}}var w0,m$,s2;var VZ=x(()=>{X$();N0();a2();T0();H1();w0=class w0 extends v{constructor($,Z){super(`HEAD mismatch: snapshot was created at ${$.slice(0,8)} but current HEAD is ${Z.slice(0,8)}. Snapshots can only be restored when HEAD matches the original commit.`,1);this.name="HeadMismatchError"}};m$=class m$ extends v{constructor($,Z){super(`Failed to apply ${$} patch: ${Z}`,1);this.name="PatchApplicationError"}};s2=class s2 extends v{constructor($){super(`Restore verification failed: ${$}`,1);this.name="RestoreVerificationError"}}});var D$={};A1(D$,{snapshotExists:()=>v1,renderSnapShowJSON:()=>KZ,renderSnapListJSON:()=>ZZ,renderSnapDiffJSON:()=>qZ,readSnapshotJson:()=>F1,readIndex:()=>v$,getUntrackedFiles:()=>A0,getUnstagedPatch:()=>j$,getStagedPatch:()=>L$,getSnapshotsDir:()=>S$,getSnapshotDir:()=>p1,getHeadSha:()=>z$,getCurrentBranch:()=>j0,executeSnapShow:()=>XZ,executeSnapSave:()=>R0,executeSnapRestore:()=>UZ,executeSnapList:()=>$Z,executeSnapDiff:()=>YZ,computeSnapshotId:()=>z0,SnapshotNotFoundError:()=>m1,RestoreVerificationError:()=>s2,PatchApplicationError:()=>m$,HeadMismatchError:()=>w0});var A$=x(()=>{X$();N0();a2();QZ();T0();WZ();VZ()});H1();l$();import{Command as FX}from"commander";import{createInterface as mX}from"readline";import uX from"ora";import hX from"chalk";H1();import{mkdir as X5,writeFile as K5}from"node:fs/promises";import{dirname as IZ,join as bZ}from"node:path";var R1={quiet:!1,debug:!1};function n2($){if($.quiet)R1.quiet=!0,R1.debug=!1;else R1.quiet=!1,R1.debug=$.debug??!1}function oX(){return{...R1}}function nX(){R1.quiet=!1,R1.debug=!1}function s1($){if(!R1.quiet)console.error($)}function l($){if(!R1.quiet)console.error($)}function iX($){if(!R1.quiet&&R1.debug)console.error(`[DEBUG] ${$}`)}function c($){console.error($)}import RZ from"picomatch";var o1=["**/pnpm-lock.yaml","**/package-lock.json","**/yarn.lock","**/bun.lock","**/bun.lockb","**/*.d.ts","**/*.log","**/*.logs","**/dist/**","**/build/**","**/.svelte-kit/**","**/.next/**","**/.turbo/**","**/coverage/**","**/.cache/**","**/*.min.*","**/*.map"];function k0($){let Z=["diff","--name-status","--find-renames"];switch($.mode){case"branch":Z.push(`${$.base}..${$.head}`);break;case"unstaged":break;case"staged":Z.push("--staged");break;case"all":Z.push("HEAD");break}return Z}function S0($){let Z=["diff",`--unified=${$.unified}`,"--find-renames"];switch($.mode){case"branch":Z.push(`${$.base}..${$.head}`);break;case"unstaged":break;case"staged":Z.push("--staged");break;case"all":Z.push("HEAD");break}if(Z.push("--"),$.oldPath)Z.push($.oldPath);return Z.push($.path),Z}function v0($,Z){return["diff","--no-index",`--unified=${Z}`,"--","/dev/null",$]}function F0($){if(!$)return[];return $.split("\x00").filter(Boolean)}function y0($){if($.length===0)return()=>!1;let Z=$.map((Q)=>RZ(Q,{dot:!0}));return(Q)=>Z.some((X)=>X(Q))}function W$($){let{files:Z,includeGlobs:Q,excludeGlobs:X,defaultExcludes:K}=$,Y=y0(Q),W=y0(X),q=y0(K),V=Q.length>0,U=[],J=[];for(let B of Z){let G=B.path;if(W(G)){J.push({path:G,reason:"excluded-by-glob"});continue}if(V){if(!Y(G)){J.push({path:G,reason:"not-included"});continue}U.push(B);continue}if(q(G)){J.push({path:G,reason:"excluded-by-default"});continue}U.push(B)}return U.sort((B,G)=>B.path.localeCompare(G.path)),{included:U,skipped:J}}function m0($,Z){if($.length===0)return[];let Q=[],X=[],K=0;for(let Y of $){let W=Y.diff.length;if(W>Z){if(X.length>0)Q.push(X),X=[],K=0;Q.push([Y]);continue}if(K+W>Z&&X.length>0)Q.push(X),X=[],K=0;X.push(Y),K+=W}if(X.length>0)Q.push(X);return Q}function c$($){return $.map((Z)=>Z.diff).join(`
|
|
274
|
-
`)}function
|
|
275
|
-
`)),
|
|
276
|
-
`)}function
|
|
277
|
-
`),
|
|
278
|
-
`),
|
|
279
|
-
`)});
|
|
280
|
-
`);for(let
|
|
281
|
-
`);for(let
|
|
282
|
-
`);for(let O of B)M.push(`- \`${O.path}\``);let
|
|
283
|
-
`);if($.out)await
|
|
284
|
-
`);if($.out)await
|
|
276
|
+
`,V=W+q+Q.content;await s9(Y,V,"utf-8"),console.log(` - ${Q.path} (appended)`)}else{await s9(Y,Q.content,"utf-8");let W=K?"overwritten":"created";console.log(` - ${Q.path} (${W})`)}}}async function o9($,Z,X){let Q=await $.generate(X);if(Z.dryRun){console.log("=".repeat(80)),console.log(`DRY RUN: Integration for ${$.name}`),console.log("=".repeat(80)),console.log();for(let Y of Q)console.log(`File: ${Y.path}`),console.log("-".repeat(80)),console.log(Y.content),console.log("-".repeat(80)),console.log();return}console.log(`Integration for ${$.name}:`),await OY(Q,X,Z.force)}async function MY($){let Z=[];for(let[X,Q]of Object.entries(T0)){if(!Q.detect)continue;try{if(await Q.detect($))Z.push(X)}catch{}}return Z}async function _Y($){let Z=$.cwd??process.cwd(),X=Object.keys(T0);if(!$.target){let Y=await MY(Z);if(Y.length===0){console.log("No supported agent guide files detected in this repo."),console.log(`Run "branch-narrator integrate <target>" with one of: ${X.join(", ")}`);return}console.log(`Auto-detected guides: ${Y.join(", ")}`);for(let K of Y){let W=T0[K];await o9(W,$,Z)}return}let Q=T0[$.target];if(!Q)throw new y(`Unknown integration target: ${$.target}
|
|
277
|
+
Supported targets: ${X.join(", ")}`,1);await o9(Q,$,Z)}var T0;var n9=T(()=>{x1();y9();$5();g9();l9();d9();a9();T0={cursor:A0,jules:f9,claude:v9,"jules-rules":u9,opencode:p9}});import{mkdir as x0,readFile as u$,writeFile as g$,readdir as HB,rm as zB,stat as HY}from"node:fs/promises";import{join as F1,dirname as zY}from"node:path";import{createHash as t9}from"node:crypto";function f$($=process.cwd()){return F1($,LY,jY)}function ZZ($=process.cwd()){return F1(f$($),DY)}function t1($,Z=process.cwd()){return F1(f$(Z),$)}function Q5($,Z=process.cwd()){return F1(t1($,Z),NY)}function RY($,Z=process.cwd()){return F1(t1($,Z),e9)}function TY($,Z=process.cwd()){return F1(t1($,Z),$Z)}function XZ($,Z=process.cwd()){return F1(t1($,Z),Z5)}function QZ($,Z=process.cwd()){return F1(XZ($,Z),X5)}function YZ($,Z=process.cwd()){return F1(XZ($,Z),AY)}function KZ($,Z,X=process.cwd()){return F1(YZ($,X),Z)}function c1($){return t9("sha256").update($).digest("hex")}function E0($,Z,X,Q){let Y=`${$}:${Z}:${X}:${Q}`;return t9("sha256").update(Y).digest("hex").slice(0,12)}async function xY($=process.cwd()){await x0(f$($),{recursive:!0})}async function w0($,Z=process.cwd()){let X=t1($,Z);await x0(X,{recursive:!0}),await x0(YZ($,Z),{recursive:!0})}async function p1($,Z=process.cwd()){try{let X=Q5($,Z);return await HY(X),!0}catch{return!1}}async function l$($=process.cwd()){try{let Z=ZZ($),X=await u$(Z,"utf-8");return JSON.parse(X)}catch{return{schemaVersion:"1.0",snapshots:[]}}}async function EY($,Z=process.cwd()){await xY(Z);let X=ZZ(Z);await g$(X,JSON.stringify($,null,2),"utf-8")}async function qZ($,Z=process.cwd()){let X=await l$(Z);X.snapshots=X.snapshots.filter((Q)=>Q.snapshotId!==$.snapshotId),X.snapshots.push($),X.snapshots.sort((Q,Y)=>Y.createdAt.localeCompare(Q.createdAt)),await EY(X,Z)}async function d1($,Z=process.cwd()){let X=Q5($,Z),Q=await u$(X,"utf-8");return JSON.parse(Q)}async function WZ($,Z,X=process.cwd()){await w0($,X);let Q=Q5($,X);await g$(Q,JSON.stringify(Z,null,2),"utf-8")}async function Y5($,Z,X,Q=process.cwd()){await w0($,Q);let Y=Z==="staged"?e9:$Z,K=F1(t1($,Q),Y);return await g$(K,X),{path:Y,sha256:c1(X),bytes:X.length}}async function K5($,Z,X=process.cwd()){let Q=Z==="staged"?RY($,X):TY($,X);return await u$(Q)}async function c$($,Z=process.cwd()){try{let X=QZ($,Z),Q=await u$(X,"utf-8");return JSON.parse(Q)}catch{return{entries:[]}}}async function UZ($,Z,X=process.cwd()){await w0($,X);let Q=QZ($,X);await x0(zY(Q),{recursive:!0}),await g$(Q,JSON.stringify(Z,null,2),"utf-8")}async function VZ($,Z,X=process.cwd()){await w0($,X);let Q=c1(Z),Y=KZ($,Q,X);return await g$(Y,Z),Q}async function JZ($,Z,X=process.cwd()){let Q=KZ($,Z,X);return await u$(Q)}function BZ($){return{snapshotId:$.snapshotId,label:$.label,createdAt:$.createdAt,headSha:$.git.headSha,branch:$.git.branch,filesChanged:$.analysis.facts.stats.filesChanged,riskScore:$.analysis.riskReport.riskScore,flagCount:$.analysis.riskReport.flags.length,findingCount:$.analysis.facts.findings.length}}function q5(){return new Date().toISOString().replace(/[:.]/g,"-")}function GZ(){return`auto/pre-restore/${q5()}`}var LY=".branch-narrator",jY="snapshots",DY="index.json",NY="snapshot.json",e9="staged.patch",$Z="unstaged.patch",Z5="untracked",X5="manifest.json",AY="blobs";var U$=()=>{};import{execa as e1}from"execa";import{readFile as wY,stat as IY,chmod as bY,unlink as RB,readdir as TB,rmdir as xB}from"node:fs/promises";import{join as W5,dirname as PY}from"node:path";async function T$($=process.cwd()){try{return(await e1("git",["rev-parse","HEAD"],{cwd:$})).stdout.trim()}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new W1("git rev-parse HEAD",String(Z.stderr));throw Z}}async function I0($=process.cwd()){try{let X=(await e1("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:$})).stdout.trim();return X==="HEAD"?"":X}catch{return""}}async function x$($=process.cwd()){try{let Z=await e1("git",["diff","--binary","--staged"],{cwd:$,maxBuffer:104857600});return Buffer.from(Z.stdout,"utf-8")}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new W1("git diff --binary --staged",String(Z.stderr));throw Z}}async function E$($=process.cwd()){try{let Z=await e1("git",["diff","--binary"],{cwd:$,maxBuffer:104857600});return Buffer.from(Z.stdout,"utf-8")}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new W1("git diff --binary",String(Z.stderr));throw Z}}async function b0($,Z={},X=process.cwd()){if($.length===0)return;let Q=["apply"];if(Z.cached)Q.push("--cached");if(Z.check)Q.push("--check");Q.push("-");try{await e1("git",Q,{cwd:X,input:$})}catch(Y){if(Y instanceof Error&&"stderr"in Y)throw new W1(`git ${Q.join(" ")}`,String(Y.stderr));throw Y}}async function P0($=process.cwd()){try{let X=(await e1("git",["ls-files","--others","--exclude-standard","-z"],{cwd:$})).stdout;if(!X)return[];return X.split("\x00").filter(Boolean)}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new W1("git ls-files --others --exclude-standard -z",String(Z.stderr));throw Z}}async function OZ($,Z=process.cwd()){let X=W5(Z,$);return await wY(X)}async function MZ($,Z=process.cwd()){let X=W5(Z,$);return(await IY(X)).mode}async function _Z($=process.cwd()){try{await e1("git",["reset","--hard","HEAD"],{cwd:$})}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new W1("git reset --hard HEAD",String(Z.stderr));throw Z}}async function HZ($=process.cwd()){try{await e1("git",["clean","-fd","--exclude=.branch-narrator"],{cwd:$})}catch(Z){if(Z instanceof Error&&"stderr"in Z)throw new W1("git clean -fd --exclude=.branch-narrator",String(Z.stderr));throw Z}}async function zZ($,Z,X,Q=process.cwd()){let{writeFile:Y,mkdir:K}=await import("node:fs/promises"),W=W5(Q,$);await K(PY(W),{recursive:!0}),await Y(W,Z),await bY(W,X)}var C0=T(()=>{x1()});import{writeFile as CY,mkdir as SY}from"node:fs/promises";import{dirname as kY}from"node:path";async function S0($={}){let Z=$.cwd??process.cwd(),X=$.label??`snapshot-${q5()}`,[Q,Y]=await Promise.all([T$(Z),I0(Z)]),[K,W]=await Promise.all([x$(Z),E$(Z)]),q=await P0(Z),V={entries:[]},U=new Map,J=0;for(let V1 of q)try{let D=await OZ(V1,Z),C=await MZ(V1,Z),H1=c1(D),g1={path:V1,blobSha256:H1,mode:C,bytes:D.length};V.entries.push(g1),U.set(H1,D),J+=D.length}catch{continue}V.entries.sort((V1,D)=>V1.path.localeCompare(D.path));let B=c1(K),G=c1(W),M=JSON.stringify(V),_=E0(Q,B,G,M),O=await i1({mode:"all",cwd:Z,includeUntracked:!0}),[H,z]=await Promise.all([M$(Z),_$(Z)]),N="auto",j=y$(O,Z),E=j.profile,x=h1(E),R=await v1(x.analyzers,O),b=D$(R),w=await N$({changeSet:O,findings:R,riskScore:b,requestedProfile:N,detectedProfile:E,profileConfidence:j.confidence,profileReasons:j.reasons,filters:{excludes:[],includes:[],redact:!1,maxFileBytes:1048576,maxDiffBytes:5242880},skippedFiles:[],warnings:[],noTimestamp:!0,repoRoot:H,isDirty:z,mode:"all"}),p=await A$(O,{noTimestamp:!0,mode:"all",cwd:Z}),P=await a$(),N1=new Date().toISOString(),U1={schemaVersion:"1.0",snapshotId:_,label:X,createdAt:N1,tool:{name:"branch-narrator",version:P},git:{headSha:Q,branch:Y},workspace:{patches:{staged:{path:"staged.patch",sha256:B,bytes:K.length},unstaged:{path:"unstaged.patch",sha256:G,bytes:W.length}},untracked:{manifestPath:`${Z5}/${X5}`,fileCount:V.entries.length,totalBytes:J}},analysis:{facts:w,riskReport:p}};await Y5(_,"staged",K,Z),await Y5(_,"unstaged",W,Z),await UZ(_,V,Z);for(let[,V1]of U)await VZ(_,V1,Z);await WZ(_,U1,Z);let A1=BZ(U1);await qZ(A1,Z);let a1={snapshotId:_,label:X,snapshotPath:`.branch-narrator/snapshots/${_}`};if($.out)await SY(kY($.out),{recursive:!0}),await CY($.out,_,"utf-8");return a1}var U5=T(()=>{U$();C0();s$();H$();m$();z0();N0();H$()});async function LZ($={}){let Z=$.cwd??process.cwd(),X=await l$(Z);return X.snapshots.sort((Q,Y)=>Y.createdAt.localeCompare(Q.createdAt)),X}function jZ($,Z=!1){return Z?JSON.stringify($,null,2):JSON.stringify($)}var DZ=T(()=>{U$()});async function NZ($,Z={}){let X=Z.cwd??process.cwd();if(!await p1($,X))throw new r1($);return await d1($,X)}function AZ($,Z=!1){return Z?JSON.stringify($,null,2):JSON.stringify($)}var r1;var k0=T(()=>{U$();x1();r1=class r1 extends y{constructor($){super(`Snapshot not found: ${$}`,1);this.name="SnapshotNotFoundError"}}});async function RZ($,Z,X={}){let Q=X.cwd??process.cwd();if(!await p1($,Q))throw new r1($);if(!await p1(Z,Q))throw new r1(Z);let[Y,K]=await Promise.all([d1($,Q),d1(Z,Q)]),[W,q]=await Promise.all([c$($,Q),c$(Z,Q)]),V=FY(Y.analysis.facts.findings,K.analysis.facts.findings),U=vY(Y.analysis.riskReport.flags,K.analysis.riskReport.flags),J=yY(Y,K,W.entries,q.entries);return{schemaVersion:"1.0",from:$,to:Z,delta:{riskScore:{from:Y.analysis.riskReport.riskScore,to:K.analysis.riskReport.riskScore,delta:K.analysis.riskReport.riskScore-Y.analysis.riskReport.riskScore},findings:V,flags:U,files:J},summary:{findingsAdded:V.added.length,findingsRemoved:V.removed.length,findingsChanged:V.changed.length,flagsAdded:U.added.length,flagsRemoved:U.removed.length,flagsChanged:U.changed.length,filesAdded:J.added.length,filesRemoved:J.removed.length,filesModified:J.modified.length}}}function FY($,Z){let X=new Map,Q=new Map;for(let q of $)if(q.findingId)X.set(q.findingId,q);for(let q of Z)if(q.findingId)Q.set(q.findingId,q);let Y=[],K=[],W=[];for(let q of X.keys())if(!Q.has(q))K.push(q);for(let[q,V]of Q){let U=X.get(q);if(!U)Y.push(q);else if(!F0(U,V))W.push({findingId:q,before:U,after:V})}return Y.sort(),K.sort(),W.sort((q,V)=>q.findingId.localeCompare(V.findingId)),{added:Y,removed:K,changed:W}}function vY($,Z){let X=new Map,Q=new Map;for(let q of $)if(q.flagId)X.set(q.flagId,q);for(let q of Z)if(q.flagId)Q.set(q.flagId,q);let Y=[],K=[],W=[];for(let q of X.keys())if(!Q.has(q))K.push(q);for(let[q,V]of Q){let U=X.get(q);if(!U)Y.push(q);else if(!F0(U,V))W.push({flagId:q,before:U,after:V})}return Y.sort(),K.sort(),W.sort((q,V)=>q.flagId.localeCompare(V.flagId)),{added:Y,removed:K,changed:W}}function yY($,Z,X,Q){let Y=new Set,K=new Set,W=new Map,q=new Map,V=$.analysis.facts.changeset,U=Z.analysis.facts.changeset;for(let M of V.files.added)Y.add(M),W.set(M,"added");for(let M of V.files.modified)Y.add(M),W.set(M,"modified");for(let M of V.files.deleted)Y.add(M),W.set(M,"deleted");for(let{from:M,to:_}of V.files.renamed)Y.add(M),Y.add(_),W.set(M,`renamed:${_}`);for(let M of U.files.added)K.add(M),q.set(M,"added");for(let M of U.files.modified)K.add(M),q.set(M,"modified");for(let M of U.files.deleted)K.add(M),q.set(M,"deleted");for(let{from:M,to:_}of U.files.renamed)K.add(M),K.add(_),q.set(M,`renamed:${_}`);for(let M of X)Y.add(M.path),W.set(M.path,M.blobSha256);for(let M of Q)K.add(M.path),q.set(M.path,M.blobSha256);let J=[],B=[],G=[];for(let M of Y)if(!K.has(M))B.push(M);for(let M of K)if(!Y.has(M))J.push(M);else{let _=W.get(M),O=q.get(M);if(_!==O)G.push(M)}return J.sort(),B.sort(),G.sort(),{added:J,removed:B,modified:G}}function F0($,Z){if($===Z)return!0;if($===null||Z===null)return!1;if(typeof $!=="object"||typeof Z!=="object")return!1;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let Y=0;Y<$.length;Y++)if(!F0($[Y],Z[Y]))return!1;return!0}if(Array.isArray($)||Array.isArray(Z))return!1;let X=Object.keys($).sort(),Q=Object.keys(Z).sort();if(X.length!==Q.length)return!1;if(!X.every((Y,K)=>Y===Q[K]))return!1;for(let Y of X)if(!F0($[Y],Z[Y]))return!1;return!0}function TZ($,Z=!1){return Z?JSON.stringify($,null,2):JSON.stringify($)}var xZ=T(()=>{U$();k0()});async function EZ($,Z={}){let X=Z.cwd??process.cwd();if(!await p1($,X))throw new r1($);let Q=await d1($,X),Y=await T$(X);if(Y!==Q.git.headSha)throw new v0(Q.git.headSha,Y);let K=GZ(),W=await S0({label:K,cwd:X});await _Z(X),await HZ(X);let q=await K5($,"staged",X);if(q.length>0)try{await b0(q,{cached:!0},X),await b0(q,{},X)}catch(B){throw new p$("staged",B instanceof Error?B.message:String(B))}let V=await K5($,"unstaged",X);if(V.length>0)try{await b0(V,{},X)}catch(B){throw new p$("unstaged",B instanceof Error?B.message:String(B))}let U=await c$($,X);for(let B of U.entries){let G=await JZ($,B.blobSha256,X);await zZ(B.path,G,B.mode,X)}let J=await mY(Q,X);return{snapshotId:$,backupSnapshotId:W.snapshotId,success:!0,verified:J}}async function mY($,Z){try{let[X,Q]=await Promise.all([x$(Z),E$(Z)]),Y=c1(X),K=c1(Q),W=Y===$.workspace.patches.staged.sha256,q=K===$.workspace.patches.unstaged.sha256;return W&&q}catch{return!1}}var v0,p$,V5;var wZ=T(()=>{U$();C0();U5();k0();x1();v0=class v0 extends y{constructor($,Z){super(`HEAD mismatch: snapshot was created at ${$.slice(0,8)} but current HEAD is ${Z.slice(0,8)}. Snapshots can only be restored when HEAD matches the original commit.`,1);this.name="HeadMismatchError"}};p$=class p$ extends y{constructor($,Z){super(`Failed to apply ${$} patch: ${Z}`,1);this.name="PatchApplicationError"}};V5=class V5 extends y{constructor($){super(`Restore verification failed: ${$}`,1);this.name="RestoreVerificationError"}}});var w$={};P1(w$,{snapshotExists:()=>p1,renderSnapShowJSON:()=>AZ,renderSnapListJSON:()=>jZ,renderSnapDiffJSON:()=>TZ,readSnapshotJson:()=>d1,readIndex:()=>l$,getUntrackedFiles:()=>P0,getUnstagedPatch:()=>E$,getStagedPatch:()=>x$,getSnapshotsDir:()=>f$,getSnapshotDir:()=>t1,getHeadSha:()=>T$,getCurrentBranch:()=>I0,executeSnapShow:()=>NZ,executeSnapSave:()=>S0,executeSnapRestore:()=>EZ,executeSnapList:()=>LZ,executeSnapDiff:()=>RZ,computeSnapshotId:()=>E0,SnapshotNotFoundError:()=>r1,RestoreVerificationError:()=>V5,PatchApplicationError:()=>p$,HeadMismatchError:()=>v0});var I$=T(()=>{U$();C0();U5();DZ();k0();xZ();wZ()});x1();s$();import{Command as hY}from"commander";import{createInterface as uY}from"readline";import gY from"ora";import fY from"chalk";x1();import{mkdir as L5,writeFile as j5}from"node:fs/promises";import{dirname as rZ,join as aZ}from"node:path";var S1={quiet:!1,debug:!1};function B5($){if($.quiet)S1.quiet=!0,S1.debug=!1;else S1.quiet=!1,S1.debug=$.debug??!1}function nY(){return{...S1}}function tY(){S1.quiet=!1,S1.debug=!1}function J$($){if(!S1.quiet)console.error($)}function l($){if(!S1.quiet)console.error($)}function eY($){if(!S1.quiet&&S1.debug)console.error(`[DEBUG] ${$}`)}function c($){console.error($)}import fZ from"picomatch";var X$=["**/pnpm-lock.yaml","**/package-lock.json","**/yarn.lock","**/bun.lock","**/bun.lockb","**/*.d.ts","**/*.log","**/*.logs","**/dist/**","**/build/**","**/.svelte-kit/**","**/.next/**","**/.turbo/**","**/coverage/**","**/.cache/**","**/*.min.*","**/*.map"];function f0($){let Z=["diff","--name-status","--find-renames"];switch($.mode){case"branch":Z.push(`${$.base}..${$.head}`);break;case"unstaged":break;case"staged":Z.push("--staged");break;case"all":Z.push("HEAD");break}return Z}function l0($){let Z=["diff",`--unified=${$.unified}`,"--find-renames"];switch($.mode){case"branch":Z.push(`${$.base}..${$.head}`);break;case"unstaged":break;case"staged":Z.push("--staged");break;case"all":Z.push("HEAD");break}if(Z.push("--"),$.oldPath)Z.push($.oldPath);return Z.push($.path),Z}function c0($,Z){return["diff","--no-index",`--unified=${Z}`,"--","/dev/null",$]}function p0($){if(!$)return[];return $.split("\x00").filter(Boolean)}function g0($){if($.length===0)return()=>!1;let Z=$.map((X)=>fZ(X,{dot:!0}));return(X)=>Z.some((Q)=>Q(X))}function B$($){let{files:Z,includeGlobs:X,excludeGlobs:Q,defaultExcludes:Y}=$,K=g0(X),W=g0(Q),q=g0(Y),V=X.length>0,U=[],J=[];for(let B of Z){let G=B.path;if(W(G)){J.push({path:G,reason:"excluded-by-glob"});continue}if(V){if(!K(G)){J.push({path:G,reason:"not-included"});continue}U.push(B);continue}if(q(G)){J.push({path:G,reason:"excluded-by-default"});continue}U.push(B)}return U.sort((B,G)=>B.path.localeCompare(G.path)),{included:U,skipped:J}}function d0($,Z){if($.length===0)return[];let X=[],Q=[],Y=0;for(let K of $){let W=K.diff.length;if(W>Z){if(Q.length>0)X.push(Q),Q=[],Y=0;X.push([K]);continue}if(Y+W>Z&&Q.length>0)X.push(Q),Q=[],Y=0;Q.push(K),Y+=W}if(Q.length>0)X.push(Q);return X}function o$($){return $.map((Z)=>Z.diff).join(`
|
|
278
|
+
`)}function lZ($){switch($.mode){case"branch":return`Git Diff: ${$.base}..${$.head}`;case"unstaged":return"Git Diff: Unstaged Changes (working tree vs index)";case"staged":return"Git Diff: Staged Changes (index vs HEAD)";case"all":return"Git Diff: All Changes (working tree vs HEAD)"}}function i$($,Z){let X=[];if(X.push(`# ${lZ(Z)}`),X.push(""),X.push(`**Mode:** ${Z.mode}`),X.push(`**Unified context:** ${Z.unified} lines`),Z.excludePatterns.length>0)X.push(`**Excluded patterns:** ${Z.excludePatterns.join(", ")}`);X.push(`**Files included:** ${$.length}`),X.push(""),X.push("## Files"),X.push("");for(let Q of $){let Y=cZ(Q.status),K=Q.untracked?" [untracked]":"";X.push(`- \`${Q.path}\` (${Y}${K})`)}return X.push(""),X.push("## Diff"),X.push(""),X.push("```diff"),X.push($.map((Q)=>Q.diff).join(`
|
|
279
|
+
`)),X.push("```"),X.join(`
|
|
280
|
+
`)}function cZ($){switch($){case"A":return"added";case"M":return"modified";case"D":return"deleted";case"R":return"renamed";case"C":return"copied";case"T":return"type-changed";case"U":return"unmerged";case"?":return"untracked";case"unknown":return"unknown";default:return"unknown"}}function n$($){return $.reduce((Z,X)=>Z+X.diff.length,0)}function G5($){let Z=$.match(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(!Z)return null;return{oldStart:parseInt(Z[1],10),oldLines:Z[2]?parseInt(Z[2],10):1,newStart:parseInt(Z[3],10),newLines:Z[4]?parseInt(Z[4],10):1}}function r0($){if(!$.trim())return[];let Z=$.split(`
|
|
281
|
+
`),X=[],Q=null;for(let Y of Z)if(Y.startsWith("@@")){if(Q)X.push(Q);let K=G5(Y);Q={header:Y,oldStart:K?.oldStart,oldLines:K?.oldLines,newStart:K?.newStart,newLines:K?.newLines,lines:[]}}else if(Q){if(Y.startsWith("\\"))continue;let K;if(Y.startsWith("+"))K="add";else if(Y.startsWith("-"))K="del";else K="context";Q.lines.push({kind:K,text:Y})}if(Q)X.push(Q);return X}function pZ($){let Z=[];if(Z.push("--mode",$.mode),$.mode==="branch"){if($.base)Z.push("--base",$.base);if($.head)Z.push("--head",$.head)}if(Z.push("--format","json"),$.unified!==0)Z.push("--unified",String($.unified));for(let X of $.include)Z.push("--include",X);for(let X of $.exclude)Z.push("--exclude",X);if(!$.includeUntracked)Z.push("--no-untracked");if($.nameOnly)Z.push("--name-only");if($.stat)Z.push("--stat");if($.patchFor)Z.push("--patch-for",$.patchFor);return Z}function s1($,Z,X,Q){let Y={schemaVersion:"2.0",generatedAt:$.noTimestamp?void 0:new Date().toISOString(),command:{name:"dump-diff",args:pZ($)},git:{mode:$.mode,base:$.mode==="branch"?$.base??null:null,head:$.mode==="branch"?$.head??null:null,isDirty:$.mode!=="branch"},options:{unified:$.unified,include:$.include,exclude:$.exclude,includeUntracked:$.includeUntracked,nameOnly:$.nameOnly,stat:$.stat,patchFor:$.patchFor},files:Z,skippedFiles:X,summary:{changedFileCount:Q,includedFileCount:Z.length,skippedFileCount:X.length}};if(Y.generatedAt===void 0)delete Y.generatedAt;return Y}function o1($,Z=!1){return Z?JSON.stringify($,null,2):JSON.stringify($)}function O5($){if(!$.trim())return[];let Z=[],X=$.split(`
|
|
282
|
+
`),Q=null,Y,K=[],W=()=>{if(Q&&K.length>0)Z.push({path:Q,oldPath:Y,diffText:K.join(`
|
|
283
|
+
`)});Q=null,Y=void 0,K=[]};for(let q=0;q<X.length;q++){let V=X[q];if(V.startsWith("diff --git ")){W();let U=V.match(/^diff --git a\/(.+) b\/(.+)$/);if(U){Q=U[2];let B=q+1;while(B<X.length&&!X[B].startsWith("diff --git ")){let G=X[B];if(G.startsWith("rename from ")){Y=G.substring(12);break}if(G.startsWith("@@"))break;B++}}K.push(V)}else if(Q)K.push(V)}return W(),Z}async function t$($,Z=4){if($.length===0)return[];let X=Array($.length),Q=0,Y=0;return new Promise((K,W)=>{let q=()=>{if(Q>=$.length&&Y===0){K(X);return}while(Y<Z&&Q<$.length){let V=Q++,U=$[V];Y++,U().then((J)=>{X[V]=J,Y--,q()}).catch(W)}};q()})}x1();import{execa as y1}from"execa";async function dZ($=process.cwd()){try{let Z=await y1("git",["rev-parse","--is-inside-work-tree"],{cwd:$,reject:!1});return Z.exitCode===0&&Z.stdout.trim()==="true"}catch{return!1}}async function M5($,Z=process.cwd()){try{return(await y1("git",["rev-parse","--verify",$],{cwd:Z,reject:!1})).exitCode===0}catch{return!1}}function _5($){if(!$.trim())return[];let Z=[],X=$.trim().split(`
|
|
284
|
+
`);for(let Q of X){if(!Q.trim())continue;let Y=Q.split("\t"),K=Y[0]?.charAt(0);if(K==="R"&&Y.length>=3)Z.push({path:Y[2],oldPath:Y[1],status:"R"});else if(Y.length>=2)Z.push({path:Y[1],status:K})}return Z}async function P$($){let Z=$.cwd??process.cwd();if(!await dZ(Z))throw new V$(Z);if($.mode==="branch"){if(!$.base||!await M5($.base,Z))throw new T1($.base??"undefined");if(!$.head||!await M5($.head,Z))throw new T1($.head??"undefined")}let X=f0({mode:$.mode,base:$.base,head:$.head});try{let Q=await y1("git",X,{cwd:Z});return _5(Q.stdout)}catch(Q){if(Q instanceof Error&&"stderr"in Q)throw new W1(`git ${X.join(" ")}`,String(Q.stderr));throw Q}}async function e$($){let Z=$.cwd??process.cwd(),X=$.unified??0,Q=l0({mode:$.mode,base:$.base,head:$.head,unified:X,path:$.path,oldPath:$.oldPath});try{return(await y1("git",Q,{cwd:Z})).stdout}catch(Y){if(Y instanceof Error&&"stderr"in Y)throw new W1(`git ${Q.join(" ")}`,String(Y.stderr));throw Y}}async function H5($){let Z=$.cwd??process.cwd(),X=["diff","--numstat","--find-renames"];switch($.mode){case"branch":X.push(`${$.base}..${$.head}`);break;case"unstaged":break;case"staged":X.push("--staged");break;case"all":X.push("HEAD");break}X.push("--",$.path);try{let Y=(await y1("git",X,{cwd:Z,reject:!1})).stdout.trim();if(!Y)return!1;let K=Y.split("\t");return K[0]==="-"&&K[1]==="-"}catch{return!1}}async function C$($=process.cwd()){try{let Z=await y1("git",["ls-files","--others","--exclude-standard","-z"],{cwd:$});return p0(Z.stdout)}catch{return[]}}async function a0($,Z=0,X=process.cwd()){let Q=c0($,Z);try{return(await y1("git",Q,{cwd:X,reject:!1})).stdout}catch{return""}}async function $0($,Z=process.cwd()){try{return(await y1("git",["diff","--no-index","--","/dev/null",$],{cwd:Z,reject:!1})).stdout.includes("Binary files")}catch{return!1}}async function s0($){let Z=$.cwd??process.cwd(),X=$.unified??0;if($.paths.length===0)return"";let Q=["diff",`--unified=${X}`,"--find-renames"];switch($.mode){case"branch":Q.push(`${$.base}..${$.head}`);break;case"unstaged":break;case"staged":Q.push("--staged");break;case"all":Q.push("HEAD");break}Q.push("--",...$.paths);try{return(await y1("git",Q,{cwd:Z})).stdout}catch(Y){if(Y instanceof Error&&"stderr"in Y)throw new W1(`git ${Q.join(" ")}`,String(Y.stderr));throw Y}}async function S$($){let Z=$.cwd??process.cwd(),X=["diff","--numstat","--find-renames"];switch($.mode){case"branch":X.push(`${$.base}..${$.head}`);break;case"unstaged":break;case"staged":X.push("--staged");break;case"all":X.push("HEAD");break}try{let Q=await y1("git",X,{cwd:Z});return z5(Q.stdout)}catch(Q){if(Q instanceof Error&&"stderr"in Q)throw new W1(`git ${X.join(" ")}`,String(Q.stderr));throw Q}}function z5($){let Z=new Map;if(!$.trim())return Z;let X=$.trim().split(`
|
|
285
|
+
`);for(let Q of X){if(!Q.trim())continue;let Y=Q.split("\t");if(Y.length<3)continue;let K=Y[0],W=Y[1],q=K==="-"&&W==="-",V=Y.length>=4,U,J;if(V)J=Y[2],U=Y[3];else U=Y[2];let B={path:U,oldPath:J,added:q?0:parseInt(K,10),removed:q?0:parseInt(W,10),binary:q};Z.set(U,B)}return Z}var o0=8;async function D5($){let Z=$.cwd??process.cwd();if($.mode!=="branch"){let X=$.base!=="main",Q=$.head!=="HEAD";if(X||Q)J$(`Warning: --base and --head are ignored when --mode is "${$.mode}"`)}if($.patchFor){await nZ($,Z);return}if($.nameOnly){await oZ($,Z);return}if($.stat){await iZ($,Z);return}await sZ($,Z)}async function sZ($,Z){let X=await P$({mode:$.mode,base:$.base,head:$.head,cwd:Z}),Q=[];if($.includeUntracked&&$.mode!=="branch")Q=(await C$(Z)).map((N)=>({path:N,status:"A",untracked:!0}));let Y=[...X,...Q];if(Y.length===0){if($.format==="json"){let z=s1({mode:$.mode,base:$.base,head:$.head,unified:$.unified,include:$.include,exclude:$.exclude,includeUntracked:$.includeUntracked,nameOnly:!1,stat:!1,patchFor:null,noTimestamp:$.noTimestamp??!1},[],[],0),N=o1(z,$.pretty);if($.out)await R1($.out,N),l(`Wrote JSON output to ${$.out}`);else console.log(N);return}console.log("No changes found.");return}let{included:K,skipped:W}=B$({files:Y,includeGlobs:$.include,excludeGlobs:$.exclude,defaultExcludes:X$}),q=[],V=[],U=K.filter((z)=>!z.untracked),J=K.filter((z)=>z.untracked),B=new Map;if(U.length>0)B=await S$({mode:$.mode,base:$.base,head:$.head,cwd:Z});for(let z of U)if(B.get(z.path)?.binary)V.push({path:z.path,reason:"binary"});else q.push(z);if(J.length>0){let z=J.map((j)=>async()=>{let E=await $0(j.path,Z);return{file:j,isBinary:E}}),N=await t$(z,o0);for(let{file:j,isBinary:E}of N)if(E)V.push({path:j.path,reason:"binary"});else q.push(j)}let G=[...W,...V];if($.dryRun){await eZ($,q,G,Z);return}let M=await tZ($,q,Z),_=[],O=[];for(let z of M)if(z.diff.trim()==="")O.push({path:z.path,reason:"diff-empty"});else _.push(z);let H=[...G,...O];if($.format==="json"){let z=n$(_);if($.maxChars!==void 0&&z>$.maxChars)throw new y(`JSON output (${z.toLocaleString()} chars) exceeds --max-chars (${$.maxChars.toLocaleString()}). JSON format does not support chunking. Use --format text or --format md for chunked output, or increase --max-chars.`,1);let N=_.map((R)=>({path:R.path,oldPath:R.oldPath,status:R.status,untracked:R.untracked,patch:{text:R.diff}})),j=H.map((R)=>({path:R.path,status:R.status,reason:R.reason,note:R.note})),E=s1({mode:$.mode,base:$.base,head:$.head,unified:$.unified,include:$.include,exclude:$.exclude,includeUntracked:$.includeUntracked,nameOnly:!1,stat:!1,patchFor:null,noTimestamp:$.noTimestamp??!1},N,j,Y.length),x=o1(E,$.pretty);if($.out)await R1($.out,x),l(`Wrote JSON output to ${$.out}`);else console.log(x)}else await $4($,_,H,Y.length,Z)}async function oZ($,Z){let X=await P$({mode:$.mode,base:$.base,head:$.head,cwd:Z}),Q=[];if($.includeUntracked&&$.mode!=="branch")Q=(await C$(Z)).map((_)=>({path:_,status:"A",untracked:!0}));let Y=[...X,...Q],{included:K,skipped:W}=B$({files:Y,includeGlobs:$.include,excludeGlobs:$.exclude,defaultExcludes:X$}),q=K.filter((M)=>!M.untracked),V=K.filter((M)=>M.untracked),U=new Map;if(q.length>0)U=await S$({mode:$.mode,base:$.base,head:$.head,cwd:Z});for(let M of q)if(U.get(M.path)?.binary)W.push({path:M.path,status:M.status,reason:"binary"});if(V.length>0){let M=V.map((O)=>async()=>{let H=await $0(O.path,Z);return{file:O,isBinary:H}}),_=await t$(M,o0);for(let{file:O,isBinary:H}of _)if(H)W.push({path:O.path,status:O.status,reason:"binary"})}let B=K.filter((M)=>{return!W.some((_)=>_.path===M.path&&_.reason==="binary")}).sort((M,_)=>M.path.localeCompare(_.path)),G=W.sort((M,_)=>M.path.localeCompare(_.path));if($.format==="json"){let M=B.map((z)=>({path:z.path,oldPath:z.oldPath,status:z.status,untracked:z.untracked})),_=G.map((z)=>({path:z.path,status:z.status,reason:z.reason,note:z.note})),O=s1({mode:$.mode,base:$.base,head:$.head,unified:$.unified,include:$.include,exclude:$.exclude,includeUntracked:$.includeUntracked,nameOnly:!0,stat:!1,patchFor:null,noTimestamp:$.noTimestamp??!1},M,_,Y.length),H=o1(O,$.pretty);if($.out)await R1($.out,H),l(`Wrote JSON output to ${$.out}`);else console.log(H)}else if($.format==="md"){let M=[];M.push(`# Changed Files
|
|
286
|
+
`);for(let O of B)M.push(`- \`${O.path}\``);let _=M.join(`
|
|
287
|
+
`);if($.out)await R1($.out,_),l(`Wrote markdown output to ${$.out}`);else console.log(_)}else{let _=B.map((O)=>O.path).join(`
|
|
288
|
+
`);if($.out)await R1($.out,_),l(`Wrote text output to ${$.out}`);else console.log(_)}}async function iZ($,Z){let X=await P$({mode:$.mode,base:$.base,head:$.head,cwd:Z}),Q=[];if($.includeUntracked&&$.mode!=="branch")Q=(await C$(Z)).map((G)=>({path:G,status:"A",untracked:!0}));let Y=[...X,...Q],K=await S$({mode:$.mode,base:$.base,head:$.head,cwd:Z}),{included:W,skipped:q}=B$({files:Y,includeGlobs:$.include,excludeGlobs:$.exclude,defaultExcludes:X$});for(let B of W)if(K.get(B.path)?.binary)q.push({path:B.path,status:B.status,reason:"binary"});let U=W.filter((B)=>{return!K.get(B.path)?.binary}).map((B)=>{let G=K.get(B.path);return{path:B.path,oldPath:B.oldPath,status:B.status,stats:G?{added:G.added,removed:G.removed}:{added:0,removed:0}}}).sort((B,G)=>B.path.localeCompare(G.path)),J=q.sort((B,G)=>B.path.localeCompare(G.path));if($.format==="json"){let B=U.map((O)=>({path:O.path,oldPath:O.oldPath,status:O.status,stats:O.stats})),G=J.map((O)=>({path:O.path,status:O.status,reason:O.reason,note:O.note})),M=s1({mode:$.mode,base:$.base,head:$.head,unified:$.unified,include:$.include,exclude:$.exclude,includeUntracked:$.includeUntracked,nameOnly:!1,stat:!0,patchFor:null,noTimestamp:$.noTimestamp??!1},B,G,Y.length),_=o1(M,$.pretty);if($.out)await R1($.out,_),l(`Wrote JSON output to ${$.out}`);else console.log(_)}else if($.format==="md"){let B=[];B.push(`# File Statistics
|
|
285
289
|
`),B.push("| File | Added | Removed |"),B.push("| ---- | -----:| -------:|");for(let M of U)B.push(`| \`${M.path}\` | ${M.stats.added} | ${M.stats.removed} |`);let G=B.join(`
|
|
286
|
-
`);if($.out)await
|
|
287
|
-
`);if($.out)await
|
|
290
|
+
`);if($.out)await R1($.out,G),l(`Wrote markdown output to ${$.out}`);else console.log(G)}else{let G=U.map((M)=>`${M.stats.added} ${M.stats.removed} ${M.path}`).join(`
|
|
291
|
+
`);if($.out)await R1($.out,G),l(`Wrote text output to ${$.out}`);else console.log(G)}}async function nZ($,Z){if(!$.patchFor)throw new y("--patch-for requires a file path",1);let X=$.patchFor,Q=await P$({mode:$.mode,base:$.base,head:$.head,cwd:Z}),Y=[];if($.includeUntracked&&$.mode!=="branch")Y=(await C$(Z)).map((M)=>({path:M,status:"A",untracked:!0}));let W=[...Q,...Y].find((G)=>G.path===X||G.oldPath===X);if(!W)throw new y(`File not found in changes: ${X}. Run 'branch-narrator dump-diff --name-only' to see changed files.`,1);let{included:q,skipped:V}=B$({files:[W],includeGlobs:$.include,excludeGlobs:$.exclude,defaultExcludes:X$});if(q.length===0){let G=V[0]?.reason||"excluded";throw new y(`File is excluded: ${X} (reason: ${G}). Use --include "${X}" to include it.`,1)}let U;if(W.untracked)U=await $0(W.path,Z);else U=await H5({mode:$.mode,base:$.base,head:$.head,path:W.path,cwd:Z});if(U){if($.format==="json"){let G=[{path:W.path,status:W.status,reason:"binary"}],M=s1({mode:$.mode,base:$.base,head:$.head,unified:$.unified,include:$.include,exclude:$.exclude,includeUntracked:$.includeUntracked,nameOnly:!1,stat:!1,patchFor:X,noTimestamp:$.noTimestamp??!1},[],G,1),_=o1(M,$.pretty);if($.out)await R1($.out,_),l(`Wrote JSON output to ${$.out}`);else console.log(_)}else throw new y(`File is binary: ${X}`,1);return}let J;if(W.untracked)J=await a0(W.path,$.unified,Z);else J=await e$({mode:$.mode,base:$.base,head:$.head,path:W.path,oldPath:W.oldPath,unified:$.unified,cwd:Z});let B;if($.format==="json"){let M=(await S$({mode:$.mode,base:$.base,head:$.head,cwd:Z})).get(W.path);if(M&&!M.binary)B={added:M.added,removed:M.removed}}if($.format==="json"){let G=r0(J),M=[{path:W.path,oldPath:W.oldPath,status:W.status,untracked:W.untracked,stats:B,patch:{text:J,hunks:G}}],_=s1({mode:$.mode,base:$.base,head:$.head,unified:$.unified,include:$.include,exclude:$.exclude,includeUntracked:$.includeUntracked,nameOnly:!1,stat:!1,patchFor:X,noTimestamp:$.noTimestamp??!1},M,[],1),O=o1(_,$.pretty);if($.out)await R1($.out,O),l(`Wrote JSON output to ${$.out}`);else console.log(O)}else if($.format==="md"){let G=[];G.push(`# Diff for \`${W.path}\`
|
|
288
292
|
`),G.push("```diff"),G.push(J),G.push("```");let M=G.join(`
|
|
289
|
-
`);if($.out)await
|
|
290
|
-
`),console.log(`Mode: ${$.mode}`),$.mode==="branch")console.log(`Base: ${$.base}`),console.log(`Head: ${$.head}`);console.log(`Format: ${$.format}`),console.log(`Unified context: ${$.unified} lines`),console.log(`Include untracked: ${$.includeUntracked}`),console.log(""),console.log(`Files included (${Z.length}):`);for(let W of Z){let q=
|
|
291
|
-
Output would be written to: ${$.out}`);else if(
|
|
292
|
-
Chunks would be written to: ${$.chunkDir}/`)}async function
|
|
293
|
-
Total: ${V.length} chunks, ${Z.length} files, ${W.toLocaleString()} chars`)}else{let V;if($.format==="md")V=
|
|
293
|
+
`);if($.out)await R1($.out,M),l(`Wrote markdown output to ${$.out}`);else console.log(M)}else if($.out)await R1($.out,J),l(`Wrote text output to ${$.out}`);else console.log(J)}async function tZ($,Z,X){let Q=[],Y=Z.filter((W)=>!W.untracked),K=Z.filter((W)=>W.untracked);if(Y.length>0){let W=Y.map((q)=>q.path);try{let q=await s0({mode:$.mode,base:$.base,head:$.head,paths:W,unified:$.unified,cwd:X}),V=O5(q),U=new Map;for(let J of V)if(U.set(J.path,J.diffText),J.oldPath)U.set(J.oldPath,J.diffText);for(let J of Y){let B=U.get(J.path);if(!B||B.trim()==="")B=await e$({mode:$.mode,base:$.base,head:$.head,path:J.path,oldPath:J.oldPath,unified:$.unified,cwd:X});Q.push({path:J.path,oldPath:J.oldPath,status:J.status,diff:B||"",untracked:!1})}}catch(q){J$(`Batch diff failed, falling back to per-file diffs: ${q instanceof Error?q.message:String(q)}`);for(let V of Y){let U=await e$({mode:$.mode,base:$.base,head:$.head,path:V.path,oldPath:V.oldPath,unified:$.unified,cwd:X});Q.push({path:V.path,oldPath:V.oldPath,status:V.status,diff:U,untracked:!1})}}}if(K.length>0){let W=K.map((V)=>async()=>{let U=await a0(V.path,$.unified,X);return{path:V.path,oldPath:V.oldPath,status:V.status,diff:U,untracked:!0}}),q=await t$(W,o0);Q.push(...q)}return Q}async function eZ($,Z,X,Q){let Y=0;if(Z.length>0){let W=Z.filter((V)=>!V.untracked).map((V)=>V.path);if(W.length>0){let V=await s0({mode:$.mode,base:$.base,head:$.head,paths:W,unified:$.unified,cwd:Q});Y+=V.length}let q=Z.filter((V)=>V.untracked).length;if(q>0)Y+=q*500}let K=$.maxChars!==void 0&&Y>$.maxChars;if(console.log(`=== Dry Run ===
|
|
294
|
+
`),console.log(`Mode: ${$.mode}`),$.mode==="branch")console.log(`Base: ${$.base}`),console.log(`Head: ${$.head}`);console.log(`Format: ${$.format}`),console.log(`Unified context: ${$.unified} lines`),console.log(`Include untracked: ${$.includeUntracked}`),console.log(""),console.log(`Files included (${Z.length}):`);for(let W of Z){let q=Z4(W.status),V=W.untracked?" [untracked]":"";console.log(` ${q} ${W.path}${V}`)}console.log(""),console.log(`Files skipped (${X.length}):`);for(let W of X)console.log(` - ${W.path} (${W.reason})`);if(console.log(""),console.log(`Estimated output size: ${Y.toLocaleString()} chars`),$.maxChars!==void 0){if(console.log(`Max chars: ${$.maxChars.toLocaleString()}`),console.log(`Would chunk: ${K?"yes":"no"}`),K){let W=Math.ceil(Y/$.maxChars);console.log(`Estimated chunks: ~${W}`)}}if($.out)console.log(`
|
|
295
|
+
Output would be written to: ${$.out}`);else if(K)console.log(`
|
|
296
|
+
Chunks would be written to: ${$.chunkDir}/`)}async function $4($,Z,X,Q,Y){let K={mode:$.mode,base:$.mode==="branch"?$.base:null,head:$.mode==="branch"?$.head:null,unified:$.unified,excludePatterns:[...X$,...$.exclude]},W=n$(Z);if($.maxChars!==void 0&&W>$.maxChars){let V=d0(Z,$.maxChars),U=$.format==="md"?"md":"txt";await L5($.chunkDir,{recursive:!0});for(let J=0;J<V.length;J++){let B=V[J],G=String(J+1).padStart(3,"0"),M=`${$.name}-${G}.${U}`,_=aZ($.chunkDir,M),O;if($.format==="md"){let H={...K,base:$.mode==="branch"?`${$.base} (chunk ${J+1}/${V.length})`:null};O=i$(B,H)}else O=o$(B);await j5(_,O,"utf-8"),l(`Wrote chunk ${J+1}/${V.length} to ${_}`)}l(`
|
|
297
|
+
Total: ${V.length} chunks, ${Z.length} files, ${W.toLocaleString()} chars`)}else{let V;if($.format==="md")V=i$(Z,K);else V=o$(Z);if($.out)await R1($.out,V),l(`Wrote ${$.format} output to ${$.out}`);else console.log(V)}}async function R1($,Z){let X=rZ($);await L5(X,{recursive:!0}),await j5($,Z,"utf-8")}function Z4($){switch($){case"A":return"+";case"M":return"~";case"D":return"-";case"R":return"→";default:return"?"}}H$();m$();q0();Y0();Q2();G0();function s7($){let Z=new Map;for(let X of $){if(!Z.has(X.type))Z.set(X.type,[]);Z.get(X.type).push(X)}return Z}function o7($){if(!$.interactive?.context)return"";return`## Context
|
|
294
298
|
|
|
295
299
|
${$.interactive.context}
|
|
296
300
|
|
|
297
|
-
`}function
|
|
301
|
+
`}function i7($,Z){let X=[],Q=$.get("file-summary")?.[0];if(Q){let W=Q.added.length+Q.modified.length+Q.deleted.length+Q.renamed.length;if(X.push(`${W} file(s) changed`),Q.added.length>0)X.push(`${Q.added.length} file(s) added`);if(Q.deleted.length>0)X.push(`${Q.deleted.length} file(s) deleted`)}let Y=j$(Z);for(let W of Y)if(!W.includes("file(s) changed")&&!W.includes("file(s) with")&&!W.toLowerCase().includes("finding"))X.push(W);if(X.length===0)X.push("Minor changes detected");return`## Summary
|
|
298
302
|
|
|
299
|
-
`+
|
|
303
|
+
`+X.slice(0,8).map((W)=>`- ${W}`).join(`
|
|
300
304
|
`)+`
|
|
301
305
|
|
|
302
|
-
`}function
|
|
306
|
+
`}function n7($,Z){if(!$||!Z)return"";let{categories:X,summary:Q}=$;if(Q.length<=1)return"";let Y=`## What Changed
|
|
303
307
|
|
|
304
|
-
`,
|
|
308
|
+
`,K=Q.filter((W)=>W.count>0).sort((W,q)=>q.count-W.count);for(let{category:W,count:q}of K){let V=Q0(W),U=X[W];Y+=`### ${V} (${q})
|
|
305
309
|
|
|
306
|
-
`;let J=U.slice(0,10);for(let B of J){let G="";if(Z.added.includes(B))G=" *(new)*";else if(Z.deleted.includes(B))G=" *(deleted)*";
|
|
307
|
-
`}if(U.length>10)
|
|
308
|
-
`;
|
|
309
|
-
`}return
|
|
310
|
+
`;let J=U.slice(0,10);for(let B of J){let G="";if(Z.added.includes(B))G=" *(new)*";else if(Z.deleted.includes(B))G=" *(deleted)*";Y+=`- \`${B}\`${G}
|
|
311
|
+
`}if(U.length>10)Y+=`- *...and ${U.length-10} more*
|
|
312
|
+
`;Y+=`
|
|
313
|
+
`}return Y}function t7($){if($.length===0)return"";let Z=`## Routes / API
|
|
310
314
|
|
|
311
315
|
`;Z+=`| Route | Type | Change | Methods |
|
|
312
316
|
`,Z+=`|-------|------|--------|--------|
|
|
313
|
-
`;for(let
|
|
317
|
+
`;for(let X of $){let Q=n1(X.routeId),Y=X.methods?.join(", ")||"-";Z+=`| \`${Q}\` | ${X.routeType} | ${X.change} | ${Y} |
|
|
314
318
|
`}return Z+`
|
|
315
|
-
`}function
|
|
319
|
+
`}function e7($){if($.length===0)return"";let Z=`## API Contracts
|
|
316
320
|
|
|
317
321
|
`;Z+=`The following API specification files have changed:
|
|
318
322
|
|
|
319
|
-
`;for(let
|
|
323
|
+
`;for(let X of $)for(let Q of X.files)Z+=`- \`${Q}\`
|
|
320
324
|
`;return Z+=`
|
|
321
|
-
`,Z}function
|
|
325
|
+
`,Z}function $X($){if($.length===0)return"";let Z=`## Database (Supabase)
|
|
322
326
|
|
|
323
|
-
`;for(let
|
|
327
|
+
`;for(let X of $){let Q=X.risk==="high"?"\uD83D\uDD34":X.risk==="medium"?"\uD83D\uDFE1":"\uD83D\uDFE2";Z+=`**Risk Level:** ${Q} ${X.risk.toUpperCase()}
|
|
324
328
|
|
|
325
329
|
`,Z+=`**Files:**
|
|
326
|
-
`;for(let
|
|
330
|
+
`;for(let Y of X.files)Z+=`- \`${Y}\`
|
|
327
331
|
`;if(Z+=`
|
|
328
|
-
`,
|
|
329
|
-
`;for(let
|
|
332
|
+
`,X.reasons.length>0){Z+=`**Detected patterns:**
|
|
333
|
+
`;for(let Y of X.reasons)Z+=`- ${Y}
|
|
330
334
|
`;Z+=`
|
|
331
|
-
`}}return Z}function
|
|
335
|
+
`}}return Z}function ZX($){if($.length===0)return"";let Z=`## Config / Env
|
|
332
336
|
|
|
333
337
|
`;Z+=`| Variable | Status | Evidence |
|
|
334
338
|
`,Z+=`|----------|--------|----------|
|
|
335
|
-
`;for(let
|
|
339
|
+
`;for(let X of $){let Q=X.evidenceFiles.slice(0,2).join(", ");Z+=`| \`${X.name}\` | ${X.change} | ${Q} |
|
|
336
340
|
`}return Z+`
|
|
337
|
-
`}function
|
|
341
|
+
`}function XX($){if($.length===0)return"";let Z=`## Cloudflare
|
|
338
342
|
|
|
339
|
-
`;for(let
|
|
343
|
+
`;for(let X of $){Z+=`**Area:** ${X.area}
|
|
340
344
|
`,Z+=`**Files:**
|
|
341
|
-
`;for(let
|
|
345
|
+
`;for(let Q of X.files)Z+=`- \`${Q}\`
|
|
342
346
|
`;Z+=`
|
|
343
|
-
`}return Z}function
|
|
347
|
+
`}return Z}function QX($){if($.length===0)return"";let Z=$.filter((Y)=>Y.section==="dependencies"),X=$.filter((Y)=>Y.section==="devDependencies"),Q=`## Dependencies
|
|
344
348
|
|
|
345
|
-
`;if(Z.length>0){
|
|
349
|
+
`;if(Z.length>0){Q+=`### Production
|
|
346
350
|
|
|
347
|
-
`,
|
|
348
|
-
`,
|
|
349
|
-
`;for(let
|
|
350
|
-
`;
|
|
351
|
-
`}if(
|
|
351
|
+
`,Q+=`| Package | From | To | Impact |
|
|
352
|
+
`,Q+=`|---------|------|-----|--------|
|
|
353
|
+
`;for(let Y of Z)Q+=`| \`${Y.name}\` | ${Y.from??"-"} | ${Y.to??"-"} | ${Y.impact??"-"} |
|
|
354
|
+
`;Q+=`
|
|
355
|
+
`}if(X.length>0){Q+=`### Dev Dependencies
|
|
352
356
|
|
|
353
|
-
`,
|
|
354
|
-
`,
|
|
355
|
-
`;for(let
|
|
356
|
-
`;
|
|
357
|
-
`}return
|
|
357
|
+
`,Q+=`| Package | From | To | Impact |
|
|
358
|
+
`,Q+=`|---------|------|-----|--------|
|
|
359
|
+
`;for(let Y of X)Q+=`| \`${Y.name}\` | ${Y.from??"-"} | ${Y.to??"-"} | ${Y.impact??"-"} |
|
|
360
|
+
`;Q+=`
|
|
361
|
+
`}return Q}function YX($){if($.length===0)return"";let Z=`## \uD83D\uDD12 Security-Sensitive Files
|
|
358
362
|
|
|
359
|
-
|
|
363
|
+
`;Z+=`The following files touch authentication, authorization, or security-critical code:
|
|
360
364
|
|
|
361
|
-
`;for(let K of
|
|
362
|
-
|
|
365
|
+
`;let X=new Map;for(let Y of $)for(let K of Y.files){if(!X.has(K))X.set(K,[]);for(let W of Y.reasons)if(!X.get(K).includes(W))X.get(K).push(W)}let Q=[...X.entries()].sort((Y,K)=>Y[0].localeCompare(K[0]));for(let[Y,K]of Q.slice(0,10)){let W=K.map((q)=>X2(q)).join(", ");Z+=`- \`${Y}\` *(${W})*
|
|
366
|
+
`}if(Q.length>10)Z+=`- ...and ${Q.length-10} more
|
|
367
|
+
`;return Z+=`
|
|
368
|
+
`,Z}function KX($){if($.length===0)return"";let Z=`## GraphQL Schema
|
|
369
|
+
|
|
370
|
+
`,X=$.filter((Y)=>Y.isBreaking);if(X.length>0){Z+=`### \uD83D\uDD34 Breaking Changes
|
|
371
|
+
|
|
372
|
+
`;for(let Y of X){if(Z+=`**File:** \`${Y.file}\`
|
|
373
|
+
`,Y.breakingChanges.length>0)for(let K of Y.breakingChanges)Z+=`- ${K}
|
|
363
374
|
`;Z+=`
|
|
364
|
-
`}}let
|
|
375
|
+
`}}let Q=$.filter((Y)=>Y.addedElements.length>0);if(Q.length>0){Z+=`### Added Elements
|
|
365
376
|
|
|
366
|
-
`;for(let
|
|
367
|
-
`;for(let
|
|
368
|
-
`;if(
|
|
377
|
+
`;for(let Y of Q){Z+=`**File:** \`${Y.file}\`
|
|
378
|
+
`;for(let K of Y.addedElements.slice(0,10))Z+=`- ${K}
|
|
379
|
+
`;if(Y.addedElements.length>10)Z+=`- ...and ${Y.addedElements.length-10} more
|
|
369
380
|
`;Z+=`
|
|
370
381
|
`}}Z+=`### All Schema Changes
|
|
371
382
|
|
|
372
383
|
`,Z+=`| File | Status | Breaking |
|
|
373
384
|
`,Z+=`|------|--------|----------|
|
|
374
|
-
`;for(let
|
|
385
|
+
`;for(let Y of $){let K=Y.isBreaking?"\uD83D\uDD34 Yes":"\uD83D\uDFE2 No";Z+=`| \`${Y.file}\` | ${Y.status} | ${K} |
|
|
375
386
|
`}return Z+=`
|
|
376
|
-
`,Z}function
|
|
387
|
+
`,Z}function qX($){if($.length===0)return"";let Z=`### TypeScript Configuration
|
|
377
388
|
|
|
378
|
-
`;for(let
|
|
389
|
+
`;for(let X of $){let Q=X.isBreaking?"\uD83D\uDD34":"\uD83D\uDFE2";if(Z+=`**File:** \`${X.file}\` ${Q}
|
|
379
390
|
|
|
380
|
-
`,
|
|
381
|
-
`;for(let q of
|
|
391
|
+
`,X.strictnessChanges.length>0){Z+=`**Strictness Changes:**
|
|
392
|
+
`;for(let q of X.strictnessChanges)Z+=`- ${q}
|
|
382
393
|
`;Z+=`
|
|
383
|
-
`}let{added:
|
|
384
|
-
`;if(
|
|
394
|
+
`}let{added:Y,removed:K,modified:W}=X.changedOptions;if(Y.length>0)Z+=`**Added:** ${Y.map((q)=>`\`${q}\``).join(", ")}
|
|
395
|
+
`;if(K.length>0)Z+=`**Removed:** ${K.map((q)=>`\`${q}\``).join(", ")}
|
|
385
396
|
`;if(W.length>0)Z+=`**Modified:** ${W.map((q)=>`\`${q}\``).join(", ")}
|
|
386
397
|
`;Z+=`
|
|
387
|
-
`}return Z}function
|
|
398
|
+
`}return Z}function WX($){if($.length===0)return"";let Z=`### Tailwind Configuration
|
|
388
399
|
|
|
389
|
-
`;for(let
|
|
400
|
+
`;for(let X of $){let Q=X.isBreaking?"\uD83D\uDD34":"\uD83D\uDFE2";if(Z+=`**File:** \`${X.file}\` (${X.configType}) ${Q}
|
|
390
401
|
|
|
391
|
-
`,
|
|
392
|
-
`;for(let
|
|
402
|
+
`,X.affectedSections.length>0){Z+=`**Affected Sections:**
|
|
403
|
+
`;for(let Y of X.affectedSections)Z+=`- ${Y}
|
|
393
404
|
`;Z+=`
|
|
394
|
-
`}if(
|
|
395
|
-
`;for(let
|
|
405
|
+
`}if(X.isBreaking&&X.breakingReasons.length>0){Z+=`**Breaking Changes:**
|
|
406
|
+
`;for(let Y of X.breakingReasons)Z+=`- ${Y}
|
|
396
407
|
`;Z+=`
|
|
397
|
-
`}}return Z}function
|
|
408
|
+
`}}return Z}function UX($){if($.length===0)return"";let Z=`### Monorepo Configuration
|
|
398
409
|
|
|
399
|
-
`;for(let
|
|
400
|
-
`,Z+=`**File:** \`${
|
|
410
|
+
`;for(let X of $){if(Z+=`**Tool:** ${X.tool}
|
|
411
|
+
`,Z+=`**File:** \`${X.file}\`
|
|
401
412
|
|
|
402
|
-
`,
|
|
403
|
-
`;for(let
|
|
413
|
+
`,X.affectedFields.length>0){Z+=`**Changed Fields:**
|
|
414
|
+
`;for(let Q of X.affectedFields)Z+=`- ${Q}
|
|
404
415
|
`;Z+=`
|
|
405
|
-
`}if(
|
|
406
|
-
`;for(let
|
|
416
|
+
`}if(X.impacts.length>0){Z+=`**Impacts:**
|
|
417
|
+
`;for(let Q of X.impacts)Z+=`- ${Q}
|
|
407
418
|
`;Z+=`
|
|
408
|
-
`}}return Z}function
|
|
419
|
+
`}}return Z}function VX($){if($.length===0)return"";let Z=`### Vite Configuration
|
|
409
420
|
|
|
410
|
-
`;
|
|
421
|
+
`;for(let X of $){let Q=X.isBreaking?"\uD83D\uDD34":"\uD83D\uDFE2";if(Z+=`**File:** \`${X.file}\` ${Q}
|
|
411
422
|
|
|
412
|
-
|
|
423
|
+
`,X.pluginsDetected.length>0)Z+=`**Plugins:** ${X.pluginsDetected.map((Y)=>`\`${Y}\``).join(", ")}
|
|
424
|
+
`;if(X.affectedSections.length>0){Z+=`**Affected Sections:**
|
|
425
|
+
`;for(let Y of X.affectedSections.slice(0,5))Z+=`- ${Y}
|
|
426
|
+
`;if(X.affectedSections.length>5)Z+=`- ...and ${X.affectedSections.length-5} more
|
|
427
|
+
`;Z+=`
|
|
428
|
+
`}if(X.isBreaking&&X.breakingReasons.length>0){Z+=`**Breaking Changes:**
|
|
429
|
+
`;for(let Y of X.breakingReasons)Z+=`- ${Y}
|
|
430
|
+
`;Z+=`
|
|
431
|
+
`}}return Z}function JX($,Z,X,Q){let Y=$.length>0,K=Z.length>0,W=X.length>0,q=Q.length>0;if(!Y&&!K&&!W&&!q)return"";let V=`## Configuration Changes
|
|
413
432
|
|
|
414
|
-
|
|
433
|
+
`;if(Y)V+=qX($);if(K)V+=WX(Z);if(q)V+=VX(Q);if(W)V+=UX(X);return V}function BX($){if($.length===0)return"";let Z=`## Package API
|
|
415
434
|
|
|
416
|
-
`;for(let
|
|
435
|
+
`;for(let X of $){let Q=X.isBreaking?"\uD83D\uDD34 Breaking":"\uD83D\uDFE2 Non-breaking";if(Z+=`**Status:** ${Q}
|
|
436
|
+
|
|
437
|
+
`,X.removedExports.length>0){Z+=`### Removed Exports
|
|
438
|
+
|
|
439
|
+
`;for(let Y of X.removedExports)Z+=`- \uD83D\uDD34 \`${Y}\`
|
|
417
440
|
`;Z+=`
|
|
418
|
-
`}if(
|
|
441
|
+
`}if(X.addedExports.length>0){Z+=`### Added Exports
|
|
419
442
|
|
|
420
|
-
`;for(let
|
|
443
|
+
`;for(let Y of X.addedExports)Z+=`- \uD83D\uDFE2 \`${Y}\`
|
|
421
444
|
`;Z+=`
|
|
422
|
-
`}if(
|
|
445
|
+
`}if(X.legacyFieldChanges.length>0){Z+=`### Entry Point Changes
|
|
423
446
|
|
|
424
447
|
`,Z+=`| Field | From | To |
|
|
425
448
|
`,Z+=`|-------|------|----|
|
|
426
|
-
`;for(let
|
|
449
|
+
`;for(let Y of X.legacyFieldChanges)Z+=`| \`${Y.field}\` | ${Y.from??"-"} | ${Y.to??"-"} |
|
|
427
450
|
`;Z+=`
|
|
428
|
-
`}if(
|
|
451
|
+
`}if(X.binChanges.added.length>0||X.binChanges.removed.length>0){if(Z+=`### Binary Commands
|
|
429
452
|
|
|
430
|
-
`,
|
|
431
|
-
`;if(
|
|
453
|
+
`,X.binChanges.added.length>0)Z+=`**Added:** ${X.binChanges.added.map((Y)=>`\`${Y}\``).join(", ")}
|
|
454
|
+
`;if(X.binChanges.removed.length>0)Z+=`**Removed:** ${X.binChanges.removed.map((Y)=>`\`${Y}\``).join(", ")}
|
|
432
455
|
`;Z+=`
|
|
433
|
-
`}}return Z}function
|
|
456
|
+
`}}return Z}function GX($){let Z=$.get("stencil-component-change")??[],X=$.get("stencil-prop-change")??[],Q=$.get("stencil-event-change")??[],Y=$.get("stencil-method-change")??[],K=$.get("stencil-slot-change")??[];if(!(Z.length>0||X.length>0||Q.length>0||Y.length>0||K.length>0))return"";let q=`## Component API (Stencil)
|
|
434
457
|
|
|
435
|
-
`,V=new Map,U=(J)=>{if(!V.has(J))V.set(J,{props:[],events:[],methods:[],slots:[]})};for(let J of Z)U(J.tag),V.get(J.tag).component=J;for(let J of
|
|
458
|
+
`,V=new Map,U=(J)=>{if(!V.has(J))V.set(J,{props:[],events:[],methods:[],slots:[]})};for(let J of Z)U(J.tag),V.get(J.tag).component=J;for(let J of X)U(J.tag),V.get(J.tag).props.push(J);for(let J of Q)U(J.tag),V.get(J.tag).events.push(J);for(let J of Y)U(J.tag),V.get(J.tag).methods.push(J);for(let J of K)U(J.tag),V.get(J.tag).slots.push(J);for(let[J,B]of V){if(q+=`### \`<${J}>\`
|
|
436
459
|
|
|
437
460
|
`,B.component){let G=B.component,M=G.change==="removed"?"\uD83D\uDD34":G.change==="added"?"\uD83D\uDFE2":"\uD83D\uDFE1";if(q+=`**Component:** ${M} ${G.change}`,G.change==="tag-changed")q+=` (${G.fromTag} → ${G.toTag})`;if(G.change==="shadow-changed")q+=` (shadow: ${G.fromShadow} → ${G.toShadow})`;q+=`
|
|
438
461
|
`,q+=`**File:** \`${G.file}\`
|
|
439
462
|
|
|
440
463
|
`}if(B.props.length>0){q+=`**Props:**
|
|
441
|
-
`;for(let G of B.props){let M=G.change==="removed"?"\uD83D\uDD34":G.change==="added"?"\uD83D\uDFE2":"\uD83D\uDFE1",
|
|
464
|
+
`;for(let G of B.props){let M=G.change==="removed"?"\uD83D\uDD34":G.change==="added"?"\uD83D\uDFE2":"\uD83D\uDFE1",_="";if(G.details?.typeText)_=`: ${G.details.typeText}`;q+=`- ${M} \`${G.propName}\`${_} (${G.change})
|
|
442
465
|
`}q+=`
|
|
443
466
|
`}if(B.events.length>0){q+=`**Events:**
|
|
444
467
|
`;for(let G of B.events){let M=G.change==="removed"?"\uD83D\uDD34":G.change==="added"?"\uD83D\uDFE2":"\uD83D\uDFE1";q+=`- ${M} \`${G.eventName}\` (${G.change})
|
|
445
468
|
`}q+=`
|
|
446
469
|
`}if(B.methods.length>0){q+=`**Methods:**
|
|
447
|
-
`;for(let G of B.methods){let M=G.change==="removed"?"\uD83D\uDD34":G.change==="added"?"\uD83D\uDFE2":"\uD83D\uDFE1",
|
|
470
|
+
`;for(let G of B.methods){let M=G.change==="removed"?"\uD83D\uDD34":G.change==="added"?"\uD83D\uDFE2":"\uD83D\uDFE1",_=G.signature?`: ${G.signature}`:"";q+=`- ${M} \`${G.methodName}\`${_} (${G.change})
|
|
448
471
|
`}q+=`
|
|
449
472
|
`}if(B.slots.length>0){q+=`**Slots:**
|
|
450
|
-
`;for(let G of B.slots){let M=G.change==="removed"?"\uD83D\uDD34":"\uD83D\uDFE2",
|
|
473
|
+
`;for(let G of B.slots){let M=G.change==="removed"?"\uD83D\uDD34":"\uD83D\uDFE2",_=G.slotName==="default"?"(default)":`"${G.slotName}"`;q+=`- ${M} ${_} (${G.change})
|
|
451
474
|
`}q+=`
|
|
452
|
-
`}}return q}function
|
|
475
|
+
`}}return q}function OX($){let Z=$.get("angular-component-change")??[];if(Z.length===0)return"";let X=`## Angular Components
|
|
476
|
+
|
|
477
|
+
`,Q=new Map;for(let Y of Z){let K=Y.componentType;if(!Q.has(K))Q.set(K,[]);Q.get(K).push(Y)}for(let[Y,K]of Q){let W=Y.charAt(0).toUpperCase()+Y.slice(1)+"s";X+=`### ${W}
|
|
478
|
+
|
|
479
|
+
`,X+=`| File | Change | Selector | Standalone |
|
|
480
|
+
`,X+=`|------|--------|----------|------------|
|
|
481
|
+
`;for(let q of K){let V=q.change==="deleted"?"\uD83D\uDD34":q.change==="added"?"\uD83D\uDFE2":"\uD83D\uDFE1",U=q.selector||"-",J=q.standalone!==void 0?q.standalone?"Yes":"No":"-";X+=`| \`${q.file}\` | ${V} ${q.change} | \`${U}\` | ${J} |
|
|
482
|
+
`}X+=`
|
|
483
|
+
`}return X}function MX($){if($.length===0)return"";let Z=`### CI Workflows
|
|
453
484
|
|
|
454
|
-
`;for(let
|
|
455
|
-
`,Z+=`- File: \`${
|
|
456
|
-
`,Z+=`- ${
|
|
485
|
+
`;for(let X of $){let Q=X.riskType==="permissions_broadened"||X.riskType==="pull_request_target"||X.riskType==="remote_script_download"?"\uD83D\uDD34":"\uD83D\uDFE1",Y=X.riskType.replace(/_/g," ");Z+=`${Q} **${Y}**
|
|
486
|
+
`,Z+=`- File: \`${X.file}\`
|
|
487
|
+
`,Z+=`- ${X.details}
|
|
457
488
|
|
|
458
|
-
`}return Z}function
|
|
489
|
+
`}return Z}function _X($){if($.length===0)return"";let Z=`## SQL Risk
|
|
459
490
|
|
|
460
|
-
`;for(let
|
|
461
|
-
`,Z+=`- File: \`${
|
|
462
|
-
`,Z+=`- ${
|
|
491
|
+
`;for(let X of $){let Q=X.riskType==="destructive"?"\uD83D\uDD34":X.riskType==="unscoped_modification"?"\uD83D\uDD34":"\uD83D\uDFE1",Y=X.riskType.replace(/_/g," ");Z+=`${Q} **${Y}**
|
|
492
|
+
`,Z+=`- File: \`${X.file}\`
|
|
493
|
+
`,Z+=`- ${X.details}
|
|
463
494
|
|
|
464
|
-
`}return Z}function
|
|
495
|
+
`}return Z}function HX($){if($.length===0)return"";let Z=`### Infrastructure
|
|
465
496
|
|
|
466
|
-
`,
|
|
467
|
-
`;let W=
|
|
497
|
+
`,X=new Map;for(let Q of $){if(!X.has(Q.infraType))X.set(Q.infraType,[]);X.get(Q.infraType).push(Q)}for(let[Q,Y]of X){Z+=`**${Q==="dockerfile"?"Docker":Q==="terraform"?"Terraform":Q==="k8s"?"Kubernetes":Q}:**
|
|
498
|
+
`;let W=Y.flatMap((q)=>q.files);for(let q of W)Z+=`- \`${q}\`
|
|
468
499
|
`;Z+=`
|
|
469
|
-
`}return Z}function
|
|
500
|
+
`}return Z}function zX($,Z){if($.length===0&&Z.length===0)return"";let X=`## CI / Infrastructure
|
|
470
501
|
|
|
471
|
-
`;return
|
|
502
|
+
`;return X+=MX($),X+=HX(Z),X}function LX($){if($.length===0)return"";let Z=`## Database (Python)
|
|
472
503
|
|
|
473
|
-
`;for(let
|
|
474
|
-
`,Z+=`**Risk Level:** ${
|
|
504
|
+
`;for(let X of $){let Q=X.risk==="high"?"\uD83D\uDD34":X.risk==="medium"?"\uD83D\uDFE1":"\uD83D\uDFE2",Y=X.tool==="alembic"?"Alembic":"Django";Z+=`**Tool:** ${Y}
|
|
505
|
+
`,Z+=`**Risk Level:** ${Q} ${X.risk.toUpperCase()}
|
|
475
506
|
|
|
476
507
|
`,Z+=`**Files:**
|
|
477
|
-
`;for(let
|
|
508
|
+
`;for(let K of X.files)Z+=`- \`${K}\`
|
|
478
509
|
`;if(Z+=`
|
|
479
|
-
`,
|
|
480
|
-
`;for(let
|
|
510
|
+
`,X.reasons.length>0){Z+=`**Detected patterns:**
|
|
511
|
+
`;for(let K of X.reasons)Z+=`- ${K}
|
|
481
512
|
`;Z+=`
|
|
482
|
-
`}}return Z}function
|
|
513
|
+
`}}return Z}function jX($){if($.length===0)return"";let Z=`### Python Configuration
|
|
483
514
|
|
|
484
|
-
`;for(let
|
|
515
|
+
`;for(let X of $){let Q=X.isBreaking?"\uD83D\uDD34":"\uD83D\uDFE2";if(Z+=`**File:** \`${X.file}\` (${X.configType}) ${Q}
|
|
485
516
|
|
|
486
|
-
`,
|
|
487
|
-
`;for(let
|
|
488
|
-
`;if(
|
|
517
|
+
`,X.affectedSections.length>0){Z+=`**Affected Sections:**
|
|
518
|
+
`;for(let Y of X.affectedSections.slice(0,5))Z+=`- ${Y}
|
|
519
|
+
`;if(X.affectedSections.length>5)Z+=`- ...and ${X.affectedSections.length-5} more
|
|
489
520
|
`;Z+=`
|
|
490
|
-
`}if(
|
|
491
|
-
`;for(let
|
|
521
|
+
`}if(X.isBreaking&&X.breakingReasons.length>0){Z+=`**Breaking Changes:**
|
|
522
|
+
`;for(let Y of X.breakingReasons)Z+=`- ${Y}
|
|
492
523
|
`;Z+=`
|
|
493
|
-
`}}return Z}function
|
|
524
|
+
`}}return Z}function DX($){let Z=$.get("large-diff")??[],X=$.get("lockfile-mismatch")??[],Q=$.get("test-gap")??[];if(!(Z.length>0||X.length>0||Q.length>0))return"";let K=`## ⚠️ Warnings
|
|
494
525
|
|
|
495
|
-
`;for(let W of Z)
|
|
496
|
-
`;for(let W of
|
|
497
|
-
`;else if(!W.manifestChanged&&W.lockfileChanged)
|
|
498
|
-
`;for(let W of
|
|
499
|
-
`;return
|
|
500
|
-
`,
|
|
526
|
+
`;for(let W of Z)K+=`- **Large diff detected:** ${W.filesChanged} files changed, ${W.linesChanged} lines modified
|
|
527
|
+
`;for(let W of X)if(W.manifestChanged&&!W.lockfileChanged)K+=`- **Lockfile mismatch:** package.json changed but lockfile not updated
|
|
528
|
+
`;else if(!W.manifestChanged&&W.lockfileChanged)K+=`- **Lockfile mismatch:** lockfile changed but package.json not updated
|
|
529
|
+
`;for(let W of Q)K+=`- **Test coverage gap:** ${W.prodFilesChanged} production files changed, only ${W.testFilesChanged} test files changed
|
|
530
|
+
`;return K+=`
|
|
531
|
+
`,K}function NX($,Z){let X=[],Q=Z.get("test-change");if(Q&&Q.length>0){let W=Q.reduce((U,J)=>U+J.added.length,0),q=Q.reduce((U,J)=>U+J.modified.length,0),V="`bun test` - Run test suite";if(W>0||q>0){let U=[];if(W>0)U.push(`${W} new`);if(q>0)U.push(`${q} updated`);V+=` (${U.join(", ")} test file(s))`}X.push(V)}if($.profile==="sveltekit")X.push("`bun run check` - Run SvelteKit type check");let Y=Z.get("route-change");if(Y){let W=Y.filter((V)=>V.routeType==="endpoint");for(let V of W.slice(0,3)){let U=n1(V.routeId),J=V.methods?.join("/")||"GET";X.push(`Test \`${J} ${U}\` endpoint`)}let q=Y.filter((V)=>V.routeType==="page"&&V.change!=="deleted");for(let V of q.slice(0,3)){let U=n1(V.routeId);X.push(`Verify \`${U}\` page renders correctly`)}}if($.interactive?.testNotes)X.push($.interactive.testNotes);if(X.length===0)X.push("No specific test suggestions");let K=`## Suggested Test Plan
|
|
501
532
|
|
|
502
|
-
`;return
|
|
533
|
+
`;return K+=X.map((W)=>`- [ ] ${W}`).join(`
|
|
503
534
|
`)+`
|
|
504
535
|
|
|
505
|
-
`,
|
|
536
|
+
`,K}function AX($){let{riskScore:Z}=$,X=Z.level==="high"?"\uD83D\uDD34":Z.level==="medium"?"\uD83D\uDFE1":"\uD83D\uDFE2",Q=`## Risks / Notes
|
|
506
537
|
|
|
507
|
-
`;
|
|
538
|
+
`;Q+=`**Overall Risk:** ${X} ${Z.level.toUpperCase()} (score: ${Z.score}/100)
|
|
508
539
|
|
|
509
|
-
`;let
|
|
510
|
-
`;
|
|
511
|
-
`}return
|
|
540
|
+
`;let Y=Z.evidenceBullets??[];if(Y.length>0){for(let K of Y)Q+=`- ${K}
|
|
541
|
+
`;Q+=`
|
|
542
|
+
`}return Q}function V9($){let Z=s7($.findings),X="";X+=o7($),X+=i7(Z,$.findings);let Q=Z.get("file-category")?.[0],Y=Z.get("file-summary")?.[0];X+=n7(Q,Y);let K=Z.get("route-change")??[];X+=t7(K);let W=Z.get("api-contract-change")??[];X+=e7(W);let q=Z.get("graphql-change")??[];X+=KX(q);let V=Z.get("db-migration")??[];X+=$X(V);let U=Z.get("python-migration")??[];X+=LX(U);let J=Z.get("sql-risk")??[];X+=_X(J);let B=Z.get("env-var")??[];X+=ZX(B);let G=Z.get("typescript-config")??[],M=Z.get("tailwind-config")??[],_=Z.get("monorepo-config")??[],O=Z.get("vite-config")??[],H=Z.get("python-config")??[];X+=JX(G,M,_,O),X+=jX(H);let z=Z.get("cloudflare-change")??[];X+=XX(z);let N=Z.get("dependency-change")??[];X+=QX(N);let j=Z.get("package-exports")??[];X+=BX(j),X+=GX(Z),X+=OX(Z);let E=Z.get("ci-workflow")??[],x=Z.get("infra-change")??[];X+=zX(E,x);let R=Z.get("security-file")??[];X+=YX(R);let b=Z.get("convention-violation")??[];if(b.length>0){X+=`## ⚠️ Conventions
|
|
512
543
|
|
|
513
|
-
`;for(let
|
|
514
|
-
`;for(let
|
|
515
|
-
`;if(
|
|
516
|
-
`}
|
|
517
|
-
`}let
|
|
544
|
+
`;for(let P of b){X+=`- **${P.message}**
|
|
545
|
+
`;for(let N1 of P.files.slice(0,5))X+=` - \`${N1}\`
|
|
546
|
+
`;if(P.files.length>5)X+=` - ...and ${P.files.length-5} more
|
|
547
|
+
`}X+=`
|
|
548
|
+
`}let w=Z.get("test-parity-violation")??[];if(w.length>0){X+=`## \uD83E\uDDEA Test Coverage Gaps
|
|
518
549
|
|
|
519
|
-
`,
|
|
550
|
+
`,X+=`Found ${w.length} source file(s) without corresponding tests:
|
|
520
551
|
|
|
521
|
-
`;for(let
|
|
522
|
-
`}if(
|
|
523
|
-
`;
|
|
524
|
-
`}let
|
|
552
|
+
`;for(let P of w.slice(0,10)){let N1=P.confidence==="high"?"\uD83D\uDD34":P.confidence==="medium"?"\uD83D\uDFE1":"⚪";X+=`- ${N1} \`${P.sourceFile}\`
|
|
553
|
+
`}if(w.length>10)X+=`- ...and ${w.length-10} more
|
|
554
|
+
`;X+=`
|
|
555
|
+
`}let p=Z.get("impact-analysis")??[];if(p.length>0){let P={high:0,medium:1,low:2},N1=[...p].sort((U1,A1)=>P[U1.blastRadius]-P[A1.blastRadius]);X+=`## \uD83E\uDDE8 Impact Analysis
|
|
525
556
|
|
|
526
|
-
`;for(let
|
|
557
|
+
`;for(let U1 of N1){let A1=U1.blastRadius==="high"?"\uD83D\uDD34":U1.blastRadius==="medium"?"\uD83D\uDFE1":"\uD83D\uDFE2";X+=`### \`${U1.sourceFile}\` ${A1}
|
|
527
558
|
|
|
528
|
-
`,
|
|
559
|
+
`,X+=`**Blast Radius:** ${U1.blastRadius.toUpperCase()} (${U1.affectedFiles.length} files)
|
|
529
560
|
|
|
530
|
-
`,
|
|
531
|
-
`;for(let
|
|
532
|
-
`;if(
|
|
533
|
-
`;
|
|
534
|
-
`}}return
|
|
535
|
-
`}function
|
|
536
|
-
${
|
|
561
|
+
`,X+=`Affected files:
|
|
562
|
+
`;for(let a1 of U1.affectedFiles.slice(0,5))X+=`- \`${a1}\`
|
|
563
|
+
`;if(U1.affectedFiles.length>5)X+=`- ...and ${U1.affectedFiles.length-5} more
|
|
564
|
+
`;X+=`
|
|
565
|
+
`}}return X+=DX(Z),X+=NX($,Z),X+=AX($),X.trim()+`
|
|
566
|
+
`}function zV($){let Z={profile:$.profile,riskScore:$.riskScore,findings:$.findings};return JSON.stringify(Z,null,2)}q0();Y0();G0();import q1 from"chalk";import J9 from"boxen";import F2 from"cli-table3";var L={riskHigh:q1.red.bold,riskMedium:q1.yellow.bold,riskLow:q1.green.bold,fileAdded:q1.green,fileDeleted:q1.red,fileModified:q1.cyan,fileRenamed:q1.blue,header:q1.magenta.bold,subheader:q1.cyan.bold,label:q1.gray,value:q1.white,muted:q1.dim,accent:q1.blue,warning:q1.yellow,success:q1.green,error:q1.red,route:q1.blue,packageName:q1.cyan,version:q1.yellow,envVar:q1.magenta},k={file:"\uD83D\uDCC4",folder:"\uD83D\uDCC1",route:"\uD83D\uDEE4️",database:"\uD83D\uDDC4️",security:"\uD83D\uDD12",dependency:"\uD83D\uDCE6",test:"\uD83E\uDDEA",config:"⚙️",warning:"⚠️",check:"✓",cross:"✗",arrow:"→",bullet:"•",riskHigh:"\uD83D\uDD34",riskMedium:"\uD83D\uDFE1",riskLow:"\uD83D\uDFE2",impact:"\uD83D\uDCA5",infra:"\uD83C\uDFD7️",ci:"\uD83D\uDD04",sql:"\uD83D\uDCCA",lock:"\uD83D\uDD10",component:"\uD83E\uDDE9",large:"\uD83D\uDCCF",python:"\uD83D\uDC0D"},TX={sveltekit:[{cmd:"bun run check",label:"Run SvelteKit type check"}],next:[{cmd:"bun run build",label:"Run Next.js build"}],react:[],vue:[{cmd:"bun run build",label:"Run Vue build"}],astro:[{cmd:"bun run build",label:"Run Astro build"}],stencil:[{cmd:"bun run build",label:"Run Stencil build"}],angular:[{cmd:"ng build",label:"Run Angular build"}],library:[{cmd:"bun run build",label:"Build library"}],python:[{cmd:"pytest",label:"Run pytest"}],vite:[{cmd:"bun run build",label:"Run Vite build"}],auto:[]};function xX($){let Z=new Map;for(let X of $){if(!Z.has(X.type))Z.set(X.type,[]);Z.get(X.type).push(X)}return Z}function v2($){let Z=$==="high"?L.riskHigh:$==="medium"?L.riskMedium:L.riskLow;return`${$==="high"?k.riskHigh:$==="medium"?k.riskMedium:k.riskLow} ${Z($.toUpperCase())}`}function M1($,Z){let X=Z?`${Z} `:"";return`
|
|
567
|
+
${L.header(X+$)}
|
|
537
568
|
${"─".repeat(50)}
|
|
538
|
-
`}function
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
${
|
|
542
|
-
`;
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
`,Z+=`${
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
${
|
|
551
|
-
`;
|
|
569
|
+
`}function EX($,Z,X){let Q=$.find((V)=>V.type==="file-summary"),Y=[];if(Q){let V=Q.added.length+Q.modified.length+Q.deleted.length+Q.renamed.length,U=[];if(Q.added.length>0)U.push(L.fileAdded(`+${Q.added.length}`));if(Q.modified.length>0)U.push(L.fileModified(`~${Q.modified.length}`));if(Q.deleted.length>0)U.push(L.fileDeleted(`-${Q.deleted.length}`));if(Q.renamed.length>0)U.push(L.fileRenamed(`→${Q.renamed.length}`));let J=`${L.value(String(V))} file(s) changed ${U.length>0?`(${U.join(", ")})`:""}`;Y.push(J)}if(Y.length===0)Y.push("Minor changes detected");let K=`${L.label("Profile:")} ${L.accent(X)}`,W=`${L.label("Risk:")} ${v2(Z.level)} ${L.muted(`(score: ${Z.score}/100)`)}`,q=Y.map((V)=>` ${k.bullet} ${V}`).join(`
|
|
570
|
+
`)+`
|
|
571
|
+
|
|
572
|
+
${K}
|
|
573
|
+
${W}`;return J9(q,{title:"SUMMARY",titleAlignment:"left",padding:{top:0,bottom:0,left:1,right:1},borderColor:"cyan",borderStyle:"round"})}function wX($,Z){if(!$||!Z)return"";let{categories:X,summary:Q}=$;if(Q.length<=1)return"";let Y=M1("WHAT CHANGED",k.file),K=Q.filter((W)=>W.count>0).sort((W,q)=>q.count-W.count);for(let{category:W,count:q}of K){let V=Q0(W);Y+=`
|
|
574
|
+
${L.subheader(V)} ${L.muted(`(${q})`)}
|
|
575
|
+
`;let U=X[W],J=U.slice(0,8);for(let B of J){let G=" ",M=L.value;if(Z.added.includes(B))G=L.fileAdded("+ "),M=L.fileAdded;else if(Z.deleted.includes(B))G=L.fileDeleted("- "),M=L.fileDeleted;else if(Z.modified.includes(B))G=L.fileModified("~ "),M=L.fileModified;Y+=` ${G}${M(B)}
|
|
576
|
+
`}if(U.length>8)Y+=` ${L.muted(`...and ${U.length-8} more`)}
|
|
577
|
+
`}return Y}function IX($){if($.length===0)return"";let Z=M1("ROUTES / API",k.route),X=new F2({head:[L.label("Route"),L.label("Type"),L.label("Change"),L.label("Methods")],style:{head:[],border:["dim"]},chars:{top:"─","top-mid":"┬","top-left":"┌","top-right":"┐",bottom:"─","bottom-mid":"┴","bottom-left":"└","bottom-right":"┘",left:"│","left-mid":"├",mid:"─","mid-mid":"┼",right:"│","right-mid":"┤",middle:"│"}});for(let Q of $){let Y=n1(Q.routeId),K=Q.methods?.join(", ")||"-",W=Q.change==="added"?L.fileAdded:Q.change==="deleted"?L.fileDeleted:L.fileModified;X.push([L.route(Y),Q.routeType,W(Q.change),K])}return Z+=X.toString()+`
|
|
578
|
+
`,Z}function bX($){if($.length===0)return"";let Z=M1("DATABASE (SUPABASE)",k.database);for(let X of $){Z+=`${L.label("Risk Level:")} ${v2(X.risk)}
|
|
579
|
+
|
|
580
|
+
`,Z+=`${L.label("Files:")}
|
|
581
|
+
`;for(let Q of X.files)Z+=` ${k.bullet} ${L.value(Q)}
|
|
582
|
+
`;if(X.reasons.length>0){Z+=`
|
|
583
|
+
${L.label("Detected patterns:")}
|
|
584
|
+
`;for(let Q of X.reasons)Z+=` ${k.warning} ${L.warning(Q)}
|
|
552
585
|
`}Z+=`
|
|
553
|
-
`}return Z}function
|
|
554
|
-
`,Z}function
|
|
555
|
-
`,Z+=`${
|
|
556
|
-
`;for(let
|
|
586
|
+
`}return Z}function PX($){if($.length===0)return"";let Z=M1("CONFIG / ENV",k.config),X=new F2({head:[L.label("Variable"),L.label("Status"),L.label("Evidence")],style:{head:[],border:["dim"]},chars:{top:"─","top-mid":"┬","top-left":"┌","top-right":"┐",bottom:"─","bottom-mid":"┴","bottom-left":"└","bottom-right":"┘",left:"│","left-mid":"├",mid:"─","mid-mid":"┼",right:"│","right-mid":"┤",middle:"│"}});for(let Q of $){let Y=Q.evidenceFiles.slice(0,2).join(", "),K=Q.change==="added"?L.fileAdded:L.fileModified;X.push([L.envVar(Q.name),K(Q.change),L.muted(Y)])}return Z+=X.toString()+`
|
|
587
|
+
`,Z}function CX($){if($.length===0)return"";let Z=M1("CLOUDFLARE","☁️");for(let X of $){Z+=`${L.label("Area:")} ${L.value(X.area)}
|
|
588
|
+
`,Z+=`${L.label("Files:")}
|
|
589
|
+
`;for(let Q of X.files)Z+=` ${k.bullet} ${L.value(Q)}
|
|
557
590
|
`;Z+=`
|
|
558
|
-
`}return Z}function
|
|
559
|
-
`,V=new
|
|
560
|
-
`,q};if(Z.length>0)
|
|
561
|
-
`;return
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
`;
|
|
565
|
-
`}
|
|
566
|
-
`;
|
|
567
|
-
`;let X=Z.get("file-category")?.[0],K=Z.get("file-summary")?.[0];Q+=S7(X,K);let Y=Z.get("route-change")??[];Q+=v7(Y);let W=Z.get("db-migration")??[];Q+=F7(W);let q=Z.get("env-var")??[];Q+=m7(q);let V=Z.get("cloudflare-change")??[];Q+=u7(V);let U=Z.get("dependency-change")??[];return Q+=h7(U),Q+=g7($,Z),Q+=l7($),Q}var k1=new FX,gX=await g$();k1.name("branch-narrator").description("A local-first CLI that reads git diff and generates structured PR descriptions").version(gX).option("--quiet","Suppress all non-fatal diagnostic output (warnings, info)").option("--debug","Show debug diagnostics on stderr").hook("preAction",($)=>{let Z=$.opts();n2({quiet:Z.quiet,debug:Z.debug})});async function JZ($){let Z=mX({input:process.stdin,output:process.stderr});return new Promise((Q)=>{Z.question($,(X)=>{Z.close(),Q(X.trim())})})}async function N$($){if($.mode==="branch"){let{base:X,head:K}=$;if(!X)X=await p0();if(!K)K="HEAD";return{base:X,head:K}}let Z=$.base!==void 0,Q=$.head!==void 0;if(Z||Q)s1(`Warning: --base and --head are ignored when --mode is "${$.mode}"`);return{base:void 0,head:void 0}}async function BZ($){let Z=$.showSpinner?uX({text:"Collecting git changes...",color:"cyan"}).start():null,Q=await l1({mode:$.mode,base:$.base,head:$.head,includeUntracked:$.mode==="all"||$.mode==="unstaged"});if(Z)Z.text="Resolving profile...";let X=e1($.profile,Q,process.cwd()),K=y1(X);if(Z)Z.text=`Running analyzers (${K.analyzers.length})...`;let Y=await I1(K.analyzers,Q);if(Z)Z.succeed(hX.green(`Analysis complete (${Y.length} findings)`));return{findings:Y,resolvedProfile:X}}k1.command("pretty").description("Display a colorized summary of changes (for humans)").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base branch to compare against (branch mode; auto-detected if omitted)").option("--head <ref>","Head branch (branch mode; defaults to HEAD)").option("--profile <name>","Profile to use (auto|sveltekit|react|stencil|next)","auto").action(async($)=>{try{let Z=$.mode;if(!["branch","unstaged","staged","all"].includes(Z))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:Q,head:X}=await N$({mode:Z,base:$.base,head:$.head}),{findings:K,resolvedProfile:Y}=await BZ({mode:Z,base:Q,head:X,profile:$.profile,showSpinner:!0}),W=O$(K);console.log(A2({findings:K,riskScore:W,profile:Y}));return}catch(Z){j1(Z)}});k1.command("pr-body").description("Generate a Markdown PR description").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base branch to compare against (branch mode; auto-detected if omitted)").option("--head <ref>","Head branch (branch mode; defaults to HEAD)").option("-u, --uncommitted","[DEPRECATED] Use --mode unstaged instead",!1).option("--profile <name>","Profile to use (auto|sveltekit|react|stencil|next)","auto").option("--interactive","Prompt for additional context",!1).action(async($)=>{try{let Z=$.mode;if($.uncommitted)s1("Warning: --uncommitted is deprecated. Use --mode unstaged instead."),Z="unstaged";if(!["branch","unstaged","staged","all"].includes(Z))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:Q,head:X}=await N$({mode:Z,base:$.base,head:$.head}),{findings:K,resolvedProfile:Y}=await BZ({mode:Z,base:Q,head:X,profile:$.profile,showSpinner:!1}),W=O$(K),q;if($.interactive){let U=await JZ("Context/Why (1-3 sentences, press Enter to skip): "),J=await JZ("Special manual test notes (press Enter to skip): ");q={context:U||void 0,testNotes:J||void 0}}console.log(f8({findings:K,riskScore:W,profile:Y,interactive:q}));return}catch(Z){j1(Z)}});k1.command("facts").description("Output structured JSON facts (agent-grade output)").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base git reference (branch mode only; auto-detected if omitted)").option("--head <ref>","Head git reference (branch mode only; defaults to HEAD)").option("--profile <name>","Profile to use (auto|sveltekit|react|stencil|next)","auto").option("--format <type>","Output format: json|sarif","json").option("--pretty","Pretty-print JSON with 2-space indentation",!1).option("--redact","Redact obvious secret values in evidence excerpts",!1).option("--exclude <glob>","Additional exclusion glob (repeatable)",E0,[]).option("--include <glob>","Include only files matching glob (repeatable)",E0,[]).option("--max-file-bytes <n>","Maximum file size in bytes to analyze","1048576").option("--max-diff-bytes <n>","Maximum diff size in bytes to analyze","5242880").option("--max-findings <n>","Maximum number of findings to include").option("--out <path>","Write output to file instead of stdout").option("--no-timestamp","Omit generatedAt for deterministic output").option("--since <path>","Compare current output to a previous JSON file").option("--since-strict","Exit with code 1 on scope/tool/schema mismatch",!1).option("--test-parity","Enable test parity checking (opt-in, may be slow on large repos)",!1).action(async($)=>{try{let{executeFacts:Z}=await Promise.resolve().then(() => (K9(),X9)),{getRepoRoot:Q,isWorkingDirDirty:X}=await Promise.resolve().then(() => (B$(),G5)),{computeFactsDelta:K}=await Promise.resolve().then(() => (w2(),Q9)),Y=$.mode;if(!["branch","unstaged","staged","all"].includes(Y))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:W,head:q}=await N$({mode:Y,base:$.base,head:$.head});if($.format!=="json"&&$.format!=="sarif")c(`Invalid format: ${$.format}. Use json or sarif.`),process.exit(1);let V=parseInt($.maxFileBytes,10),U=parseInt($.maxDiffBytes,10),J=$.maxFindings?parseInt($.maxFindings,10):void 0,B=await l1({mode:Y,base:W,head:q,includeUntracked:Y==="all"||Y==="unstaged"}),[G,M]=await Promise.all([Q(),X()]),H=$.profile,O,z,_;if(H==="auto"){let R=b$(B,process.cwd());O=R.profile,z=R.confidence,_=R.reasons}else O=H,z="high",_=[`Profile explicitly set to ${H}`];let D=y1(O),L=await I1(D.analyzers,B);if($.testParity){let{testParityAnalyzer:R}=await Promise.resolve().then(() => (Q0(),e0)),h=await R.analyze(B);L.push(...h)}let w=O$(L),T=await Z({changeSet:B,findings:L,riskScore:w,requestedProfile:H,detectedProfile:O,profileConfidence:z,profileReasons:_,filters:{excludes:$.exclude,includes:$.include,redact:$.redact,maxFileBytes:V,maxDiffBytes:U,maxFindings:J},skippedFiles:[],warnings:[],noTimestamp:$.timestamp===!1,repoRoot:G,isDirty:M,mode:Y}),A;if($.since)A=await K({sincePath:$.since,currentFacts:T,mode:Y,base:W||null,head:q||null,profile:O,include:$.include,exclude:$.exclude,sinceStrict:$.sinceStrict});else A=T;if($.format==="sarif"&&$.since)throw new v("The --since option cannot be used with --format sarif. Remove --since or choose a different output format.",1);let b;if($.format==="sarif"){let{renderSarif:R}=await Promise.resolve().then(() => (W9(),q9)),h=R(A,B);b=$.pretty?JSON.stringify(h,null,2):JSON.stringify(h)}else b=$.pretty?JSON.stringify(A,null,2):JSON.stringify(A);if($.out){let{writeFile:R,mkdir:h}=await import("node:fs/promises"),{dirname:y}=await import("node:path");await h(y($.out),{recursive:!0}),await R($.out,b,"utf-8"),l(`Facts written to ${$.out}`)}else console.log(b);return}catch(Z){j1(Z)}});function E0($,Z){return Z.concat([$])}k1.command("dump-diff").description("Output prompt-ready git diff with smart exclusions (for AI agents)").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base git reference (branch mode only; auto-detected if omitted)").option("--head <ref>","Head git reference (branch mode only; defaults to HEAD)").option("--no-untracked","Exclude untracked files (non-branch modes)").option("--out <path>","Write output to file (creates directories as needed)").option("--format <type>","Output format: text|md|json","text").option("--unified <n>","Lines of unified context (git diff -U)","0").option("--include <glob>","Include only files matching glob (repeatable)",E0,[]).option("--exclude <glob>","Additional exclusion glob (repeatable)",E0,[]).option("--max-chars <n>","Chunk output if it exceeds this size").option("--chunk-dir <path>","Directory for chunk files",".ai/diff-chunks").option("--name <prefix>","Chunk file name prefix","diff").option("--dry-run","Preview what would be included/excluded",!1).option("--name-only","Output only file list (no diffs)",!1).option("--stat","Output file statistics (additions/deletions)",!1).option("--patch-for <path>","Output diff for a specific file only").option("--pretty","Pretty-print JSON with 2-space indentation",!1).option("--no-timestamp","Omit generatedAt for deterministic output",!1).action(async($)=>{try{let Z=$.mode;if(!["branch","unstaged","staged","all"].includes(Z))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:Q,head:X}=await N$({mode:Z,base:$.base,head:$.head}),K=$.format;if(!["text","md","json"].includes(K))c(`Invalid format: ${$.format}. Use text, md, or json.`),process.exit(1);let Y=parseInt($.unified,10);if(isNaN(Y)||Y<0)c(`Invalid unified context: ${$.unified}. Must be a non-negative integer.`),process.exit(1);let W=$.maxChars?parseInt($.maxChars,10):void 0;if(W!==void 0&&(isNaN(W)||W<=0))c(`Invalid max-chars: ${$.maxChars}. Must be a positive integer.`),process.exit(1);let q=$.nameOnly===!0,V=$.stat===!0,U=$.patchFor!==void 0;if([q,V,U].filter(Boolean).length>1)c("Options --name-only, --stat, and --patch-for are mutually exclusive. Use only one at a time."),process.exit(1);await Y5({mode:Z,base:Q,head:X,out:$.out,format:K,unified:Y,include:$.include,exclude:$.exclude,maxChars:W,chunkDir:$.chunkDir,name:$.name,dryRun:$.dryRun,includeUntracked:$.untracked!==!1,nameOnly:q,stat:V,patchFor:$.patchFor,pretty:$.pretty,noTimestamp:$.timestamp===!1});return}catch(Z){j1(Z)}});k1.command("risk-report").description("Analyze git diff and emit risk score (0-100) with evidence-backed flags").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base git reference (branch mode only; auto-detected if omitted)").option("--head <ref>","Head git reference (branch mode only; defaults to HEAD)").option("--format <type>","Output format: json|md|text","json").option("--out <path>","Write output to file instead of stdout").option("--fail-on-score <n>","Exit with code 2 if risk score >= threshold").option("--only <categories>","Only include these categories (comma-separated)").option("--exclude <categories>","Exclude these categories (comma-separated)").option("--max-evidence-lines <n>","Max evidence lines per flag","5").option("--redact","Redact secret values in evidence",!1).option("--explain-score","Include score breakdown in output",!1).option("--pretty","Pretty-print JSON with 2-space indentation",!1).option("--no-timestamp","Omit generatedAt for deterministic output",!1).option("--since <path>","Compare current output to a previous JSON file").option("--since-strict","Exit with code 1 on scope/tool/schema mismatch",!1).option("--test-parity","Enable test parity checking (opt-in, may be slow on large repos)",!1).action(async($)=>{try{let{executeRiskReport:Z,renderRiskReportJSON:Q,renderRiskReportMarkdown:X,renderRiskReportText:K}=await Promise.resolve().then(() => (G0(),J9)),{computeRiskReportDelta:Y}=await Promise.resolve().then(() => (m2(),V9)),W=$.mode;if(!["branch","unstaged","staged","all"].includes(W))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:q,head:V}=await N$({mode:W,base:$.base,head:$.head}),U=$.format;if(!["json","md","text"].includes(U))c(`Invalid format: ${$.format}. Use json, md, or text.`),process.exit(1);let J=parseInt($.maxEvidenceLines,10);if(isNaN(J)||J<1)c(`Invalid max-evidence-lines: ${$.maxEvidenceLines}. Must be a positive integer.`),process.exit(1);let B=$.failOnScore?parseInt($.failOnScore,10):void 0;if(B!==void 0&&(isNaN(B)||B<0||B>100))c(`Invalid fail-on-score: ${$.failOnScore}. Must be 0-100.`),process.exit(1);let G=$.only?$.only.split(",").map((_)=>_.trim()):void 0,M=$.exclude?$.exclude.split(",").map((_)=>_.trim()):void 0,H=await l1({mode:W,base:q,head:V,includeUntracked:W==="all"||W==="unstaged"}),O=await Z(H,{only:G,exclude:M,maxEvidenceLines:J,redact:$.redact,explainScore:$.explainScore,noTimestamp:$.timestamp===!1,mode:W,testParity:$.testParity}),z;if($.since){if(U!=="json")c("--since requires --format json (other formats not supported in v1)"),process.exit(1);let _=await Y({sincePath:$.since,currentReport:O,mode:W,base:q||null,head:V||null,only:G||null,exclude:M||null,sinceStrict:$.sinceStrict});z=$.pretty?JSON.stringify(_,null,2):JSON.stringify(_)}else switch(U){case"json":z=Q(O,$.pretty);break;case"md":z=X(O);break;case"text":z=K(O);break}if($.out){let{writeFile:_,mkdir:D}=await import("node:fs/promises"),{dirname:L}=await import("node:path");await D(L($.out),{recursive:!0}),await _($.out,z,"utf-8"),l(`Risk report written to ${$.out}`)}else console.log(z);if(B!==void 0&&O.riskScore>=B){c(`Risk score ${O.riskScore} >= threshold ${B}`),process.exitCode=2;return}return}catch(Z){j1(Z)}});k1.command("zoom").description("Zoom into a specific finding or flag for detailed context").option("--finding <id>","Finding ID to zoom into").option("--flag <id>","Flag ID to zoom into").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base git reference (branch mode only; auto-detected if omitted)").option("--head <ref>","Head git reference (branch mode only; defaults to HEAD)").option("--profile <name>","Profile to use (auto|sveltekit|react|stencil|next)","auto").option("--format <type>","Output format: json|md|text","json").option("--unified <n>","Lines of unified context for patch hunks","3").option("--no-patch","Do not include patch context, only evidence").option("--max-evidence-lines <n>","Max evidence excerpt lines to show","8").option("--redact","Redact obvious secret values in evidence excerpts",!1).option("--out <path>","Write output to file instead of stdout").option("--pretty","Pretty-print JSON with 2-space indentation",!1).option("--no-timestamp","Omit generatedAt for deterministic output").action(async($)=>{try{let{executeZoom:Z}=await Promise.resolve().then(() => (O9(),G9)),{renderZoomJSON:Q,renderZoomMarkdown:X,renderZoomText:K}=await Promise.resolve().then(() => M9),Y=$.mode;if(!["branch","unstaged","staged","all"].includes(Y))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:W,head:q}=await N$({mode:Y,base:$.base,head:$.head}),V=$.format;if(!["json","md","text"].includes(V))c(`Invalid format: ${$.format}. Use json, md, or text.`),process.exit(1);let U=parseInt($.unified,10);if(isNaN(U)||U<0)c(`Invalid unified context: ${$.unified}. Must be a non-negative integer.`),process.exit(1);let J=parseInt($.maxEvidenceLines,10);if(isNaN(J)||J<1)c(`Invalid max-evidence-lines: ${$.maxEvidenceLines}. Must be a positive integer.`),process.exit(1);let B=await l1({mode:Y,base:W,head:q,includeUntracked:Y==="all"||Y==="unstaged"}),G=await Z(B,{findingId:$.finding,flagId:$.flag,mode:Y,base:W,head:q,profile:$.profile,includePatch:$.patch!==!1,unified:U,maxEvidenceLines:J,redact:$.redact,noTimestamp:$.timestamp===!1}),M;switch(V){case"json":M=Q(G,$.pretty);break;case"md":M=X(G);break;case"text":M=K(G);break}if($.out){let{writeFile:H,mkdir:O}=await import("node:fs/promises"),{dirname:z}=await import("node:path");await O(z($.out),{recursive:!0}),await H($.out,M,"utf-8"),l(`Zoom output written to ${$.out}`)}else console.log(M);return}catch(Z){j1(Z)}});k1.command("integrate [target]").description("Generate provider-specific rules (auto-detects when omitted)").option("--dry-run","Preview what would be written without creating files",!1).option("--force","Overwrite existing files",!1).action(async($,Z)=>{try{let{executeIntegrate:Q}=await Promise.resolve().then(() => (k9(),y9));await Q({target:$,dryRun:Z.dryRun,force:Z.force});return}catch(Q){j1(Q)}});var u$=k1.command("snap").description("Manage local workspace snapshots for agent iteration");u$.command("save [label]").description("Create a new snapshot of current workspace state").option("--out <path>","Write snapshotId to file instead of stdout").action(async($,Z)=>{try{let{executeSnapSave:Q}=await Promise.resolve().then(() => (A$(),D$)),X=await Q({label:$,out:Z.out});if(!Z.out)console.log(X.snapshotId);else l(`Snapshot ${X.snapshotId} saved to ${Z.out}`);return}catch(Q){j1(Q)}});u$.command("list").description("List all snapshots").option("--pretty","Pretty-print JSON with 2-space indentation",!1).action(async($)=>{try{let{executeSnapList:Z,renderSnapListJSON:Q}=await Promise.resolve().then(() => (A$(),D$)),X=await Z();console.log(Q(X,$.pretty));return}catch(Z){j1(Z)}});u$.command("show <snapshotId>").description("Show snapshot details").option("--pretty","Pretty-print JSON with 2-space indentation",!1).action(async($,Z)=>{try{let{executeSnapShow:Q,renderSnapShowJSON:X}=await Promise.resolve().then(() => (A$(),D$)),K=await Q($);console.log(X(K,Z.pretty));return}catch(Q){j1(Q)}});u$.command("diff <idA> <idB>").description("Compare two snapshots").option("--pretty","Pretty-print JSON with 2-space indentation",!1).action(async($,Z,Q)=>{try{let{executeSnapDiff:X,renderSnapDiffJSON:K}=await Promise.resolve().then(() => (A$(),D$)),Y=await X($,Z);console.log(K(Y,Q.pretty));return}catch(X){j1(X)}});u$.command("restore <snapshotId>").description("Restore workspace to snapshot state (creates automatic backup first)").action(async($)=>{try{let{executeSnapRestore:Z}=await Promise.resolve().then(() => (A$(),D$)),Q=await Z($);if(l(`Restored to snapshot ${Q.snapshotId}`),l(`Pre-restore backup: ${Q.backupSnapshotId}`),Q.verified)l("Verification: passed");else s1("Verification: patch hashes differ (this may be expected for empty patches)");return}catch(Z){j1(Z)}});function j1($){if($ instanceof v)c(`Error: ${$.message}`),process.exit($.exitCode);if($ instanceof Error){if(c(`Unexpected error: ${$.message}`),process.env.DEBUG)c($.stack||"")}else c("An unexpected error occurred");process.exit(1)}await k1.parseAsync();
|
|
591
|
+
`}return Z}function SX($){if($.length===0)return"";let Z=$.filter((K)=>K.section==="dependencies"),X=$.filter((K)=>K.section==="devDependencies"),Q=M1("DEPENDENCIES",k.dependency),Y=(K,W)=>{if(K.length===0)return"";let q=`${L.subheader(W)}
|
|
592
|
+
`,V=new F2({head:[L.label("Package"),L.label("From"),L.label("To"),L.label("Impact")],style:{head:[],border:["dim"]},chars:{top:"─","top-mid":"┬","top-left":"┌","top-right":"┐",bottom:"─","bottom-mid":"┴","bottom-left":"└","bottom-right":"┘",left:"│","left-mid":"├",mid:"─","mid-mid":"┼",right:"│","right-mid":"┤",middle:"│"}});for(let U of K){let J=U.impact==="major"?L.error:U.impact==="minor"?L.warning:L.muted;V.push([L.packageName(U.name),L.muted(U.from??"-"),L.version(U.to??"-"),J(U.impact??"-")])}return q+=V.toString()+`
|
|
593
|
+
`,q};if(Z.length>0)Q+=Y(Z,"Production");if(X.length>0)Q+=Y(X,"Dev Dependencies");return Q}function kX($,Z){let X=[],Q=Z.get("test-change");if(Q&&Q.length>0)X.push(`${L.accent("bun test")} - Run test suite`);let Y=TX[$.profile]??[];for(let{cmd:V,label:U}of Y)X.push(`${L.accent(V)} - ${U}`);let K=Z.get("route-change");if(K){let V=K.filter((J)=>J.routeType==="endpoint");for(let J of V.slice(0,3)){let B=n1(J.routeId),G=J.methods?.join("/")||"GET";X.push(`Test ${L.route(`${G} ${B}`)} endpoint`)}let U=K.filter((J)=>J.routeType==="page"&&J.change!=="deleted");for(let J of U.slice(0,3)){let B=n1(J.routeId);X.push(`Verify ${L.route(B)} page renders correctly`)}}let W=Z.get("test-gap");if(W&&W.length>0){let V=W.reduce((U,J)=>U+J.prodFilesChanged,0);X.push(`${L.warning(`${V} modified file(s) lack test coverage`)}`)}if($.interactive?.testNotes)X.push($.interactive.testNotes);if(X.length===0)X.push("No specific test suggestions");let q=M1("SUGGESTED TEST PLAN",k.test);for(let V of X)q+=` ${L.muted("[ ]")} ${V}
|
|
594
|
+
`;return q}function FX($){if($.length===0)return"";let Z=$.filter((K)=>K.blastRadius==="high"||K.blastRadius==="medium");if(Z.length===0)return"";let X=M1("IMPACT ANALYSIS",k.impact),Q=Z.filter((K)=>K.blastRadius==="high"),Y=Z.filter((K)=>K.blastRadius==="medium");if(Q.length>0){X+=`${L.riskHigh("HIGH BLAST RADIUS")} ${L.muted(`(${Q.length} file(s))`)}
|
|
595
|
+
`;for(let K of Q.slice(0,5)){if(X+=` ${k.bullet} ${L.value(K.sourceFile)}`,K.affectedFiles.length>0)X+=` ${L.muted(`→ affects ${K.affectedFiles.length} file(s)`)}`;X+=`
|
|
596
|
+
`}if(Q.length>5)X+=` ${L.muted(`...and ${Q.length-5} more`)}
|
|
597
|
+
`;X+=`
|
|
598
|
+
`}if(Y.length>0){X+=`${L.riskMedium("MEDIUM BLAST RADIUS")} ${L.muted(`(${Y.length} file(s))`)}
|
|
599
|
+
`;for(let K of Y.slice(0,3)){if(X+=` ${k.bullet} ${L.value(K.sourceFile)}`,K.affectedFiles.length>0)X+=` ${L.muted(`→ affects ${K.affectedFiles.length} file(s)`)}`;X+=`
|
|
600
|
+
`}if(Y.length>3)X+=` ${L.muted(`...and ${Y.length-3} more`)}
|
|
601
|
+
`}return X}function vX($){if($.length===0)return"";let Z=M1("INFRASTRUCTURE",k.infra),X=new Map;for(let Q of $){if(!X.has(Q.infraType))X.set(Q.infraType,[]);X.get(Q.infraType).push(...Q.files)}for(let[Q,Y]of X){let K=Q==="docker"?"Docker":Q==="terraform"?"Terraform":Q==="kubernetes"?"Kubernetes":Q==="compose"?"Docker Compose":Q.charAt(0).toUpperCase()+Q.slice(1);Z+=`${L.subheader(K)} ${L.muted(`(${Y.length})`)}
|
|
602
|
+
`;for(let W of Y.slice(0,5))Z+=` ${k.bullet} ${L.value(W)}
|
|
603
|
+
`;if(Y.length>5)Z+=` ${L.muted(`...and ${Y.length-5} more`)}
|
|
604
|
+
`;Z+=`
|
|
605
|
+
`}return Z}function yX($){if($.length===0)return"";let Z=$.filter((Y)=>Y.riskType==="permissions_broadened"||Y.riskType==="pull_request_target"),X=$.filter((Y)=>Y.riskType!=="permissions_broadened"&&Y.riskType!=="pull_request_target");if(Z.length===0&&X.length===0)return"";let Q=M1("CI/CD WORKFLOWS",k.ci);if(Z.length>0){Q+=`${L.riskHigh("⚠️ SECURITY CONCERNS")}
|
|
606
|
+
`;for(let Y of Z){let K=Y.riskType==="permissions_broadened"?"Permissions broadened":"pull_request_target trigger";Q+=` ${k.bullet} ${L.warning(Y.file)}: ${L.error(K)}
|
|
607
|
+
`}Q+=`
|
|
608
|
+
`}if(X.length>0){Q+=`${L.subheader("Modified Workflows")} ${L.muted(`(${X.length})`)}
|
|
609
|
+
`;for(let Y of X.slice(0,5)){if(Q+=` ${k.bullet} ${L.value(Y.file)}`,Y.riskType)Q+=` ${L.muted(`(${Y.riskType})`)}`;Q+=`
|
|
610
|
+
`}if(X.length>5)Q+=` ${L.muted(`...and ${X.length-5} more`)}
|
|
611
|
+
`}return Q}function mX($){if($.length===0)return"";let Z=M1("SQL RISKS",k.sql),X=$.filter((Y)=>Y.riskType==="destructive"),Q=$.filter((Y)=>Y.riskType!=="destructive");if(X.length>0){Z+=`${L.riskHigh("⚠️ DESTRUCTIVE SQL DETECTED")}
|
|
612
|
+
`;for(let Y of X){if(Z+=` ${k.bullet} ${L.error(Y.file)}`,Y.details)Z+=`: ${L.warning(Y.details)}`;Z+=`
|
|
613
|
+
`}Z+=`
|
|
614
|
+
`}if(Q.length>0){Z+=`${L.subheader("Other SQL Changes")} ${L.muted(`(${Q.length})`)}
|
|
615
|
+
`;for(let Y of Q.slice(0,5)){if(Z+=` ${k.bullet} ${L.value(Y.file)}`,Y.riskType)Z+=` ${L.muted(`(${Y.riskType})`)}`;Z+=`
|
|
616
|
+
`}if(Q.length>5)Z+=` ${L.muted(`...and ${Q.length-5} more`)}
|
|
617
|
+
`}return Z}function hX($){let Z=$.find((Q)=>Q.type==="lockfile-mismatch");if(!Z)return"";if(Z.manifestChanged===Z.lockfileChanged)return"";let X=M1("LOCKFILE WARNING",k.lock);if(Z.manifestChanged&&!Z.lockfileChanged)X+=`${L.warning("⚠️ package.json changed but lockfile not updated")}
|
|
618
|
+
`,X+=`${L.muted("Run your package manager to update the lockfile.")}
|
|
619
|
+
`;else if(!Z.manifestChanged&&Z.lockfileChanged)X+=`${L.warning("⚠️ Lockfile changed but package.json not updated")}
|
|
620
|
+
`,X+=`${L.muted("This may indicate inconsistent dependency resolution.")}
|
|
621
|
+
`;return X}function uX($){let Z=$.get("stencil-component-change")??[],X=$.get("stencil-prop-change")??[],Q=$.get("stencil-event-change")??[],Y=$.get("stencil-method-change")??[],K=$.get("stencil-slot-change")??[];if(Z.length+X.length+Q.length+Y.length+K.length===0)return"";let q=M1("STENCIL COMPONENTS",k.component),V=new Map,U=(J)=>{if(!V.has(J))V.set(J,{props:[],events:[],methods:[],slots:[]});return V.get(J)};for(let J of X)U(J.tag).props.push(`${J.propName} (${J.change})`);for(let J of Q)U(J.tag).events.push(`${J.eventName} (${J.change})`);for(let J of Y)U(J.tag).methods.push(`${J.methodName} (${J.change})`);for(let J of K){let B=U(J.tag),G=J.slotName||"(default)";B.slots.push(`${G} (${J.change})`)}for(let[J,B]of V){q+=`${L.subheader(`<${J}>`)}`;let G=[];if(B.props.length>0)G.push(`${B.props.length} prop(s)`);if(B.events.length>0)G.push(`${B.events.length} event(s)`);if(B.methods.length>0)G.push(`${B.methods.length} method(s)`);if(B.slots.length>0)G.push(`${B.slots.length} slot(s)`);q+=` ${L.muted(`(${G.join(", ")})`)}
|
|
622
|
+
`;let M=[...B.props.map((_)=>`@Prop ${_}`),...B.events.map((_)=>`@Event ${_}`),...B.methods.map((_)=>`@Method ${_}`),...B.slots.map((_)=>`slot ${_}`)];for(let _ of M.slice(0,4))q+=` ${k.bullet} ${L.value(_)}
|
|
623
|
+
`;if(M.length>4)q+=` ${L.muted(`...and ${M.length-4} more`)}
|
|
624
|
+
`;q+=`
|
|
625
|
+
`}return q}function gX($){let Z=$.get("typescript-config")??[],X=$.get("tailwind-config")??[],Q=$.get("graphql-change")??[],Y=$.get("package-exports")??[],K=$.get("monorepo-config")??[];if(Z.length+X.length+Q.length+Y.length+K.length===0)return"";let q=M1("CONFIG CHANGES",k.config);if(Z.length>0){let V=Z.some((U)=>U.isBreaking);if(q+=`${L.subheader("TypeScript Config")}`,V)q+=` ${L.error("(BREAKING)")}`;q+=`
|
|
626
|
+
`;for(let U of Z){q+=` ${k.bullet} ${L.value(U.file)}`;let J=[...U.changedOptions.added,...U.changedOptions.removed,...U.changedOptions.modified];if(J.length>0){if(q+=`: ${L.muted(J.slice(0,3).join(", "))}`,J.length>3)q+=L.muted(` +${J.length-3}`)}q+=`
|
|
627
|
+
`}q+=`
|
|
628
|
+
`}if(X.length>0){let V=X.some((U)=>U.isBreaking);if(q+=`${L.subheader("Tailwind Config")}`,V)q+=` ${L.error("(BREAKING)")}`;q+=`
|
|
629
|
+
`;for(let U of X)q+=` ${k.bullet} ${L.value(U.file)}
|
|
630
|
+
`;q+=`
|
|
631
|
+
`}if(Q.length>0){let V=Q.some((U)=>U.isBreaking);if(q+=`${L.subheader("GraphQL Schema")}`,V)q+=` ${L.error("(BREAKING)")}`;q+=`
|
|
632
|
+
`;for(let U of Q){q+=` ${k.bullet} ${L.value(U.file)}`;let J=[...U.breakingChanges.map((B)=>`${B} (breaking)`),...U.addedElements];if(J.length>0){if(q+=`: ${L.muted(J.slice(0,2).join(", "))}`,J.length>2)q+=L.muted(` +${J.length-2}`)}q+=`
|
|
633
|
+
`}q+=`
|
|
634
|
+
`}if(Y.length>0){let V=Y.some((U)=>U.isBreaking);if(q+=`${L.subheader("Package Exports")}`,V)q+=` ${L.error("(BREAKING)")}`;q+=`
|
|
635
|
+
`;for(let U of Y){let J=[];if(U.addedExports&&U.addedExports.length>0)J.push(`+${U.addedExports.length} added`);if(U.removedExports&&U.removedExports.length>0)J.push(`-${U.removedExports.length} removed`);if(U.binChanges){if(U.binChanges.added.length>0)J.push(`+${U.binChanges.added.length} bin`);if(U.binChanges.removed.length>0)J.push(`-${U.binChanges.removed.length} bin`)}if(q+=` ${k.bullet} ${L.value("package.json exports")}`,J.length>0)q+=`: ${L.muted(J.join(", "))}`;q+=`
|
|
636
|
+
`}q+=`
|
|
637
|
+
`}if(K.length>0){q+=`${L.subheader("Monorepo Config")}
|
|
638
|
+
`;for(let V of K)q+=` ${k.bullet} ${L.value(V.tool)}: ${L.muted(V.file)}
|
|
639
|
+
`;q+=`
|
|
640
|
+
`}return q}function fX($){let Z=j$($);if(Z.length===0)return"";let X=M1("KEY HIGHLIGHTS","⚡"),Q=[],Y=[],K=[];for(let W of Z){let q=W.toLowerCase();if(q.includes("risk")||q.includes("security")||q.includes("breaking")||q.includes("destructive")||q.includes("blast radius"))Q.push(W);else if(q.includes("added")||q.includes("modified")||q.includes("deleted")||q.includes("changed")||q.includes("updated")||q.includes("new"))Y.push(W);else K.push(W)}if(Q.length>0){X+=`${L.riskHigh("Risks & Breaking Changes")}
|
|
641
|
+
`;for(let W of Q)X+=` ${k.warning} ${L.warning(W)}
|
|
642
|
+
`;X+=`
|
|
643
|
+
`}if(Y.length>0){X+=`${L.subheader("Changes")}
|
|
644
|
+
`;for(let W of Y)X+=` ${k.bullet} ${L.value(W)}
|
|
645
|
+
`;X+=`
|
|
646
|
+
`}if(K.length>0){X+=`${L.subheader("Info")}
|
|
647
|
+
`;for(let W of K)X+=` ${k.bullet} ${L.muted(W)}
|
|
648
|
+
`;X+=`
|
|
649
|
+
`}return X}function lX($){if($.length===0)return"";let Z=$[0];if(!Z||Z.linesChanged<500)return"";let X=M1("LARGE CHANGES",k.large);return X+=`${L.warning("⚠️ Large change detected - review carefully")}
|
|
650
|
+
|
|
651
|
+
`,X+=` ${k.bullet} ${L.value(`${Z.filesChanged} file(s)`)} changed
|
|
652
|
+
`,X+=` ${k.bullet} ${L.value(`${Z.linesChanged} line(s)`)} modified
|
|
653
|
+
`,X}function cX($){let{riskScore:Z}=$,X=M1("RISKS / NOTES",k.warning);X+=`${L.label("Overall Risk:")} ${v2(Z.level)} ${L.muted(`(score: ${Z.score}/100)`)}
|
|
654
|
+
|
|
655
|
+
`;let Q=Z.evidenceBullets??[];if(Q.length>0)for(let Y of Q)X+=` ${k.bullet} ${Y}
|
|
656
|
+
`;return X}function pX($){if(!$.interactive?.context)return"";return J9($.interactive.context,{title:"CONTEXT",titleAlignment:"left",padding:{top:0,bottom:0,left:1,right:1},borderColor:"blue",borderStyle:"round"})+`
|
|
657
|
+
`}function y2($){let Z=xX($.findings),X=`
|
|
658
|
+
`;X+=pX($),X+=EX($.findings,$.riskScore,$.profile),X+=`
|
|
659
|
+
`,X+=fX($.findings);let Q=Z.get("large-diff")??[];X+=lX(Q);let Y=Z.get("lockfile-mismatch")??[];X+=hX(Y);let K=Z.get("impact-analysis")??[];X+=FX(K);let W=Z.get("file-category")?.[0],q=Z.get("file-summary")?.[0];X+=wX(W,q);let V=Z.get("route-change")??[];X+=IX(V);let U=Z.get("db-migration")??[];X+=bX(U);let J=Z.get("sql-risk")??[];X+=mX(J);let B=Z.get("env-var")??[];X+=PX(B),X+=gX(Z),X+=uX(Z);let G=Z.get("infra-change")??[];X+=vX(G);let M=Z.get("ci-workflow")??[];X+=yX(M);let _=Z.get("cloudflare-change")??[];X+=CX(_);let O=Z.get("dependency-change")??[];return X+=SX(O),X+=kX($,Z),X+=cX($),X}var u1=new hY,lY=await a$();u1.name("branch-narrator").description("A local-first CLI that reads git diff and generates structured PR descriptions").version(lY).option("--quiet","Suppress all non-fatal diagnostic output (warnings, info)").option("--debug","Show debug diagnostics on stderr").hook("preAction",($)=>{let Z=$.opts();B5({quiet:Z.quiet,debug:Z.debug})});async function IZ($){let Z=uY({input:process.stdin,output:process.stderr});return new Promise((X)=>{Z.question($,(Q)=>{Z.close(),X(Q.trim())})})}async function b$($){if($.mode==="branch"){let{base:Q,head:Y}=$;if(!Q)Q=await t0();if(!Y)Y="HEAD";return{base:Q,head:Y}}let Z=$.base!==void 0,X=$.head!==void 0;if(Z||X)J$(`Warning: --base and --head are ignored when --mode is "${$.mode}"`);return{base:void 0,head:void 0}}async function bZ($){let Z=$.showSpinner?gY({text:"Collecting git changes...",color:"cyan"}).start():null,X=await i1({mode:$.mode,base:$.base,head:$.head,includeUntracked:$.mode==="all"||$.mode==="unstaged"});if(Z)Z.text="Resolving profile...";let Q=Y$($.profile,X,process.cwd()),Y=h1(Q);if(Z)Z.text=`Running analyzers (${Y.analyzers.length})...`;let K=await v1(Y.analyzers,X);if(Z)Z.succeed(fY.green(`Analysis complete (${K.length} findings)`));return{findings:K,resolvedProfile:Q}}u1.command("pretty").description("Display a colorized summary of changes (for humans)").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base branch to compare against (branch mode; auto-detected if omitted)").option("--head <ref>","Head branch (branch mode; defaults to HEAD)").option("--profile <name>","Profile to use (auto|sveltekit|react|stencil|next)","auto").action(async($)=>{try{let Z=$.mode;if(!["branch","unstaged","staged","all"].includes(Z))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:X,head:Q}=await b$({mode:Z,base:$.base,head:$.head}),{findings:Y,resolvedProfile:K}=await bZ({mode:Z,base:X,head:Q,profile:$.profile,showSpinner:!0}),W=D$(Y);console.log(y2({findings:Y,riskScore:W,profile:K}));return}catch(Z){I1(Z)}});u1.command("pr-body").description("Generate a Markdown PR description").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base branch to compare against (branch mode; auto-detected if omitted)").option("--head <ref>","Head branch (branch mode; defaults to HEAD)").option("--profile <name>","Profile to use (auto|sveltekit|react|stencil|next)","auto").option("--interactive","Prompt for additional context",!1).action(async($)=>{try{let Z=$.mode;if(!["branch","unstaged","staged","all"].includes(Z))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:X,head:Q}=await b$({mode:Z,base:$.base,head:$.head}),{findings:Y,resolvedProfile:K}=await bZ({mode:Z,base:X,head:Q,profile:$.profile,showSpinner:!1}),W=D$(Y),q;if($.interactive){let U=await IZ("Context/Why (1-3 sentences, press Enter to skip): "),J=await IZ("Special manual test notes (press Enter to skip): ");q={context:U||void 0,testNotes:J||void 0}}console.log(V9({findings:Y,riskScore:W,profile:K,interactive:q}));return}catch(Z){I1(Z)}});u1.command("facts").description("Output structured JSON facts (agent-grade output)").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base git reference (branch mode only; auto-detected if omitted)").option("--head <ref>","Head git reference (branch mode only; defaults to HEAD)").option("--profile <name>","Profile to use (auto|sveltekit|react|stencil|next)","auto").option("--format <type>","Output format: json|sarif","json").option("--pretty","Pretty-print JSON with 2-space indentation",!1).option("--redact","Redact obvious secret values in evidence excerpts",!1).option("--exclude <glob>","Additional exclusion glob (repeatable)",y0,[]).option("--include <glob>","Include only files matching glob (repeatable)",y0,[]).option("--max-file-bytes <n>","Maximum file size in bytes to analyze","1048576").option("--max-diff-bytes <n>","Maximum diff size in bytes to analyze","5242880").option("--max-findings <n>","Maximum number of findings to include").option("--out <path>","Write output to file instead of stdout").option("--no-timestamp","Omit generatedAt for deterministic output").option("--since <path>","Compare current output to a previous JSON file").option("--since-strict","Exit with code 1 on scope/tool/schema mismatch",!1).option("--test-parity","Enable test parity checking (opt-in, may be slow on large repos)",!1).action(async($)=>{try{let{executeFacts:Z}=await Promise.resolve().then(() => (A9(),N9)),{getRepoRoot:X,isWorkingDirDirty:Q}=await Promise.resolve().then(() => (H$(),w5)),{computeFactsDelta:Y}=await Promise.resolve().then(() => (f2(),D9)),K=$.mode;if(!["branch","unstaged","staged","all"].includes(K))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:W,head:q}=await b$({mode:K,base:$.base,head:$.head});if($.format!=="json"&&$.format!=="sarif")c(`Invalid format: ${$.format}. Use json or sarif.`),process.exit(1);let V=parseInt($.maxFileBytes,10),U=parseInt($.maxDiffBytes,10),J=$.maxFindings?parseInt($.maxFindings,10):void 0,B=await i1({mode:K,base:W,head:q,includeUntracked:K==="all"||K==="unstaged"}),[G,M]=await Promise.all([X(),Q()]),_=$.profile,O,H,z;if(_==="auto"){let w=y$(B,process.cwd());O=w.profile,H=w.confidence,z=w.reasons}else O=_,H="high",z=[`Profile explicitly set to ${_}`];let N=h1(O),j=await v1(N.analyzers,B);if($.testParity){let{testParityAnalyzer:w}=await Promise.resolve().then(() => (J0(),W2)),p=await w.analyze(B);j.push(...p)}let E=D$(j),x=await Z({changeSet:B,findings:j,riskScore:E,requestedProfile:_,detectedProfile:O,profileConfidence:H,profileReasons:z,filters:{excludes:$.exclude,includes:$.include,redact:$.redact,maxFileBytes:V,maxDiffBytes:U,maxFindings:J},skippedFiles:[],warnings:[],noTimestamp:$.timestamp===!1,repoRoot:G,isDirty:M,mode:K}),R;if($.since)R=await Y({sincePath:$.since,currentFacts:x,mode:K,base:W||null,head:q||null,profile:O,include:$.include,exclude:$.exclude,sinceStrict:$.sinceStrict});else R=x;if($.format==="sarif"&&$.since)throw new y("The --since option cannot be used with --format sarif. Remove --since or choose a different output format.",1);let b;if($.format==="sarif"){let{renderSarif:w}=await Promise.resolve().then(() => (x9(),T9)),p=w(R,B);b=$.pretty?JSON.stringify(p,null,2):JSON.stringify(p)}else b=$.pretty?JSON.stringify(R,null,2):JSON.stringify(R);if($.out){let{writeFile:w,mkdir:p}=await import("node:fs/promises"),{dirname:P}=await import("node:path");await p(P($.out),{recursive:!0}),await w($.out,b,"utf-8"),l(`Facts written to ${$.out}`)}else console.log(b);return}catch(Z){I1(Z)}});function y0($,Z){return Z.concat([$])}u1.command("dump-diff").description("Output prompt-ready git diff with smart exclusions (for AI agents)").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base git reference (branch mode only; auto-detected if omitted)").option("--head <ref>","Head git reference (branch mode only; defaults to HEAD)").option("--no-untracked","Exclude untracked files (non-branch modes)").option("--out <path>","Write output to file (creates directories as needed)").option("--format <type>","Output format: text|md|json","text").option("--unified <n>","Lines of unified context (git diff -U)","0").option("--include <glob>","Include only files matching glob (repeatable)",y0,[]).option("--exclude <glob>","Additional exclusion glob (repeatable)",y0,[]).option("--max-chars <n>","Chunk output if it exceeds this size").option("--chunk-dir <path>","Directory for chunk files",".ai/diff-chunks").option("--name <prefix>","Chunk file name prefix","diff").option("--dry-run","Preview what would be included/excluded",!1).option("--name-only","Output only file list (no diffs)",!1).option("--stat","Output file statistics (additions/deletions)",!1).option("--patch-for <path>","Output diff for a specific file only").option("--pretty","Pretty-print JSON with 2-space indentation",!1).option("--no-timestamp","Omit generatedAt for deterministic output",!1).action(async($)=>{try{let Z=$.mode;if(!["branch","unstaged","staged","all"].includes(Z))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:X,head:Q}=await b$({mode:Z,base:$.base,head:$.head}),Y=$.format;if(!["text","md","json"].includes(Y))c(`Invalid format: ${$.format}. Use text, md, or json.`),process.exit(1);let K=parseInt($.unified,10);if(isNaN(K)||K<0)c(`Invalid unified context: ${$.unified}. Must be a non-negative integer.`),process.exit(1);let W=$.maxChars?parseInt($.maxChars,10):void 0;if(W!==void 0&&(isNaN(W)||W<=0))c(`Invalid max-chars: ${$.maxChars}. Must be a positive integer.`),process.exit(1);let q=$.nameOnly===!0,V=$.stat===!0,U=$.patchFor!==void 0;if([q,V,U].filter(Boolean).length>1)c("Options --name-only, --stat, and --patch-for are mutually exclusive. Use only one at a time."),process.exit(1);await D5({mode:Z,base:X,head:Q,out:$.out,format:Y,unified:K,include:$.include,exclude:$.exclude,maxChars:W,chunkDir:$.chunkDir,name:$.name,dryRun:$.dryRun,includeUntracked:$.untracked!==!1,nameOnly:q,stat:V,patchFor:$.patchFor,pretty:$.pretty,noTimestamp:$.timestamp===!1});return}catch(Z){I1(Z)}});u1.command("risk-report").description("Analyze git diff and emit risk score (0-100) with evidence-backed flags").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base git reference (branch mode only; auto-detected if omitted)").option("--head <ref>","Head git reference (branch mode only; defaults to HEAD)").option("--format <type>","Output format: json|md|text","json").option("--out <path>","Write output to file instead of stdout").option("--fail-on-score <n>","Exit with code 2 if risk score >= threshold").option("--only <categories>","Only include these categories (comma-separated)").option("--exclude <categories>","Exclude these categories (comma-separated)").option("--max-evidence-lines <n>","Max evidence lines per flag","5").option("--redact","Redact secret values in evidence",!1).option("--explain-score","Include score breakdown in output",!1).option("--pretty","Pretty-print JSON with 2-space indentation",!1).option("--no-timestamp","Omit generatedAt for deterministic output",!1).option("--since <path>","Compare current output to a previous JSON file").option("--since-strict","Exit with code 1 on scope/tool/schema mismatch",!1).option("--test-parity","Enable test parity checking (opt-in, may be slow on large repos)",!1).action(async($)=>{try{let{executeRiskReport:Z,renderRiskReportJSON:X,renderRiskReportMarkdown:Q,renderRiskReportText:Y}=await Promise.resolve().then(() => (N0(),I9)),{computeRiskReportDelta:K}=await Promise.resolve().then(() => (t2(),w9)),W=$.mode;if(!["branch","unstaged","staged","all"].includes(W))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:q,head:V}=await b$({mode:W,base:$.base,head:$.head}),U=$.format;if(!["json","md","text"].includes(U))c(`Invalid format: ${$.format}. Use json, md, or text.`),process.exit(1);let J=parseInt($.maxEvidenceLines,10);if(isNaN(J)||J<1)c(`Invalid max-evidence-lines: ${$.maxEvidenceLines}. Must be a positive integer.`),process.exit(1);let B=$.failOnScore?parseInt($.failOnScore,10):void 0;if(B!==void 0&&(isNaN(B)||B<0||B>100))c(`Invalid fail-on-score: ${$.failOnScore}. Must be 0-100.`),process.exit(1);let G=$.only?$.only.split(",").map((z)=>z.trim()):void 0,M=$.exclude?$.exclude.split(",").map((z)=>z.trim()):void 0,_=await i1({mode:W,base:q,head:V,includeUntracked:W==="all"||W==="unstaged"}),O=await Z(_,{only:G,exclude:M,maxEvidenceLines:J,redact:$.redact,explainScore:$.explainScore,noTimestamp:$.timestamp===!1,mode:W,testParity:$.testParity}),H;if($.since){if(U!=="json")c("--since requires --format json (other formats not supported in v1)"),process.exit(1);let z=await K({sincePath:$.since,currentReport:O,mode:W,base:q||null,head:V||null,only:G||null,exclude:M||null,sinceStrict:$.sinceStrict});H=$.pretty?JSON.stringify(z,null,2):JSON.stringify(z)}else switch(U){case"json":H=X(O,$.pretty);break;case"md":H=Q(O);break;case"text":H=Y(O);break}if($.out){let{writeFile:z,mkdir:N}=await import("node:fs/promises"),{dirname:j}=await import("node:path");await N(j($.out),{recursive:!0}),await z($.out,H,"utf-8"),l(`Risk report written to ${$.out}`)}else console.log(H);if(B!==void 0&&O.riskScore>=B){c(`Risk score ${O.riskScore} >= threshold ${B}`),process.exitCode=2;return}return}catch(Z){I1(Z)}});u1.command("zoom").description("Zoom into a specific finding or flag for detailed context").option("--finding <id>","Finding ID to zoom into").option("--flag <id>","Flag ID to zoom into").option("--mode <type>","Diff mode: branch|unstaged|staged|all","unstaged").option("--base <ref>","Base git reference (branch mode only; auto-detected if omitted)").option("--head <ref>","Head git reference (branch mode only; defaults to HEAD)").option("--profile <name>","Profile to use (auto|sveltekit|react|stencil|next)","auto").option("--format <type>","Output format: json|md|text","json").option("--unified <n>","Lines of unified context for patch hunks","3").option("--no-patch","Do not include patch context, only evidence").option("--max-evidence-lines <n>","Max evidence excerpt lines to show","8").option("--redact","Redact obvious secret values in evidence excerpts",!1).option("--out <path>","Write output to file instead of stdout").option("--pretty","Pretty-print JSON with 2-space indentation",!1).option("--no-timestamp","Omit generatedAt for deterministic output").action(async($)=>{try{let{executeZoom:Z}=await Promise.resolve().then(() => (C9(),P9)),{renderZoomJSON:X,renderZoomMarkdown:Q,renderZoomText:Y}=await Promise.resolve().then(() => S9),K=$.mode;if(!["branch","unstaged","staged","all"].includes(K))c(`Invalid mode: ${$.mode}. Use branch, unstaged, staged, or all.`),process.exit(1);let{base:W,head:q}=await b$({mode:K,base:$.base,head:$.head}),V=$.format;if(!["json","md","text"].includes(V))c(`Invalid format: ${$.format}. Use json, md, or text.`),process.exit(1);let U=parseInt($.unified,10);if(isNaN(U)||U<0)c(`Invalid unified context: ${$.unified}. Must be a non-negative integer.`),process.exit(1);let J=parseInt($.maxEvidenceLines,10);if(isNaN(J)||J<1)c(`Invalid max-evidence-lines: ${$.maxEvidenceLines}. Must be a positive integer.`),process.exit(1);let B=await i1({mode:K,base:W,head:q,includeUntracked:K==="all"||K==="unstaged"}),G=await Z(B,{findingId:$.finding,flagId:$.flag,mode:K,base:W,head:q,profile:$.profile,includePatch:$.patch!==!1,unified:U,maxEvidenceLines:J,redact:$.redact,noTimestamp:$.timestamp===!1}),M;switch(V){case"json":M=X(G,$.pretty);break;case"md":M=Q(G);break;case"text":M=Y(G);break}if($.out){let{writeFile:_,mkdir:O}=await import("node:fs/promises"),{dirname:H}=await import("node:path");await O(H($.out),{recursive:!0}),await _($.out,M,"utf-8"),l(`Zoom output written to ${$.out}`)}else console.log(M);return}catch(Z){I1(Z)}});u1.command("integrate [target]").description("Generate provider-specific rules (auto-detects when omitted)").option("--dry-run","Preview what would be written without creating files",!1).option("--force","Overwrite existing files",!1).action(async($,Z)=>{try{let{executeIntegrate:X}=await Promise.resolve().then(() => (n9(),i9));await X({target:$,dryRun:Z.dryRun,force:Z.force});return}catch(X){I1(X)}});var d$=u1.command("snap").description("Manage local workspace snapshots for agent iteration");d$.command("save [label]").description("Create a new snapshot of current workspace state").option("--out <path>","Write snapshotId to file instead of stdout").action(async($,Z)=>{try{let{executeSnapSave:X}=await Promise.resolve().then(() => (I$(),w$)),Q=await X({label:$,out:Z.out});if(!Z.out)console.log(Q.snapshotId);else l(`Snapshot ${Q.snapshotId} saved to ${Z.out}`);return}catch(X){I1(X)}});d$.command("list").description("List all snapshots").option("--pretty","Pretty-print JSON with 2-space indentation",!1).action(async($)=>{try{let{executeSnapList:Z,renderSnapListJSON:X}=await Promise.resolve().then(() => (I$(),w$)),Q=await Z();console.log(X(Q,$.pretty));return}catch(Z){I1(Z)}});d$.command("show <snapshotId>").description("Show snapshot details").option("--pretty","Pretty-print JSON with 2-space indentation",!1).action(async($,Z)=>{try{let{executeSnapShow:X,renderSnapShowJSON:Q}=await Promise.resolve().then(() => (I$(),w$)),Y=await X($);console.log(Q(Y,Z.pretty));return}catch(X){I1(X)}});d$.command("diff <idA> <idB>").description("Compare two snapshots").option("--pretty","Pretty-print JSON with 2-space indentation",!1).action(async($,Z,X)=>{try{let{executeSnapDiff:Q,renderSnapDiffJSON:Y}=await Promise.resolve().then(() => (I$(),w$)),K=await Q($,Z);console.log(Y(K,X.pretty));return}catch(Q){I1(Q)}});d$.command("restore <snapshotId>").description("Restore workspace to snapshot state (creates automatic backup first)").action(async($)=>{try{let{executeSnapRestore:Z}=await Promise.resolve().then(() => (I$(),w$)),X=await Z($);if(l(`Restored to snapshot ${X.snapshotId}`),l(`Pre-restore backup: ${X.backupSnapshotId}`),X.verified)l("Verification: passed");else J$("Verification: patch hashes differ (this may be expected for empty patches)");return}catch(Z){I1(Z)}});function I1($){if($ instanceof y)c(`Error: ${$.message}`),process.exit($.exitCode);if($ instanceof Error){if(c(`Unexpected error: ${$.message}`),process.env.DEBUG)c($.stack||"")}else c("An unexpected error occurred");process.exit(1)}await u1.parseAsync();
|