@maind-dev/mcp-bridge 0.67.0 → 0.69.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/build/index.js CHANGED
@@ -1,39 +1,39 @@
1
1
  #!/usr/bin/env node
2
- var _s=Object.defineProperty;var s=(e,t)=>_s(e,"name",{value:t,configurable:!0});var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var q=(e,t)=>{for(var n in t)_s(e,n,{get:t[n],enumerable:!0})};function ks(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let o={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(o.toolName=c)}}return o}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function Be(e,t,n){return JSON.stringify({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:n??`maind gateway: tool '${t}' is denied by local gateway policy. The call was not forwarded to the server. Remove the --deny-tool flag (or adjust the gateway policy) to allow it.`}],isError:!0}})}function $r(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function jr(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function Hr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Ur=_(()=>{"use strict";s(ks,"parseFrame");s(Be,"denyResult");s($r,"toolEvent");s(jr,"policyEvent");s(Hr,"shaEvent")});import{execFileSync as Es}from"node:child_process";function xs(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=uf}function pf(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let i=[];for(let o of cf){let a=r[o];typeof a=="string"&&vs.test(a)&&i.push({field:o,sha:a})}for(let[o,a]of lf){let c=r[o];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&vs.test(l)&&i.push({field:`${o}.${a}`,sha:l})}return i}function ff(e,t){let n=t(e);if(n===e)return{field:"",sha:e,verdict:"proven"};if(n!==null)return{field:"",sha:e,verdict:"unknown"};let r=e.slice(0,Ss);for(let i=Ss;i>=df;i--){let o=r.slice(0,i),a=t(o);if(a!==null&&a.startsWith(o))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function Ve(e,t){return e.verdict==="fabricated"?[`${t?"DENIED":"WARNING"}: the ${e.field} you passed (${e.sha}) does not exist in this repository,`,`but its prefix resolves to a real commit (${e.matchedPrefixOf}).`,"That combination cannot come from an unfetched object \u2014 it comes from completing an abbreviated hash.","Read the full hash instead of reconstructing it: `git rev-parse HEAD`, `git rev-parse <ref>`,","or `gh pr view <n> --json mergeCommit --jq .mergeCommit.oid`.",t?"The call was not forwarded.":"The call was forwarded \u2014 the record will carry an unverifiable hash."].join(" "):[`NOTE: the ${e.field} you passed (${e.sha}) could not be resolved in this repository.`,"That is often harmless \u2014 a fresh squash-merge commit, an unfetched branch, or a different repo in this workspace.","If you reconstructed it from an abbreviated hash, read the full one instead (`git rev-parse`, `gh --json`).","The call was forwarded."].join(" ")}function Rs(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"])delete e[t];return e}function un(e=process.cwd()){try{let n=Es("git",["rev-parse","--show-toplevel"],{cwd:e,env:Rs(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function mf(e){return t=>{try{let r=Es("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Rs(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function pn(e,t){if(t===null)return[];let n=pf(e);if(n.length===0)return[];let r=mf(t),i=[];for(let{field:o,sha:a}of n){let c=ff(a,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var cf,lf,vs,df,Ss,uf,Gr=_(()=>{"use strict";cf=["commit_sha","base_sha","head_sha"],lf=[["diff_stats","head_sha"],["diff_stats","base_sha"]],vs=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,df=7,Ss=12,uf=10;s(xs,"isDenyGrade");s(pf,"extractShaArgs");s(ff,"classifySha");s(Ve,"shaFindingText");s(Rs,"cleanGitEnv");s(un,"resolveRepoRootForSha");s(mf,"gitShaResolver");s(pn,"inspectLineForShas")});import{execFileSync as hf}from"node:child_process";import{createHash as gf}from"node:crypto";import{mkdirSync as yf,readFileSync as bf,renameSync as _f,writeFileSync as wf}from"node:fs";import{dirname as kf,join as As}from"node:path";function ae(e=process.cwd()){try{let t=hf("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function fn(e){return gf("sha256").update(e).digest("hex").slice(0,16)}function mn(e){return As(e,vf)}function Ts(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Is(e,t,n,r=new Date().toISOString()){try{if(!Ts(n))return;let i={version:Wr,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},o=mn(e);yf(kf(o),{recursive:!0});let a=`${o}.${process.pid}.tmp`;wf(a,JSON.stringify(i,null,2),"utf8"),_f(a,o)}catch{}}function Cs(e,t){try{let n=bf(mn(e),"utf8"),r=JSON.parse(n);return r.version!==Wr||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Ts(r.result)?null:{version:Wr,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function Ns(e,t,n=new Date){let r=Sf(t.cached_at,n),i=t.result.instructions??"",o={...t.result,instructions:`${r}
2
+ var Es=Object.defineProperty;var s=(e,t)=>Es(e,"name",{value:t,configurable:!0});var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var q=(e,t)=>{for(var n in t)Es(e,n,{get:t[n],enumerable:!0})};function Rs(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let o={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(o.toolName=c)}}return o}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function Be(e,t,n){return JSON.stringify({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:n??`maind gateway: tool '${t}' is denied by local gateway policy. The call was not forwarded to the server. Remove the --deny-tool flag (or adjust the gateway policy) to allow it.`}],isError:!0}})}function $r(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function jr(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function Hr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Ur=_(()=>{"use strict";s(Rs,"parseFrame");s(Be,"denyResult");s($r,"toolEvent");s(jr,"policyEvent");s(Hr,"shaEvent")});import{execFileSync as Is}from"node:child_process";function Cs(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=bf}function _f(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let i=[];for(let o of hf){let a=r[o];typeof a=="string"&&As.test(a)&&i.push({field:o,sha:a})}for(let[o,a]of gf){let c=r[o];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&As.test(l)&&i.push({field:`${o}.${a}`,sha:l})}return i}function wf(e,t){let n=t(e);if(n===e)return{field:"",sha:e,verdict:"proven"};if(n!==null)return{field:"",sha:e,verdict:"unknown"};let r=e.slice(0,Ts);for(let i=Ts;i>=yf;i--){let o=r.slice(0,i),a=t(o);if(a!==null&&a.startsWith(o))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function Ve(e,t){return e.verdict==="fabricated"?[`${t?"DENIED":"WARNING"}: the ${e.field} you passed (${e.sha}) does not exist in this repository,`,`but its prefix resolves to a real commit (${e.matchedPrefixOf}).`,"That combination cannot come from an unfetched object \u2014 it comes from completing an abbreviated hash.","Read the full hash instead of reconstructing it: `git rev-parse HEAD`, `git rev-parse <ref>`,","or `gh pr view <n> --json mergeCommit --jq .mergeCommit.oid`.",t?"The call was not forwarded.":"The call was forwarded \u2014 the record will carry an unverifiable hash."].join(" "):[`NOTE: the ${e.field} you passed (${e.sha}) could not be resolved in this repository.`,"That is often harmless \u2014 a fresh squash-merge commit, an unfetched branch, or a different repo in this workspace.","If you reconstructed it from an abbreviated hash, read the full one instead (`git rev-parse`, `gh --json`).","The call was forwarded."].join(" ")}function Ns(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"])delete e[t];return e}function un(e=process.cwd()){try{let n=Is("git",["rev-parse","--show-toplevel"],{cwd:e,env:Ns(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function kf(e){return t=>{try{let r=Is("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Ns(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function pn(e,t){if(t===null)return[];let n=_f(e);if(n.length===0)return[];let r=kf(t),i=[];for(let{field:o,sha:a}of n){let c=wf(a,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var hf,gf,As,yf,Ts,bf,Gr=_(()=>{"use strict";hf=["commit_sha","base_sha","head_sha"],gf=[["diff_stats","head_sha"],["diff_stats","base_sha"]],As=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,yf=7,Ts=12,bf=10;s(Cs,"isDenyGrade");s(_f,"extractShaArgs");s(wf,"classifySha");s(Ve,"shaFindingText");s(Ns,"cleanGitEnv");s(un,"resolveRepoRootForSha");s(kf,"gitShaResolver");s(pn,"inspectLineForShas")});import{execFileSync as vf}from"node:child_process";import{createHash as Sf}from"node:crypto";import{mkdirSync as Ef,readFileSync as xf,renameSync as Rf,writeFileSync as Af}from"node:fs";import{dirname as Tf,join as Ps}from"node:path";function ae(e=process.cwd()){try{let t=vf("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function fn(e){return Sf("sha256").update(e).digest("hex").slice(0,16)}function mn(e){return Ps(e,If)}function Ds(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Os(e,t,n,r=new Date().toISOString()){try{if(!Ds(n))return;let i={version:Wr,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},o=mn(e);Ef(Tf(o),{recursive:!0});let a=`${o}.${process.pid}.tmp`;Af(a,JSON.stringify(i,null,2),"utf8"),Rf(a,o)}catch{}}function Ms(e,t){try{let n=xf(mn(e),"utf8"),r=JSON.parse(n);return r.version!==Wr||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Ds(r.result)?null:{version:Wr,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function Fs(e,t,n=new Date){let r=Cf(t.cached_at,n),i=t.result.instructions??"",o={...t.result,instructions:`${r}
3
3
 
4
- ${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:o})}function Sf(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${Ef(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function Ef(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i} minute${i===1?"":"s"} ago`;let o=Math.floor(i/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let a=Math.floor(o/24);return`${a} day${a===1?"":"s"} ago`}var Wr,vf,qe=_(()=>{"use strict";Wr=1,vf=As(".maind","conventions-cache.json");s(ae,"resolveRepoRoot");s(fn,"keyFingerprint");s(mn,"cachePath");s(Ts,"hasInstructions");s(Is,"writeConventionsCache");s(Cs,"readConventionsCache");s(Ns,"buildCachedInitializeResponse");s(Sf,"fallbackMarker");s(Ef,"relativeAge")});import{existsSync as _n,mkdirSync as Ff,readFileSync as Ps,writeFileSync as Vr,chmodSync as Ds}from"node:fs";import{homedir as Lf,hostname as $f,platform as Br,release as jf}from"node:os";import{randomUUID as Hf}from"node:crypto";import{join as Se}from"node:path";function Tt(){let e=Lf(),t=process.env;if(Br()==="darwin")return Se(e,"Library","Application Support","maind");if(Br()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:Se(e,"AppData","Roaming");return Se(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:Se(e,".config");return Se(n,"maind")}function Os(e){_n(e)||Ff(e,{recursive:!0,mode:448})}function U(){let e=Tt();Os(e);let t=Se(e,Uf);if(_n(t)){let r=Ps(t,"utf8").trim();if(Kf(r))return r}let n=Hf();Vr(t,n+`
5
- `,{encoding:"utf8",mode:384});try{Ds(t,384)}catch{}return n}function Kf(e){return Wf.test(e)}function qr(){return Se(Tt(),Gf)}function Ee(e){let t=Tt();Os(t);let n=qr();Vr(n,e+`
6
- `,{encoding:"utf8",mode:384});try{Ds(n,384)}catch{}}function D(){let e=qr();if(!_n(e))return null;let t=Ps(e,"utf8").trim();return t.length>0?t:null}function It(){let e=qr();_n(e)&&Vr(e,"",{encoding:"utf8",mode:384})}function Ms(){try{return`mcp-bridge-${$f()}`}catch{return"mcp-bridge"}}function wn(e){return{os:`${Br()} ${jf()}`,ide:"mcp-bridge",ext_version:e,device_id:U()}}var Uf,Gf,Wf,B=_(()=>{"use strict";s(Tt,"configDir");s(Os,"ensureDir");Uf="device-id",Gf="api-key";s(U,"ensureDeviceId");Wf=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(Kf,"isUuid");s(qr,"apiKeyPath");s(Ee,"writeApiKey");s(D,"readApiKey");s(It,"clearApiKey");s(Ms,"bridgeLabel");s(wn,"clientMeta")});var P,xe=_(()=>{"use strict";P="0.67.0"});import{execFileSync as Zf}from"node:child_process";import{createHash as em}from"node:crypto";function tm(e){return em("sha256").update(e).digest("hex")}function nm(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function rm(e){let t=nm(e);return t?tm(t):null}function O(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&im.test(e))return e;let t;try{t=Zf("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?rm(t):null}var im,ge=_(()=>{"use strict";s(tm,"sha256Hex");s(nm,"normalizeRemoteUrl");s(rm,"projectKeyFromRemote");im=/^[a-f0-9]{64}$/;s(O,"computeProjectKey")});import sm from"node:path";import{fileURLToPath as am}from"node:url";function cm(e,t=sm.sep){return e.split(t).includes("_npx")}function ee(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",Vs,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):cm(e.entryPath,e.sep)?n("bridge is running from the npx cache (install it globally to pin a path)"):e.nodePath?{command:e.nodePath,args:[e.entryPath,...t],env:e.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},fallbackReason:null}:n("node executable path unavailable")}function te(){try{let e=am(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Je(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Bs(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Bs(n)).join(" ")}function vn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Vs)}function Sn(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Bs(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Vs,Ye=_(()=>{"use strict";Vs="@maind-dev/mcp-bridge";s(cm,"isEphemeralEntry");s(ee,"resolveBridgeLaunch");s(te,"currentBridgeEntry");s(Je,"launchToShellCommand");s(vn,"isNpxForm");s(Sn,"isLegacyHookForm");s(Bs,"shellQuote")});import*as M from"node:fs/promises";import*as En from"node:path";async function G(e){try{return await M.readFile(e,"utf8")}catch(t){if(dm(t))return null;throw t}}async function zr(e){await M.mkdir(e,{recursive:!0})}async function F(e,t,n){let r=En.dirname(e);await zr(r);let i=En.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await M.writeFile(i,t,{encoding:"utf8",mode:n});try{await M.rename(i,e)}catch(o){if(um(o))try{await M.copyFile(i,e),await M.unlink(i).catch(()=>{}),n!==void 0&&await M.chmod(e,n).catch(()=>{});return}catch(a){throw await M.unlink(i).catch(()=>{}),a}throw await M.unlink(i).catch(()=>{}),o}}async function Qs(e,t){let n=await G(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function dm(e){return Zs(e)&&e.code==="ENOENT"}function um(e){return!Zs(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function Zs(e){return typeof e=="object"&&e!==null&&"code"in e}var ce=_(()=>{"use strict";s(G,"readFileSafe");s(zr,"ensureDir");s(F,"atomicWriteFile");s(Qs,"hasLinePrefix");s(dm,"isNoEnt");s(um,"isWindowsRenameFailure");s(Zs,"isNodeError")});import{existsSync as Tm}from"node:fs";import*as oa from"node:path";function Dt(e,t={},n=Qr){let r=t.fileExists??Tm,i=t.expectedCommand??Im,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Xr(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=Cm(o,a.event,a.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let u=` Replace its command with: ${i(a.subcommand)}`;if(Sn(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+u};if(vn(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+u};let d=Nm(l);return d!==null&&!r(d)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${d}, which does not exist \u2014 the hook fails silently on every run.`+u}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function Zr(e){return e.some(t=>t.status!=="ok")}function An(e){return e.some(t=>t.remedy==="run-install")}function Im(e){return Je(ee({entryPath:te(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function Cm(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Xr(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Xr(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function Nm(e){for(let t of Pm(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return oa.isAbsolute(t)?t:null;return null}function Pm(e){let t=[],n="",r=!1;for(let i of e){if(i==="'"){r=!r;continue}if(!r&&/\s/.test(i)){n.length>0&&t.push(n),n="";continue}n+=i}return n.length>0&&t.push(n),t}function Xr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Qr,Rn,Ot=_(()=>{"use strict";Ye();Qr=[{event:"SessionStart",subcommand:"on-session-start",label:"SessionStart hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-session-start' \u2014 opens a tracked session so duration and tool-call counts can be measured. Writes only to ~/.maind/state.json; nothing leaves the machine here."},{event:"PreToolUse",subcommand:"on-tool-use",label:"PreToolUse hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-tool-use' before every tool call \u2014 counts calls, and warns you on stderr when the session's token usage crosses your handoff thresholds (ADR-039). Only the tool NAME is read, never its arguments."},{event:"PreToolUse",subcommand:"on-file-write",label:"PreToolUse write-guard hook",timeout:5,matcher:"Write",consentDescription:"It runs 'maind-mcp-bridge on-file-write' before the Write tool creates a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents, never any other tool's arguments \u2014 to check whether a numbered filename (ADR-262-\u2026, 0001-\u2026, RFC-12-\u2026) would claim a number a sibling branch or worktree already holds, and blocks that one Write while naming the next free number (ADR-263). Runs entirely on this machine (git + fs); nothing is uploaded. This is a SEPARATE hook from on-tool-use precisely because it reads an argument, which that one promises not to."},{event:"PreToolUse",subcommand:"on-file-edit",label:"PreToolUse edit-guard hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-file-edit' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares it LOCALLY against the cached peer view from this machine's own presence announces (~/.maind/presence/): when another of your sessions holds a claim or works on the same directory, it INFORMS the agent with who/where/how-fresh. The path never leaves the machine; the hook never blocks a tool call (advisory only, ADR-277). This is a SEPARATE hook from on-file-write because that one's consent covers Write alone and may deny; this one covers Edit+Write and never does."},{event:"PreToolUse",subcommand:"on-repo-health",label:"PreToolUse repo-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-repo-health' before the Edit and Write tools, and before those only \u2014 at most ONCE per session and repository, not on every call. It reads the target file PATH (never the file's contents) to find which repository you are editing, then inspects THAT repository with git and the filesystem: is a machine-local tooling file present in the main checkout but missing in this worktree, were dependencies never installed here, is a build older than its source, are you mid-rebase, on a detached HEAD, editing the shared base tree, or are checked-in git hooks not actually wired? Everything stays on this machine; no network call, and no file contents are read or stored. It only ever adds a note for the model and NEVER blocks a tool call. Separately consented from the other Edit/Write hooks because it inspects the repository, not just the path."},{event:"PostToolUse",subcommand:"on-write-health",label:"PostToolUse write-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-write-health' AFTER the Edit and Write tools, and after those only. It reads the target file PATH to decide which checks that path makes relevant, and then \u2014 this is the wider promise, which is why it is consented separately \u2014 READS THE REPOSITORY'S TRACKED SOURCE FILES FROM DISK to run them: is a registry still consistent with the design artefact it implements (only if this repo declares such a contract in .maind/spec-contracts.json), does a Tailwind class point at a theme token that does not exist (only if this repo declares theme tokens), does a new Supabase migration leave default grants in place (only if this repo has migrations). A repository without those things stays silent. File contents are read, parsed and discarded; nothing is stored and nothing is uploaded. Each finding is reported to the model at most ONCE per session, only for findings THIS branch introduces, and the hook can never block or undo an edit \u2014 PostToolUse fires after the tool has already run."},{event:"Stop",subcommand:"on-session-end",label:"Stop hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end, and flushes the session's Tier-3 counters. Gated by Tier-3 consent server-side."},{event:"Stop",subcommand:"on-index-refresh",label:"Stop index-refresh hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-index-refresh' at the end of a turn, and refreshes this repository's local code index so codebase search, trace, map, history and review answer from the current tree instead of a stale snapshot. This one READS YOUR SOURCE FILES \u2014 the ones git reports as changed \u2014 parses them, and writes symbol names and line spans to .maind/code-index.sqlite inside the repository. That is a wider promise than the other hooks make, which is why it is consented separately. Everything stays on this machine; nothing is uploaded, and no file contents are stored. It returns immediately (the work runs detached), holds one run per repository at a time, and only refreshes an index that already exists \u2014 the first build stays an explicit 'codebase_index' call."}],Rn=[{event:"SessionStart",subcommand:"guard-inject",label:"Guard inject hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-inject' when a session starts (ADR-284 guard). UNLIKE every other hook, this one talks to the maind server: it fetches your session briefing from mcp.maind.dev \u2014 sending your API key, device id, project key, and the client family 'claude-code'; never file contents, never paths \u2014 and injects the result into the session context, so the briefing no longer depends on the model remembering to ask. Cache-first (~12h), so most session starts add no network call. Inactive (exit 0, no output) while guard mode is off."},{event:"PreToolUse",subcommand:"guard-gate",label:"Guard gate hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-gate' before the Edit and Write tools, and before those only. It reads the tool NAME and the session id \u2014 never the tool's arguments, never file contents \u2014 and checks LOCALLY whether this session has been briefed (injection or a maind consultation call). Warn mode (default) adds one reminder line for the model and never blocks; block mode (explicit opt-in via 'guard mode block') may DENY an un-briefed edit, naming the reason and a logged override command. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-stop",label:"Guard stop hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-stop' when the session tries to finish. Only with the strict stop-gate enabled ('guard_stop_gate': true \u2014 off by default) and edits made without a review_changes run, it blocks the FIRST stop attempt with a reason so the review can happen; it never blocks twice. Reads only local state; nothing leaves the machine. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-cross-observe",label:"Guard cross-session observe hook",timeout:5,matcher:"Read|Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-observe' after the Read, Edit and Write tools, and after those only. It reads the target file PATH \u2014 never the file's contents \u2014 stats its modification time, and records it as this session's baseline in ~/.maind/cross-session/ (local file, TTL-pruned). That baseline is what lets the check hook detect when a parallel session, an editor, or git changes a file under you. Nothing leaves the machine. Inactive while guard mode is off."},{event:"PreToolUse",subcommand:"guard-cross-check",label:"Guard cross-session check hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-check' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares the file's current modification time against the baseline this session last observed. If the file changed outside the session (parallel session, editor, git checkout/pull), warn mode adds one advisory telling the model to re-read and reconcile; block mode ('guard mode block') DENIES that one edit with the same instruction. Runs entirely on this machine. Inactive while guard mode is off."}];s(Dt,"inspectHookWiring");s(Zr,"hasWiringDrift");s(An,"needsInstallRun");s(Im,"defaultExpectedCommand");s(Cm,"findCommand");s(Nm,"extractScriptPath");s(Pm,"tokenize");s(Xr,"isObject")});import*as ni from"node:path";import*as aa from"node:readline";async function ca(e,t){let n=ni.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let i;try{i=await G(n)}catch(m){return{target:r,action:"merge",status:"failed",detail:`read: ${ei(m)}`}}let o,a="create";if(i===null||i.trim().length===0)o={};else{a="merge";try{let m=JSON.parse(i);if(!ti(m))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};o=m}catch(m){return{target:r,action:"merge",status:"failed",detail:`parse: ${ei(m)}`}}}let c=Om(o,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:a==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await Mm(e.out,`
4
+ ${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:o})}function Cf(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${Nf(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function Nf(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i} minute${i===1?"":"s"} ago`;let o=Math.floor(i/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let a=Math.floor(o/24);return`${a} day${a===1?"":"s"} ago`}var Wr,If,qe=_(()=>{"use strict";Wr=1,If=Ps(".maind","conventions-cache.json");s(ae,"resolveRepoRoot");s(fn,"keyFingerprint");s(mn,"cachePath");s(Ds,"hasInstructions");s(Os,"writeConventionsCache");s(Ms,"readConventionsCache");s(Fs,"buildCachedInitializeResponse");s(Cf,"fallbackMarker");s(Nf,"relativeAge")});import{existsSync as _n,mkdirSync as Wf,readFileSync as Ls,writeFileSync as Vr,chmodSync as $s}from"node:fs";import{homedir as Kf,hostname as Bf,platform as Br,release as Vf}from"node:os";import{randomUUID as qf}from"node:crypto";import{join as Se}from"node:path";function Tt(){let e=Kf(),t=process.env;if(Br()==="darwin")return Se(e,"Library","Application Support","maind");if(Br()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:Se(e,"AppData","Roaming");return Se(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:Se(e,".config");return Se(n,"maind")}function js(e){_n(e)||Wf(e,{recursive:!0,mode:448})}function U(){let e=Tt();js(e);let t=Se(e,zf);if(_n(t)){let r=Ls(t,"utf8").trim();if(Xf(r))return r}let n=qf();Vr(t,n+`
5
+ `,{encoding:"utf8",mode:384});try{$s(t,384)}catch{}return n}function Xf(e){return Yf.test(e)}function qr(){return Se(Tt(),Jf)}function Ee(e){let t=Tt();js(t);let n=qr();Vr(n,e+`
6
+ `,{encoding:"utf8",mode:384});try{$s(n,384)}catch{}}function O(){let e=qr();if(!_n(e))return null;let t=Ls(e,"utf8").trim();return t.length>0?t:null}function It(){let e=qr();_n(e)&&Vr(e,"",{encoding:"utf8",mode:384})}function Hs(){try{return`mcp-bridge-${Bf()}`}catch{return"mcp-bridge"}}function wn(e){return{os:`${Br()} ${Vf()}`,ide:"mcp-bridge",ext_version:e,device_id:U()}}var zf,Jf,Yf,B=_(()=>{"use strict";s(Tt,"configDir");s(js,"ensureDir");zf="device-id",Jf="api-key";s(U,"ensureDeviceId");Yf=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(Xf,"isUuid");s(qr,"apiKeyPath");s(Ee,"writeApiKey");s(O,"readApiKey");s(It,"clearApiKey");s(Hs,"bridgeLabel");s(wn,"clientMeta")});var P,xe=_(()=>{"use strict";P="0.69.0"});import{execFileSync as sm}from"node:child_process";import{createHash as am}from"node:crypto";function cm(e){return am("sha256").update(e).digest("hex")}function lm(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function zr(e){let t=lm(e);return t?cm(t):null}function M(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&dm.test(e))return e;let t;try{t=sm("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?zr(t):null}var dm,ge=_(()=>{"use strict";s(cm,"sha256Hex");s(lm,"normalizeRemoteUrl");s(zr,"projectKeyFromRemote");dm=/^[a-f0-9]{64}$/;s(M,"computeProjectKey")});import pm from"node:path";import{fileURLToPath as fm}from"node:url";function mm(e,t=pm.sep){return e.split(t).includes("_npx")}function ee(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",Xs,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):mm(e.entryPath,e.sep)?n("bridge is running from the npx cache (install it globally to pin a path)"):e.nodePath?{command:e.nodePath,args:[e.entryPath,...t],env:e.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},fallbackReason:null}:n("node executable path unavailable")}function te(){try{let e=fm(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Je(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Ys(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Ys(n)).join(" ")}function vn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Xs)}function Sn(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Ys(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Xs,Ye=_(()=>{"use strict";Xs="@maind-dev/mcp-bridge";s(mm,"isEphemeralEntry");s(ee,"resolveBridgeLaunch");s(te,"currentBridgeEntry");s(Je,"launchToShellCommand");s(vn,"isNpxForm");s(Sn,"isLegacyHookForm");s(Ys,"shellQuote")});import*as F from"node:fs/promises";import*as En from"node:path";async function G(e){try{return await F.readFile(e,"utf8")}catch(t){if(gm(t))return null;throw t}}async function Jr(e){await F.mkdir(e,{recursive:!0})}async function L(e,t,n){let r=En.dirname(e);await Jr(r);let i=En.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await F.writeFile(i,t,{encoding:"utf8",mode:n});try{await F.rename(i,e)}catch(o){if(ym(o))try{await F.copyFile(i,e),await F.unlink(i).catch(()=>{}),n!==void 0&&await F.chmod(e,n).catch(()=>{});return}catch(a){throw await F.unlink(i).catch(()=>{}),a}throw await F.unlink(i).catch(()=>{}),o}}async function ra(e,t){let n=await G(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function gm(e){return ia(e)&&e.code==="ENOENT"}function ym(e){return!ia(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function ia(e){return typeof e=="object"&&e!==null&&"code"in e}var ce=_(()=>{"use strict";s(G,"readFileSafe");s(Jr,"ensureDir");s(L,"atomicWriteFile");s(ra,"hasLinePrefix");s(gm,"isNoEnt");s(ym,"isWindowsRenameFailure");s(ia,"isNodeError")});import{existsSync as Om}from"node:fs";import*as da from"node:path";function Dt(e,t={},n=Zr){let r=t.fileExists??Om,i=t.expectedCommand??Mm,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Qr(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=Fm(o,a.event,a.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let p=` Replace its command with: ${i(a.subcommand)}`;if(Sn(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+p};if(vn(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+p};let d=Lm(l);return d!==null&&!r(d)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${d}, which does not exist \u2014 the hook fails silently on every run.`+p}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function ei(e){return e.some(t=>t.status!=="ok")}function An(e){return e.some(t=>t.remedy==="run-install")}function Mm(e){return Je(ee({entryPath:te(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function Fm(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Qr(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Qr(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function Lm(e){for(let t of $m(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return da.isAbsolute(t)?t:null;return null}function $m(e){let t=[],n="",r=!1;for(let i of e){if(i==="'"){r=!r;continue}if(!r&&/\s/.test(i)){n.length>0&&t.push(n),n="";continue}n+=i}return n.length>0&&t.push(n),t}function Qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Zr,Rn,Ot=_(()=>{"use strict";Ye();Zr=[{event:"SessionStart",subcommand:"on-session-start",label:"SessionStart hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-session-start' \u2014 opens a tracked session so duration and tool-call counts can be measured. Writes only to ~/.maind/state.json; nothing leaves the machine here."},{event:"PreToolUse",subcommand:"on-tool-use",label:"PreToolUse hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-tool-use' before every tool call \u2014 counts calls, and warns you on stderr when the session's token usage crosses your handoff thresholds (ADR-039). Only the tool NAME is read, never its arguments."},{event:"PreToolUse",subcommand:"on-file-write",label:"PreToolUse write-guard hook",timeout:5,matcher:"Write",consentDescription:"It runs 'maind-mcp-bridge on-file-write' before the Write tool creates a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents, never any other tool's arguments \u2014 to check whether a numbered filename (ADR-262-\u2026, 0001-\u2026, RFC-12-\u2026) would claim a number a sibling branch or worktree already holds, and blocks that one Write while naming the next free number (ADR-263). Runs entirely on this machine (git + fs); nothing is uploaded. This is a SEPARATE hook from on-tool-use precisely because it reads an argument, which that one promises not to."},{event:"PreToolUse",subcommand:"on-file-edit",label:"PreToolUse edit-guard hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-file-edit' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares it LOCALLY against the cached peer view from this machine's own presence announces (~/.maind/presence/): when another of your sessions holds a claim or works on the same directory, it INFORMS the agent with who/where/how-fresh. The path never leaves the machine; the hook never blocks a tool call (advisory only, ADR-277). This is a SEPARATE hook from on-file-write because that one's consent covers Write alone and may deny; this one covers Edit+Write and never does."},{event:"PreToolUse",subcommand:"on-repo-health",label:"PreToolUse repo-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-repo-health' before the Edit and Write tools, and before those only \u2014 at most ONCE per session and repository, not on every call. It reads the target file PATH (never the file's contents) to find which repository you are editing, then inspects THAT repository with git and the filesystem: is a machine-local tooling file present in the main checkout but missing in this worktree, were dependencies never installed here, is a build older than its source, are you mid-rebase, on a detached HEAD, editing the shared base tree, or are checked-in git hooks not actually wired? Everything stays on this machine; no network call, and no file contents are read or stored. It only ever adds a note for the model and NEVER blocks a tool call. Separately consented from the other Edit/Write hooks because it inspects the repository, not just the path."},{event:"PostToolUse",subcommand:"on-write-health",label:"PostToolUse write-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-write-health' AFTER the Edit and Write tools, and after those only. It reads the target file PATH to decide which checks that path makes relevant, and then \u2014 this is the wider promise, which is why it is consented separately \u2014 READS THE REPOSITORY'S TRACKED SOURCE FILES FROM DISK to run them: is a registry still consistent with the design artefact it implements (only if this repo declares such a contract in .maind/spec-contracts.json), does a Tailwind class point at a theme token that does not exist (only if this repo declares theme tokens), does a new Supabase migration leave default grants in place (only if this repo has migrations). A repository without those things stays silent. File contents are read, parsed and discarded; nothing is stored and nothing is uploaded. Each finding is reported to the model at most ONCE per session, only for findings THIS branch introduces, and the hook can never block or undo an edit \u2014 PostToolUse fires after the tool has already run."},{event:"Stop",subcommand:"on-session-end",label:"Stop hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end, and flushes the session's Tier-3 counters. Gated by Tier-3 consent server-side."},{event:"Stop",subcommand:"on-index-refresh",label:"Stop index-refresh hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-index-refresh' at the end of a turn, and refreshes this repository's local code index so codebase search, trace, map, history and review answer from the current tree instead of a stale snapshot. This one READS YOUR SOURCE FILES \u2014 the ones git reports as changed \u2014 parses them, and writes symbol names and line spans to .maind/code-index.sqlite inside the repository. That is a wider promise than the other hooks make, which is why it is consented separately. Everything stays on this machine; nothing is uploaded, and no file contents are stored. It returns immediately (the work runs detached), holds one run per repository at a time, and only refreshes an index that already exists \u2014 the first build stays an explicit 'codebase_index' call."}],Rn=[{event:"SessionStart",subcommand:"guard-inject",label:"Guard inject hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-inject' when a session starts (ADR-284 guard). UNLIKE every other hook, this one talks to the maind server: it fetches your session briefing from mcp.maind.dev \u2014 sending your API key, device id, project key, and the client family 'claude-code'; never file contents, never paths \u2014 and injects the result into the session context, so the briefing no longer depends on the model remembering to ask. Cache-first (~12h), so most session starts add no network call. Inactive (exit 0, no output) while guard mode is off."},{event:"PreToolUse",subcommand:"guard-gate",label:"Guard gate hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-gate' before the Edit and Write tools, and before those only. It reads the tool NAME and the session id \u2014 never the tool's arguments, never file contents \u2014 and checks LOCALLY whether this session has been briefed (injection or a maind consultation call). Warn mode (default) adds one reminder line for the model and never blocks; block mode (explicit opt-in via 'guard mode block') may DENY an un-briefed edit, naming the reason and a logged override command. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-stop",label:"Guard stop hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-stop' when the session tries to finish. Only with the strict stop-gate enabled ('guard_stop_gate': true \u2014 off by default) and edits made without a review_changes run, it blocks the FIRST stop attempt with a reason so the review can happen; it never blocks twice. Reads only local state; nothing leaves the machine. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-cross-observe",label:"Guard cross-session observe hook",timeout:5,matcher:"Read|Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-observe' after the Read, Edit and Write tools, and after those only. It reads the target file PATH \u2014 never the file's contents \u2014 stats its modification time, and records it as this session's baseline in ~/.maind/cross-session/ (local file, TTL-pruned). That baseline is what lets the check hook detect when a parallel session, an editor, or git changes a file under you. Nothing leaves the machine. Inactive while guard mode is off."},{event:"PreToolUse",subcommand:"guard-cross-check",label:"Guard cross-session check hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-check' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares the file's current modification time against the baseline this session last observed. If the file changed outside the session (parallel session, editor, git checkout/pull), warn mode adds one advisory telling the model to re-read and reconcile; block mode ('guard mode block') DENIES that one edit with the same instruction. Runs entirely on this machine. Inactive while guard mode is off."}];s(Dt,"inspectHookWiring");s(ei,"hasWiringDrift");s(An,"needsInstallRun");s(Mm,"defaultExpectedCommand");s(Fm,"findCommand");s(Lm,"extractScriptPath");s($m,"tokenize");s(Qr,"isObject")});import*as ri from"node:path";import*as pa from"node:readline";async function fa(e,t){let n=ri.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let i;try{i=await G(n)}catch(f){return{target:r,action:"merge",status:"failed",detail:`read: ${ti(f)}`}}let o,a="create";if(i===null||i.trim().length===0)o={};else{a="merge";try{let f=JSON.parse(i);if(!ni(f))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};o=f}catch(f){return{target:r,action:"merge",status:"failed",detail:`parse: ${ti(f)}`}}}let c=Hm(o,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:a==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await Um(e.out,`
7
7
  Merge a ${t.event} hook into ${n}?
8
8
  ${t.consentDescription}
9
- [Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},u=o.hooks?.[t.event]??[],d={...o,hooks:{...o.hooks??{},[t.event]:[...u,l]}},p=JSON.stringify(d,null,2)+`
10
- `;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:n};try{await F(n,p,384)}catch(m){return{target:r,action:"merge",status:"failed",detail:`write: ${ei(m)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function la(e){let t=ni.join(e.homeDir,sa);return ca(e,{event:"SessionStart",command:`cat ${t}`,timeout:5,matchPattern:/maind-session-start-reminder\.md/,targetKey:"hook:~/.claude/settings.json",skipDetail:s(()=>"SessionStart hook already references the reminder file","skipDetail"),consentDescription:`It 'cat's ${sa} into every new Claude Code session.`})}function Dm(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function ri(e,t){let n=e.launch??ee({entryPath:te(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=Je(n);return ca(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:Dm(t),skipDetail:s(i=>{let o=`${t.label} already runs maind ${t.subcommand}`;return Sn(i)?`${o}, but via the retired @maind/claude-code-hook \u2014 the bridge now owns that subcommand and that package is not published. Replace its command with: ${r}`:vn(i)?`${o}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:o},"skipDetail"),consentDescription:t.consentDescription})}async function da(e){let t=[];for(let n of Qr)t.push(await ri(e,n));return t}function Om(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!ti(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!ti(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function Mm(e,t){e.write(t);let n=aa.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function ti(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ei(e){return e instanceof Error?e.message:String(e)}var sa,ii=_(()=>{"use strict";ce();Ye();Ot();sa=".claude/maind-session-start-reminder.md";s(ca,"mergeClaudeHook");s(la,"mergeSessionStartHook");s(Dm,"targetKeyFor");s(ri,"mergeSubcommandHook");s(da,"mergeAllSubcommandHooks");s(Om,"findExistingHookCommand");s(Mm,"promptYesNo");s(ti,"isObject");s(ei,"errMessage")});import{existsSync as Fm,readFileSync as Lm}from"node:fs";import{join as $m}from"node:path";function de(){return $m(Tt(),"config.json")}function ne(){try{let e=de();if(!Fm(e))return null;let t=JSON.parse(Lm(e,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r={};return typeof n.auto_announce=="boolean"&&(r.auto_announce=n.auto_announce),typeof n.machine_label=="string"&&(r.machine_label=n.machine_label),typeof n.auto_working_paths=="boolean"&&(r.auto_working_paths=n.auto_working_paths),(n.guard_mode==="off"||n.guard_mode==="warn"||n.guard_mode==="block")&&(r.guard_mode=n.guard_mode),typeof n.guard_stop_gate=="boolean"&&(r.guard_stop_gate=n.guard_stop_gate),(n.gateway_mode==="off"||n.gateway_mode==="warn"||n.gateway_mode==="enforce")&&(r.gateway_mode=n.gateway_mode),typeof n.gateway_attest=="boolean"&&(r.gateway_attest=n.gateway_attest),(n.gateway_sha_proof==="off"||n.gateway_sha_proof==="warn"||n.gateway_sha_proof==="enforce")&&(r.gateway_sha_proof=n.gateway_sha_proof),r}catch{return null}}var Xe=_(()=>{"use strict";B();s(de,"bridgeConfigPath");s(ne,"readBridgeConfig")});import{execFileSync as Vm}from"node:child_process";import{createHash as qm}from"node:crypto";function oi(e){return qm("sha256").update(e).digest("hex")}function zm(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function Jm(e){let t=zm(e);return t?oi(t):null}function Xm(e){return typeof e=="string"&&Ym.test(e)}function ba(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(Xm(t))return t;let n;try{n=Vm("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?Jm(n):null}var Ym,si=_(()=>{"use strict";s(oi,"sha256Hex");s(zm,"normalizeRemoteUrl");s(Jm,"projectKeyFromRemote");Ym=/^[a-f0-9]{64}$/;s(Xm,"isProjectKey");s(ba,"computeProjectKey")});function Tn(e){return`${e}#<module>`}function In(e,t,n){return`${e}#${t}:${n}`}var Mt=_(()=>{"use strict";s(Tn,"moduleKey");s(In,"symbolKey")});function Cn(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}function ai(e){return e.toLowerCase().endsWith(".d.ts")}var Nn=_(()=>{"use strict";s(Cn,"languageForPath");s(ai,"isSkippablePath")});function Pn(){return{nodes:[],edges:[],refs:[],imports:[]}}function _e(e){return e+1}function Dn(e){return(e.text.split(`
11
- `,1)[0]??"").trim().slice(0,200)}function Qm(e){if(!e)return null;switch(e.type){case"identifier":case"property_identifier":case"type_identifier":return e.text;case"member_expression":return e.childForFieldName("property")?.text??null;case"attribute":return e.childForFieldName("attribute")?.text??null;default:return null}}function Zm(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=Qm(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Qe(e,t,n,r){for(let i of Zm(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}var On=_(()=>{"use strict";s(Pn,"newResult");s(_e,"line1");s(Dn,"signatureOf");s(Qm,"calleeName");s(Zm,"collectCallTargets");s(Qe,"addCallRefs")});function wa(e,t){let n=Pn();for(let r of e.namedChildren)eh(r,t,n);return n}function ka(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function eh(e,t,n){let r=ka(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??nh(r);o&&n.imports.push({fromModuleKey:t.moduleKey,specifier:o});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let o=Mn(r,t,i,i,"function");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&Qe(n,o.nodeKey,a,_a);return}case"class_definition":th(r,t,n);return;case"expression_statement":{let o=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(o&&o.type==="identifier"){let a=Mn(r,t,o.text,o.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function th(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Mn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let o=e.childForFieldName("superclasses");if(o){for(let c of o.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=ka(c);if(l.type!=="function_definition")continue;let u=l.childForFieldName("name")?.text;if(!u)continue;let d=`${r}.${u}`,p=Mn(l,t,u,d,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let m=l.childForFieldName("body");m&&Qe(n,p.nodeKey,m,_a)}}function Mn(e,t,n,r,i){return{nodeKey:In(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:_e(e.startPosition.row),endLine:_e(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Dn(e),doc:null}}function nh(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var _a,va=_(()=>{"use strict";Mt();On();_a="call";s(wa,"extractPython");s(ka,"unwrapDecorated");s(eh,"handleTopLevel");s(th,"addClass");s(Mn,"makeNode");s(nh,"firstDottedName")});function xa(e,t){let n=Pn();for(let r of e.namedChildren)ih(r,t,n);return n}function rh(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function ih(e,t,n){let r=rh(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:sh(i)});return}case"function_declaration":case"generator_function_declaration":{Sa(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{oh(r,t,n);return}case"interface_declaration":ci(r,t,n,"interface");return;case"type_alias_declaration":ci(r,t,n,"type_alias");return;case"enum_declaration":ci(r,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let i of r.namedChildren){if(i.type!=="variable_declarator")continue;let o=i.childForFieldName("name");if(!o||o.type!=="identifier")continue;let a=i.childForFieldName("value"),c=a?.type==="arrow_function"||a?.type==="function_expression"||a?.type==="function";Sa(i,t,n,c?"function":"variable",o,a)}return}default:return}}function Sa(e,t,n,r,i,o){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=Fn(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let u=o??e.childForFieldName("body")??e;r==="function"&&u&&Qe(n,l.nodeKey,u,Ea)}function ci(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=Fn(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}function oh(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Fn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let a of e.descendantsOfType("class_heritage"))for(let c of a.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let u of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text});for(let u of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text})}let o=e.childForFieldName("body");if(o)for(let a of o.namedChildren){if(a.type!=="method_definition")continue;let c=a.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,u=Fn(a,t,c,l,"method");n.nodes.push(u),n.edges.push({srcKey:i.nodeKey,dstKey:u.nodeKey,kind:"contains"});let d=a.childForFieldName("body");d&&Qe(n,u.nodeKey,d,Ea)}}function Fn(e,t,n,r,i){return{nodeKey:In(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:_e(e.startPosition.row),endLine:_e(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Dn(e),doc:null}}function sh(e){return e.replace(/^["'`]|["'`]$/g,"")}var Ea,Ra=_(()=>{"use strict";Mt();On();Ea="call_expression";s(xa,"extractTypescript");s(rh,"unwrapExport");s(ih,"handleTopLevel");s(Sa,"addFunctionLike");s(ci,"addSimpleNamed");s(oh,"addClass");s(Fn,"makeNode");s(sh,"stripQuotes")});import{createRequire as ah}from"node:module";import{join as ch}from"node:path";function Ia(e,t){return t?ch(t,Aa[e]):ah(import.meta.url).resolve(`tree-sitter-wasms/out/${Aa[e]}`)}var Aa,Ta,Ca=_(()=>{"use strict";Aa={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Ta="tree-sitter.wasm";s(Ia,"grammarPath")});import{join as lh}from"node:path";import li from"web-tree-sitter";var dh,Ln,Na=_(()=>{"use strict";Mt();Nn();va();Ra();On();Ca();dh=["typescript","tsx","javascript","python"],Ln=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await li.init(this.assetDir?{locateFile:s(t=>lh(this.assetDir,t||Ta),"locateFile")}:void 0),this.parser=new li,this.initialized=!0)}supports(t){return dh.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let o=i.parse(n);if(!o)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[]};let a=o.rootNode,c=Tn(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:_e(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:c},d=r==="python"?wa(a,u):xa(a,u);return o.delete(),{filePath:t,language:r,nodes:[l,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await li.Language.load(Ia(t,this.assetDir)),this.grammars.set(t,n)),n}}});function Pa(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
12
- `).slice(0,1e3)}var Da=_(()=>{"use strict";s(Pa,"nodeEmbedText")});var di,ui=_(()=>{"use strict";di=["function","method","class","interface","enum","type_alias"]});function Oa(e,t){let n=Math.min(e.length,t.length),r=0,i=0,o=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,i+=c*c,o+=l*l}return i===0||o===0?0:r/(Math.sqrt(i)*Math.sqrt(o))}var Ma=_(()=>{"use strict";s(Oa,"cosineSimilarity")});import{posix as pi}from"node:path";function Fa(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!uh.has(r.kind))continue;let i=t.get(r.name);i?i.push(r.nodeKey):t.set(r.name,[r.nodeKey])}return{nameToKeys:t,files:n}}function La(e,t){let n=new Set,r=[],i=new Set,o=s((a,c,l)=>{if(a===c)return;let u=`${a}\0${c}\0${l}`;n.has(u)||(n.add(u),r.push({srcKey:a,dstKey:c,kind:l}),i.add(a))},"push");for(let a of e.edges)o(a.srcKey,a.dstKey,a.kind);for(let a of e.nodes)i.add(a.nodeKey);for(let a of e.refs){let c=t.nameToKeys.get(a.targetName);!c||c.length!==1||o(a.fromKey,c[0],a.kind)}for(let a of e.imports){let c=ph(e.filePath,a.specifier,t.files);c&&o(a.fromModuleKey,Tn(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}function ph(e,t,n){if(!t.startsWith("."))return null;let r=pi.normalize(pi.join(pi.dirname(e),t)),i=[],o=$n.some(c=>r.endsWith(c));o&&i.push(r);let a=/\.(js|jsx|mjs|cjs)$/.exec(r);if(a){let c=r.slice(0,-a[0].length);for(let l of $n)i.push(c+l)}if(!o){for(let c of $n)i.push(r+c);for(let c of $n)i.push(`${r}/index${c}`)}for(let c of i)if(n.has(c))return c;return null}var uh,$n,$a=_(()=>{"use strict";Mt();uh=new Set(["function","method","class","interface","enum","type_alias"]),$n=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];s(Fa,"buildResolutionIndex");s(La,"resolveFileEdges");s(ph,"resolveImportTarget")});import{execFileSync as fh}from"node:child_process";import{createHash as mh}from"node:crypto";import{readdirSync as hh,statSync as gh}from"node:fs";import{posix as Ga,sep as ja}from"node:path";function S(e,t){try{return fh("git",[...yh,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function bh(e){return ja==="/"?e:e.split(ja).join("/")}function jn(e){let t=[];for(let n of e){let r=bh(n).trim();if(!r||ai(r))continue;let i=Cn(r);i&&t.push({path:r,language:i})}return t}function Wa(e){return jn(e)}function Ka(e){let t=Ze(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return jn(t.split(`
13
- `));let n=[];return Ba(e,"",n),jn(n)}function Ba(e,t,n){let r;try{r=hh(Ga.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&Ha.has(i.name)||Ha.has(i.name))continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?Ba(e,o,n):i.isFile()&&n.push(o)}}function fi(e,t){let r=S(e,["merge-base",t,"HEAD"])?.trim();return r&&r.length>0?r:t}function Hn(e,t={}){if(Ft(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?fi(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let o=Ze(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of o.split(`
14
- `)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let u=l[0][0],d=Ua((l.length>=3?l[l.length-1]:l[1]).trim());d&&(u==="A"||u==="C"?a.set(d,"added"):u==="R"?a.set(d,"renamed"):a.set(d,"modified"))}if(n){let c=Ze(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
15
- `)){if(l.length<4)continue;let u=l[0],d=l[1];if(u==="D"||d==="D")continue;let p=l.slice(3),m=p.indexOf(" -> ");m>=0&&(p=p.slice(m+4)),p=Ua(p),!(!p||a.has(p))&&(u==="?"||u==="A"||d==="A"?a.set(p,"added"):u==="R"?a.set(p,"renamed"):a.set(p,"modified"))}}return a}function Ua(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Va(e,t={}){let n=Hn(e,t);return n===null?null:jn(n.keys())}function qa(e,t){try{let n=gh(Ga.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Un(e){return mh("sha256").update(e).digest("hex")}function Ft(e){return Ze(e,["rev-parse","HEAD"])?.trim()??null}function Gn(e,t){return Ze(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function za(e){let t=Ze(e,["status","--porcelain","-uall"]);return t!==null&&t.trim().length>0}var Ha,yh,Ze,W=_(()=>{"use strict";Nn();Ha=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),yh=["-c","diff.renames=true","-c","core.quotePath=false"];s(S,"runGit");Ze=S;s(bh,"toPosix");s(jn,"classify");s(Wa,"classifyPaths");s(Ka,"discoverSourceFiles");s(Ba,"walk");s(fi,"resolveDiffBase");s(Hn,"enumerateChangedPaths");s(Ua,"unquote");s(Va,"changedSourceFiles");s(qa,"statFile");s(Un,"hashContent");s(Ft,"headCommit");s(Gn,"resolveCommitSha");s(za,"isWorktreeDirty")});function Ya(e,t={}){if(S(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?fi(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let o=S(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(o,"utf8")>_h?c="none":Sh(o,a,()=>{c="partial"}),n){let l=S(e,["status","--porcelain","-uall"])??"";for(let u of l.split(`
16
- `)){if(u.length<4||u[0]!=="?")continue;let d=u.slice(3);d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),!(!d||a.has(d))&&a.set(d,{path:d,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:a,coverage:c}}function Sh(e,t,n){let r=null,i=0,o=!1,a=!1,c=s(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
17
- `)){if(l.startsWith("diff --git ")){c(),o=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){o=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let d=l.slice(4).trim();if(d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),d.startsWith("b/")&&(d=d.slice(2)),d==="/dev/null")continue;r={path:d,status:a?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let u=vh.exec(l);if(u){if(i++,i>wh){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let d=Number(u[1]),p=u[2]===void 0?1:Number(u[2]);p>0?r.addedRanges.push({start:d,end:d+p-1}):r.deletionPoints.push(d);continue}l.startsWith("+")&&!l.startsWith("+++")&&!r.degraded&&r.addedLines.length<kh&&r.addedLines.push(l.slice(1))}c()}var _h,wh,kh,Ja,vh,Xa=_(()=>{"use strict";W();_h=16*1024*1024,wh=500,kh=4e3,Ja=256*1024,vh=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(Ya,"changedHunks");s(Sh,"parseUnifiedDiff")});function Rh(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function Za(e){return e.split(Eh).filter(t=>t.trim().length>0)}function ec(e){let[t,n,r,i,o]=e.replace(/\n+$/,"").split(xh);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:o??""}}function Ah(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,i=t.get(r);i?i.commits+=1:t.set(r,{name:n.authorName,email:n.authorEmail,commits:1,lastDateIso:n.dateIso})}return[...t.values()].sort((n,r)=>r.commits-n.commits||n.email.localeCompare(r.email)).slice(0,10)}function nc(e,t,n={}){let r=Rh(n.limit,20,100),i=n.includeOwnership!==!1,o=Math.max(r,tc),a=t.map(d=>d.trim()).filter(d=>d.length>0&&!d.startsWith(":")),c=a.slice(0,mi),l=[];for(let d of c){let p=S(e,["log","-n",String(o),Qa,"--",d]),m=p===null?[]:Za(p).map(ec).filter(f=>f!==null);l.push({path:d,lastCommits:m.slice(0,r),ownership:i?{topAuthors:Ah(m),commitsInWindow:m.length}:null})}let u=null;if(n.since){let d=Gn(e,n.since),p=d!==null?[`${d}..HEAD`]:[`--since=${n.since}`],m=S(e,["log",...p,"-n",String(Wn+1),Qa,"--name-only","--",...c]),f=[];if(m!==null)for(let h of Za(m)){let g=h.split(`
18
- `),y=ec(g[0]??"");if(!y)continue;let b=g.slice(1).filter(w=>w.trim().length>0).length;f.push({sha:y.sha,dateIso:y.dateIso,authorName:y.authorName,subject:y.subject,filesTouched:b})}u={sinceInput:n.since,sinceResolved:d,commits:f.slice(0,Wn),truncated:f.length>Wn}}return{history:l,regression:u,ownershipWindowCommits:o,pathsTruncated:a.length>mi}}var Eh,xh,tc,mi,Wn,Qa,hi=_(()=>{"use strict";W();Eh="",xh="\0",tc=200,mi=50,Wn=100,Qa="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";s(Rh,"clamp");s(Za,"splitRecords");s(ec,"parseHistoryRecord");s(Ah,"aggregateOwnership");s(nc,"readFileHistory")});import{execFileSync as Th}from"node:child_process";import{readdirSync as Ih,statSync as rc}from"node:fs";import{isAbsolute as Ch,join as gi,relative as Nh,resolve as Ph}from"node:path";function Oh(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function Mh(e,t){try{let n=Th("git",["-C",e,"config","--get",t],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n.length>0?n:null}catch{return null}}function Fh(e){let t;try{t=Ih(e)}catch{return null}for(let n of t.filter(Oh))try{let r=rc(gi(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function Lh(e){try{return rc(e).isDirectory()}catch{return!1}}function $h(e,t){let n=Nh(e,t);return!n||n.startsWith("..")?t:n}function yi(e){let t=Dh.filter(c=>Lh(gi(e,c))),n=Mh(e,"core.hooksPath"),r=n?Ch(n)?n:Ph(e,n):gi(e,".git","hooks"),i=$h(e,r),o=Fh(r);if(o===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?o===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:a,hookDirs:t,hooksPath:n,effectiveDir:i}}function bi(e){switch(e.reason){case"wired":return`Git-Gates aktiv (core.hooksPath \u2192 ${e.effectiveDir}).`;case"default_path":return"Git-Gates aktiv (.git/hooks, nicht versioniert).";case"path_unset":return`${e.hookDirs.join(", ")} liegt im Repo, aber core.hooksPath ist ungesetzt \u2014 kein Gate feuert.`;case"path_missing":return`core.hooksPath zeigt auf ${e.effectiveDir}, das es nicht gibt \u2014 git f\xFChrt keinen Hook aus.`;case"path_empty":return`core.hooksPath zeigt auf ${e.effectiveDir}, dort liegt kein ausf\xFChrbarer Hook.`;case"no_hooks":return"Keine Git-Hooks im Repo."}}var Dh,_i=_(()=>{"use strict";Dh=[".githooks",".husky"];s(Oh,"isRealHook");s(Mh,"gitConfig");s(Fh,"hasExecutableHook");s(Lh,"isDir");s($h,"displayPath");s(yi,"resolveHookState");s(bi,"describeHookState")});import{posix as ic}from"node:path";function et(e){let t=jh.exec(e);return t?t[1]:null}function ue(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Te(e,t){let n=S(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=s(o=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||o===c||o.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let o of n.split("\0").filter(Boolean)){if(!r(o))continue;let a=ic.basename(o),c=et(a);if(c===null)continue;let l=ic.dirname(o),u=i.get(l)??[];u.push({path:o,name:a,version:c}),i.set(l,u)}return[...i.entries()].map(([o,a])=>({dir:o,files:a.sort((c,l)=>ue(c.version,l.version))})).sort((o,a)=>o.dir.localeCompare(a.dir))}function oc(e){let t=S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var jh,Lt=_(()=>{"use strict";W();jh=/^(\d+)_.+\.sql$/;s(et,"parseMigrationVersion");s(ue,"compareVersions");s(Te,"discoverSupabaseProjects");s(oc,"resolveDefaultBranch")});import{execFileSync as Hh}from"node:child_process";import{existsSync as H,readFileSync as we,readdirSync as Kn,statSync as ki}from"node:fs";import{posix as x}from"node:path";function Kh(e,t){let n=(()=>{let i=S(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=x.dirname(e);for(let i=0;i<8&&r&&r!==x.dirname(r);i++){if(H(x.join(r,".git"))){let o=(()=>{let c=S(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&o!=null&&Si(n,o))){let c=Bh(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=x.dirname(r)}return null}function Bh(e,t){let n=[];for(let r of Gh){let i;try{i=Kn(x.join(e,r),{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>o.name)}catch{continue}for(let o of i){let a=`${r}/${o}`,c=x.join(e,a),l=x.join(t,a);try{let u=ki(c),d=ki(l);if(!d.isFile())continue;if(u.size!==d.size){n.push(a);continue}if(u.size>Wh)continue;we(c).equals(we(l))||n.push(a)}catch{continue}}}return n.sort()}function pc(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let a=e.upstream.split("/").slice(1).join("/");a&&a!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;if(r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`}),e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let a=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${a} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let a=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${a.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${Ei}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let a=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${a.map(c=>c.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:a.map(c=>`${c.install} (in ${x.dirname(c.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:a,diverging:c}=e.toolCopyDrift,l=c.slice(0,3).join(", "),u=c.length>3?` (+${c.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${a} ships ${l}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${c[0]}\` from this repo root), not via a path into ${a}.`})}if(e.stalePackageBuilds.length>0){let a=e.stalePackageBuilds,c=s(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),l=a.every(u=>u.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:a.some(u=>u.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${a.map(c).join(", ")}: src/ is newer than the built ${[...new Set(a.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${l}`,hint:`Rebuild: pnpm --filter ./${a[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let o=Vh(e.hooks);return o&&t.push(o),qh(t)}function Vh(e){return!e||e.verdict!=="present_unwired"?null:{id:"setup.hooks-unwired",status:"warn",scope:"setup",title:"Git-Hooks liegen im Repo, feuern aber nicht",detail:bi(e),hint:e.reason==="path_missing"?`core.hooksPath zeigt ins Leere. Korrigieren: git config core.hooksPath ${e.hookDirs[0]??".githooks"}`:`git config core.hooksPath ${e.hookDirs[0]??".githooks"} \u2014 git klont das Verzeichnis mit, den Pfad nie.`}}function qh(e){return[...e].sort((t,n)=>sc[t.status]-sc[n.status]||t.id.localeCompare(n.id))}function fc(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function pe(e){let t=e?.trim();return t||null}function zh(e){let t=pe(S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Jh(e){let t=pe(S(e,["rev-parse","--git-dir"]));if(!t)return null;let n=x.isAbsolute(t)?t:x.join(e,t);return H(x.join(n,"rebase-merge"))||H(x.join(n,"rebase-apply"))?"rebase":H(x.join(n,"MERGE_HEAD"))?"merge":H(x.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function Yh(e){let t=[],n=null,r=s(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
19
- `))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function Xh(e){let t=x.join(e,Ei);if(!H(t))return[];try{return we(t,"utf8").split(`
20
- `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function Qh(e){try{return Te(e).map(t=>x.join(x.dirname(t.dir),"config.toml"))}catch{return[]}}function Zh(e){let t=S(e,["ls-files","-z","--",...Uh]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=uc[x.basename(r)];if(i===void 0)continue;let o=x.dirname(r);if(!eg(e,o))continue;let a=o==="."?"node_modules":x.join(o,"node_modules");n.has(a)||n.set(a,{dir:a,install:i})}return[...n.values()]}function eg(e,t){return t==="."?!0:vi(e,t)}function vi(e,t){if(H(x.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(we(x.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function mc(e,t={}){if(pe(S(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,branch:null,defaultBranch:null,upstream:null,headMatchesUpstream:null,remoteTrackingExists:null,ahead:null,behind:null,uncommitted:0,detachedHead:!1,inProgressOp:null,isSharedMainTree:!1,otherWorktrees:0,worktreeParity:null,toolCopyDrift:null,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=pe(S(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",o=i?null:r,a=zh(e),c=pe(S(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,u=null;if(c){let T=pe(S(e,["rev-parse","HEAD"])),A=pe(S(e,["rev-parse","@{u}"]));l=T!=null&&A!=null?T===A:null,u=S(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let d=null,p=null;if(a){let T=pe(S(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(T){let[A,j]=T.split(/\s+/).map(N=>Number.parseInt(N,10));Number.isFinite(A)&&(p=A),Number.isFinite(j)&&(d=j)}}let f=(S(e,["status","--porcelain"])??"").split(`
21
- `).filter(T=>T.trim().length>0).length,h=Jh(e),g=pe(S(e,["rev-parse","--show-toplevel"]))??e,y=Yh(S(e,["worktree","list","--porcelain"])??""),b=y[0]?.path??null,w=b!=null&&Si(b,g),v=Math.max(0,y.length-1),k=null;if(b&&!Si(b,g)){let T=s(j=>H(x.join(b,j))&&!H(x.join(g,j)),"here"),A=[...dc,...Qh(g),...Xh(g),...t.probePaths??[]];k={mainWorktreePath:b,currentWorktreePath:g,missing:[...new Set(A.filter(T))],missingDeps:Zh(g).filter(j=>T(j.dir))}}let E=Kh(g,e),R=t.includeRelease===!1?null:ag(e,o),I=[];return a&&(I=(S(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
22
- `).map(A=>A.trim()).filter(A=>A.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:u,ahead:d,behind:p,uncommitted:f,detachedHead:i,inProgressOp:h,isSharedMainTree:w,otherWorktrees:v,worktreeParity:k,toolCopyDrift:E,stalePackageBuilds:hc(g),release:R,unmergedMigrations:I,hooks:yi(e)}}function Si(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function rg(e){let t=new Set;vi(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<cc;){let i=n.pop();if(i===void 0)break;if(i.depth>=ng)continue;let o;try{o=Kn(x.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=i.rel==="."?a.name:x.join(i.rel,a.name);if(r+=1,r>=cc)break;vi(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function ig(e){let t=[];try{let n=x.join(e,"pnpm-workspace.yaml");if(H(n)){let r=!1;for(let i of we(n,"utf8").split(`
23
- `)){let o=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(o)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(o);a?t.push(a[1]):o.trim().length>0&&!/^\s/.test(o)&&(r=!1)}}}else{let r=x.join(e,"package.json");if(H(r)){let i=JSON.parse(we(r,"utf8")),o=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(o)&&t.push(...o.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function og(e){let t=[];for(let n of rg(e)){let r=n==="."?e:x.join(e,n),i=s(o=>n==="."?o:x.join(n,o),"prefix");for(let o of ig(r)){if(t.length>=wi)break;if(!(o.startsWith("!")||o.includes("**")))try{if(o.endsWith("/*")){let a=o.slice(0,-2),c=x.join(r,a);if(!H(c))continue;for(let l of Kn(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(x.join(a,l.name))),t.length>=wi)break}else o.includes("*")||t.push(i(o))}catch{}}}return t.slice(0,wi)}function lc(e){let t=null,n=0,r=[e];for(;r.length>0&&n<ac;){let i=r.pop();if(i===void 0)break;let o;try{o=Kn(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=x.join(i,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=ki(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=ac)break}}}return t}function sg(e,t){let n=new Set;for(let r of t)try{let i=x.join(e,r,"package.json");if(!H(i))continue;let o=JSON.parse(we(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=o[a];if(!(c===null||typeof c!="object"))for(let[l,u]of Object.entries(c))typeof u=="string"&&u.startsWith("workspace:")&&n.add(l)}}catch{}return n}function hc(e){let t=[],n=og(e),r=sg(e,n);for(let i of n)try{let o=x.join(e,i,"package.json");if(!H(o))continue;let a=JSON.parse(we(o,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(b=>{if(typeof b!="string")return null;let w=b.replace(/^\.\//,"").split("/")[0];return w==="build"||w==="dist"?w:null},"builtSeg"),l=c(a.types??a.typings),u=c(a.main),d=l??u;if(d===null)continue;let p=l!==null&&u!==null?"both":l!==null?"types":"runtime",m=x.join(e,i,"src"),f=x.join(e,i,d);if(!H(m)||!H(f))continue;let h=lc(m),g=lc(f);if(h===null||g===null)continue;let y=h-g;y>tg&&t.push({packageDir:i,buildDir:d,srcNewerByMs:Math.round(y),impact:p})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}function ag(e,t){if(!t)return null;let n=cg(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(o=>o.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}function cg(e,t){try{return Hh("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function $t(e,t={}){let n=await mc(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=pc(n),i=fc(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var dc,Ei,uc,Uh,Gh,Wh,sc,tg,wi,ac,ng,cc,xi=_(()=>{"use strict";_i();W();Lt();dc=["supabase/config.toml","supabase/.temp",".env"],Ei=".maind/worktree-requirements",uc={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},Uh=Object.keys(uc).flatMap(e=>[e,"*/"+e]),Gh=["scripts"],Wh=512*1024;s(Kh,"gatherToolCopyDrift");s(Bh,"compareToolDirs");s(pc,"computeDivergence");s(Vh,"computeHookFinding");sc={open:0,warn:1,info:2,passed:3};s(qh,"sortFindings");s(fc,"isHealthy");s(pe,"trimOrNull");s(zh,"resolveDefaultBranch");s(Jh,"detectInProgressOp");s(Yh,"parseWorktrees");s(Xh,"readWorktreeRequirements");s(Qh,"discoverSupabaseConfigProbes");s(Zh,"discoverDependencyDirs");s(eg,"isWorkspaceRoot");s(vi,"hasWorkspaceMarkers");s(mc,"gatherRepoHealthFacts");s(Si,"samePath");tg=2e3,wi=64,ac=4e3,ng=3,cc=400;s(rg,"findWorkspaceRoots");s(ig,"workspacePatternsAt");s(og,"listWorkspacePackageDirs");s(lc,"newestMtimeUnder");s(sg,"consumedWorkspaceNames");s(hc,"gatherStalePackageBuilds");s(ag,"gatherReleaseFact");s(cg,"runGh");s($t,"checkDivergence")});import{existsSync as Ri,readdirSync as gc}from"node:fs";import{posix as re}from"node:path";function Ti(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Ai)}function bc(e,t={}){let n=t.minFiles??Ii;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??yc)}function nt(e){return`${e.dir}#${e.prefix}`}function jt(e){let t=lg.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function _c(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let o=nt(i),a=e.sightingsByNamespace.get(o);if(!a)continue;let c=new Set(a.keys());for(let[l,u]of a){let d=[...new Set(u.map(h=>h.path))];if(d.length<2)continue;let p=d.find(h=>n.has(h)),m=d.filter(h=>h!==p),f=`${i.prefix}${l}`;t.push(p?{id:`number.collision:${o}#${l}`,status:"open",namespace:i,number:l,title:`${f} is already taken`,detail:`This branch adds ${p}, but ${f} already exists as ${m.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${f} stop being unambiguous.`,ownPath:p,sightings:u.filter(h=>h.path!==p),suggestion:`${i.prefix}${Ci(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${o}#${l}`,status:"info",namespace:i,number:l,title:`${f} is used more than once (pre-existing)`,detail:`${f} is carried by ${d.length} files: ${d.join(", ")}.`,sightings:u,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,o)=>r[i.status]-r[o.status]||i.id.localeCompare(o.id))}function wc(e){return!e.some(t=>t.status==="open")}function Ci(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}function Ni(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function kc(e,t){let n=Ni(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=jt(re.basename(n));if(!i)return r;let o=`${re.dirname(n)}#${i.prefix}`,a=e.namespaces.find(d=>nt(d)===o)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(o)??new Map,l=new Set,u=[];for(let d of c.get(i.number)??[])d.path===n||l.has(d.path)||(l.add(d.path),u.push(d));return{path:n,namespace:a,number:i.number,taken:u.length>0,sightings:u,suggestion:Ci(c.keys(),i.number)}}function Bn(e){let t=e?.trim();return t||null}function tt(e){return e?e.split(`
24
- `).filter(Boolean):[]}function dg(e){let t=Bn(S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function vc(e,t={}){let n=t.minFiles??Ii,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=S(e,r);if(i===null)return[];let o=new Map;for(let a of i.split("\0").filter(Boolean)){let c=re.dirname(a),l=jt(re.basename(a));if(!l)continue;let u=`${c}#${l.prefix}`,d=o.get(u);d?d.numbers.push(l.number):o.set(u,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...o.values()].filter(a=>bc(a.numbers,{...t,minFiles:n})).map(a=>({dir:a.dir,prefix:a.prefix,fileCount:a.numbers.length,distinctRatio:new Set(a.numbers).size/a.numbers.length})).sort((a,c)=>nt(a).localeCompare(nt(c)))}async function Pi(e,t={}){let n=[];if(Bn(S(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,baseRef:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=vc(e,t),o=new Map(i.map(h=>[nt(h),h])),a=[...new Set(i.map(h=>h.dir))],c=new Map,l=s((h,g,y)=>{let b=re.dirname(h),w=jt(re.basename(h));if(!w)return;let v=`${b}#${w.prefix}`;if(!o.has(v))return;let k=c.get(v)??new Map,E=k.get(w.number)??[];E.push({kind:g,where:y,path:h}),k.set(w.number,E),c.set(v,k)},"record"),u=s((h,g,y)=>{if(a.length===0)return;let b=S(e,["ls-tree","-r","--name-only",h,"--",...a]);if(b===null){n.push(`could not read ${y}`);return}for(let w of tt(b))l(w,g,y)},"scanTree");for(let h of a){let g=re.join(e,h);if(Ri(g))try{for(let y of gc(g))l(`${h}/${y}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let d=dg(e),p=t.baseRef??(d?`origin/${d}`:null);p?u(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let m=Bn(S(e,["rev-parse","--abbrev-ref","HEAD"]));for(let h of tt(S(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))h!==m&&u(h,"branch",`Branch ${h}`);if(t.includeWorktrees!==!1){let h=Bn(S(e,["rev-parse","--show-toplevel"]));for(let g of tt(S(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===h||!Ri(y)))for(let b of a){let w=re.join(y,b);if(Ri(w))try{for(let v of gc(w))l(`${b}/${v}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${b} in ${y}`)}}}}let f=[];if(p&&a.length>0){let h=S(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);h===null?n.push(Ai):f=tt(h);let g=S(e,["ls-files","--others","--exclude-standard","--",...a]);g!==null&&(f=[...f,...tt(g)]);let y=S(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);y!==null&&(f=[...f,...tt(y)])}return{isRepo:!0,defaultBranch:d,baseRef:p,namespaces:i,sightingsByNamespace:c,addedPaths:f,skipped:n}}async function Ie(e,t={}){let n=await Pi(e,t),r=_c(n);return{ok:wc(r),findings:r,facts:n}}async function Ce(e,t,n={}){let r=Ni(t);if(!jt(re.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Pi(e,{...n,dirs:n.dirs??[re.dirname(r)]});return kc(i,r)}var Ai,lg,Ii,yc,Ht=_(()=>{"use strict";W();Ai="could not diff against the base ref \u2014 everything reported as info";s(Ti,"isNumberCollisionsGraded");lg=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Ii=3,yc=.8;s(bc,"isCounterNamespace");s(nt,"namespaceKey");s(jt,"parseNumbered");s(_c,"computeNumberCollisions");s(wc,"isCollisionFree");s(Ci,"suggestNextNumber");s(Ni,"normaliseRepoPath");s(kc,"checkProposedNumber");s(Bn,"trimOrNull");s(tt,"lines");s(dg,"resolveDefaultBranch");s(vc,"detectNamespaces");s(Pi,"gatherNumberCollisionFacts");s(Ie,"checkNumberCollisions");s(Ce,"checkNumberForPath")});function Li(e){return`spec.${e}`}function rt(e,t={}){switch(e){case"open":return{level:"open",baseline:"introduced"};case"warn":return{level:"warn",baseline:"introduced"};case"info":return t.excepted?{level:"info",baseline:"introduced"}:{level:"open",baseline:"pre_existing"};default:throw new Error(`gradeEngineStatus: '${String(e)}' is not a finding status`)}}function ug(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let o=0;o<i;o++){let a=(n[o].codePointAt(0)??0)-(r[o].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function Sc(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(ug)}function Ut(e){return oi(JSON.stringify(Sc(e)))}var Di,Oi,Mi,Fi,$i=_(()=>{"use strict";si();Di={det_number_collisions:{version:"1.1.0",rules:["number.collision"]},det_spec_drift:{version:"1.1.0",rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"]},det_theme_class_drift:{version:"1.1.0",rules:["theme.dead_class"]},det_table_acl_lint:{version:"1.0.0",rules:["acl.missing_revoke"]}},Oi="number.collision",Mi="theme.dead_class",Fi="acl.missing_revoke";s(Li,"specDriftRuleId");s(rt,"gradeEngineStatus");s(ug,"codePointCompare");s(Sc,"normalizeEvidenceForHash");s(Ut,"hashDetectorEvidence")});import{existsSync as pg,readFileSync as Ec}from"node:fs";import{posix as fg}from"node:path";function zn(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}function Jn(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
25
- `,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}function Gt(e){return e==='"'||e==="'"||e==="`"}function Yn(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function Vn(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let o=e[i];if(Gt(o)){i=zn(e,i);continue}if(Yn(e,i)){i=Jn(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function mg(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Yn(e,t)){t=Jn(e,t);continue}break}return e.slice(t)}function it(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let o=e[i];if(Gt(o)){i=zn(e,i);continue}if(Yn(e,i)){i=Jn(e,i);continue}o==="["||o==="{"||o==="("?n++:o==="]"||o==="}"||o===")"?n--:o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(o=>mg(o).trim()).filter(o=>o.length>0)}function Tc(e){let t=zn(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
26
- `:i==="r"?"\r":i==="t"?" ":i)}function hg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hi(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${hg(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,o=!1;for(;i<e.length;){let a=e[i];if(Gt(a)){i=zn(e,i);continue}if(Yn(e,i)){i=Jn(e,i);continue}if(!o){if(a==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))o=!0;else if(a===";")return null;i++;continue}if(a==="[")return Vn(e,i);if(a===";")return null;i++}return null}function Ui(e){let t={};if(!e.startsWith("{"))return t;for(let n of it(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],o=r[4].trim();Gt(o[0]??"")&&(t[i]=Tc(o))}return t}function gg(e,t){if(!e.startsWith("{"))return null;for(let n of it(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===t)return r[4].trim()}return null}function Ic(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Cc(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Nc(e,t){let n=Hi(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Cc(),i=[],o=0;for(let a of it(n.slice(1,-1))){if(!a.startsWith("{")){o++;continue}let c=Ui(a),l=c[t.key_field];if(!l){o++;continue}let u=(t.partition_by??[]).map(d=>c[d]??"");i.push({key:l,fields:Ic(c,t.fields),orderPath:u,ordinal:r(u)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function Pc(e,t){let n=Hi(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};if(t.levels.length===0)return{records:[],error:`contract declares no levels for \`${t.symbol}\``,dropped:0};let r=Cc(),i=[],o=0,a=s((c,l,u)=>{let d=t.levels[l],p=l===t.levels.length-1;for(let m of it(c.slice(1,-1))){let f={...u},h=null;if(d.shape==="object"){if(!m.startsWith("{")){o++;continue}let g=Ui(m);for(let[y,b]of Object.entries(d.fields??{}))f[y]=g[String(b)]??"";if(!p&&typeof d.children=="string"){let y=gg(m,d.children);h=y&&y.startsWith("[")?Vn(y,0):null}}else{if(!m.startsWith("[")){o++;continue}let g=it(m.slice(1,-1));for(let[y,b]of Object.entries(d.fields??{})){let w=g[Number(b)];f[y]=w!==void 0&&Gt(w[0]??"")?Tc(w):""}if(!p&&typeof d.children=="number"){let y=g[d.children];h=y!==void 0&&y.startsWith("[")?Vn(y,0):null}}if(p){let g=f[t.key_field];if(!g){o++;continue}let y=(t.partition_by??[]).map(b=>f[b]??"");i.push({key:g,fields:Ic(f,t.fields),orderPath:y,ordinal:r(y)});continue}h!==null&&a(h,l+1,f)}},"walk");return a(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function xc(e,t){return t.extractor==="object-array"?Nc(e,t):Pc(e,t)}function Dc(e,t,n){let r=e;return t.strip_prefix&&r.startsWith(t.strip_prefix)&&(r=r.slice(t.strip_prefix.length)),t.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}function Oc(e,t,n){return`spec.drift:${e}#${t}:${n}`}function yg(e){return e.orderPath.join(" / ")||"(flat)"}function Mc(e,t,n,r){let i=[],o=s((u,d,p,m,f,h)=>{i.push({id:Oc(e.id,u,p),contract:e.id,dimension:u,status:d,key:p,title:m,detail:f,hint:h})},"push"),a=new Map(n.map(u=>[u.key,u])),c=new Map(t.map(u=>[u.key,u]));for(let u of t){let d=a.get(u.key);if(!d){o("coverage","open",u.key,`${u.key} is declared by the specification but missing from the implementation`,`Partition ${yg(u)}, position ${u.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let m=u.fields[p]??"",f=d.fields[p]??"";m!==f&&o("fields","open",`${u.key}.${p}`,`${u.key}: ${p} is "${f||"\u2014"}", the specification says "${m||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let u of t){let d=u.orderPath.join("\0"),p=l.get(d);p?p.push(u):l.set(d,[u])}for(let[u,d]of l){let p=d.filter(g=>a.has(g.key)).map(g=>g.key),m=n.filter(g=>g.orderPath.join("\0")===u).filter(g=>c.has(g.key)).map(g=>g.key),f=new Set(m),h=p.filter(g=>f.has(g));if(m.join("|")!==h.join("|")){let g=u.split("\0").join(" / ")||"(flat)";o("order","open",g,`Partition ${g}: sequence differs from the specification`,`implementation: ${m.join(" \u2192 ")}
27
- specification: ${h.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let u of n)c.has(u.key)||o("extra","warn",u.key,`${u.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let u of new Set([...a.keys(),...c.keys()])){if(Dc(u,e.grounding,r))continue;let d=a.has(u);o("unrealized",d?"open":"warn",u,d?`${u} is referenced by the implementation but has no artefact`:`${u} is declared by the specification but not built yet`,d?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}function bg(e,t,n){let r=[];for(let i of e.assertions??[]){let o=n.get(i.path);if(!o)continue;let a=o.indexOf(i.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(o.slice(a+i.prefix.length));if(!c)continue;let l=Number(c[1]),u=t[i.counts];l!==u&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${u}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function Rc(e,t){return{id:`contract.unreadable:${e}`,contract:e,dimension:"contract",status:"open",key:null,title:`Contract "${e}" could not be evaluated`,detail:t,hint:"This is NOT a drift finding. An anchor moved, or a declared file is gone \u2014 repair the contract in the manifest, then re-run. Nothing has been compared for this contract."}}function Fc(e,t={}){let n=s(d=>({ok:!1,verdict:"no_opinion",reason:d,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(d=>t.contracts.includes(d.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(d=>`"${d}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=s(d=>{let p=[],m=[];for(let f of r){let h=d.get(f.spec.path),g=d.get(f.impl.path);if(h==null||g==null){let v=h==null?f.spec.path:f.impl.path;p.push(Rc(f.id,`Declared file could not be read: ${v}`)),m.push({id:f.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let y=xc(h,f.spec),b=xc(g,f.impl);if(y.error||b.error){p.push(Rc(f.id,y.error??b.error??"unknown")),m.push({id:f.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let w=y.dropped>0||b.dropped>0;m.push({id:f.id,measured:!0,specRecords:y.records.length,implRecords:b.records.length,partial:w}),w&&p.push({id:`contract.partial:${f.id}`,contract:f.id,dimension:"contract",status:"warn",key:null,title:`Contract "${f.id}" was measured incompletely`,detail:`${y.dropped} specification and ${b.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),p.push(...Mc(f,y.records,b.records,e.files)),p.push(...bg(f,{spec:y.records.length,impl:b.records.length},d))}return{findings:p,contracts:m}},"runOnce"),o=i(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let d of i(e.baselineSources).findings)d.id.startsWith("contract.unreadable:")||a.add(d.id);let c=new Map;for(let d of r)for(let p of d.exceptions??[])c.set(Oc(d.id,p.dimension,p.key),p);let l=o.findings.map(d=>{let p=c.get(d.id);return p?{...d,status:"info",exceptionReason:p.reason}:a.has(d.id)?{...d,status:"info",detail:`${d.detail}
28
- Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:d});l.sort((d,p)=>Ac[d.status]-Ac[p.status]||d.id.localeCompare(p.id));let u=l.some(d=>d.status==="open");return{ok:!u,verdict:u?"drifted":"aligned",reason:null,findings:l,contracts:o.contracts}}function ji(e){let t=e?.trim();return t||null}function Xn(e){let t;try{t=JSON.parse(e)}catch(a){return{manifest:null,error:`manifest is not valid JSON: ${a.message}`}}let n=s(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,"obj"),r=s(a=>typeof a=="string"?a:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let o=s(a=>({manifest:null,error:a}),"bad");for(let[a,c]of i.contracts.entries()){let l=n(c),u=r(l?.id),d=u?`contract "${u}"`:`contract #${a+1}`;if(!l)return o(`${d}: not an object`);if(!u)return o(`${d}: \`id\` is missing`);if(!r(l.reason))return o(`${d}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let p of["spec","impl"]){let m=n(l[p]);if(!m)return o(`${d}: \`${p}\` is missing`);let f=r(m.extractor);if(!f)return o(`${d}: \`${p}.extractor\` is missing`);if(f!=="object-array"&&f!=="nested-literal-list")return o(`${d}: unknown \`${p}.extractor\` "${f}"`);if(!r(m.path)||!r(m.symbol)||!r(m.key_field))return o(`${d}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(f==="nested-literal-list"&&!Array.isArray(m.levels))return o(`${d}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(l.exceptions)?l.exceptions:[]){let m=n(p);if(!m||!r(m.reason))return o(`${d}: exception for "${r(m?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}function _g(e){let t=ji(S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function wg(e){let t=new Set;for(let n of e.contracts){t.add(n.spec.path),t.add(n.impl.path);for(let r of n.assertions??[])t.add(r.path)}return[...t]}async function Lc(e,t={}){let n=s((h,g)=>fg.join(h,g),"join"),r=t.manifestPath??qn,i=[],o={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(ji(S(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...o,manifestError:"not a git work tree"};let a=n(e,r);if(!pg(a))return{...o,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,l=null;try{({manifest:c,error:l}=Xn(Ec(a,"utf8")))}catch(h){l=`manifest at ${r} could not be read: ${h.message}`}if(!c)return{...o,isRepo:!0,manifestError:l};let u=new Map;for(let h of wg(c))try{u.set(h,Ec(n(e,h),"utf8"))}catch{u.set(h,null),i.push(`declared file unreadable in the working tree: ${h}`)}let d=new Set,p=S(e,["ls-files","-z"]);if(p===null)i.push("could not list tracked files \u2014 grounding is skipped");else for(let h of p.split("\0"))h&&d.add(h);let m=null,f=new Map;if(t.includeBaseline!==!1){let h=t.baseRef?null:_g(e),g=t.baseRef??(h?`origin/${h}`:null);if(!g)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(m=ji(S(e,["merge-base",g,"HEAD"])),!m)i.push(`no merge-base with ${g} \u2014 every finding reported as new`);else for(let y of u.keys())f.set(y,S(e,["show",`${m}:${y}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:u,baselineSources:f,baseRef:m,files:d,skipped:i}}async function Ne(e,t={}){let n=await Lc(e,t);return{...Fc(n,t),facts:n}}function Gi(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var qn,Ac,Wt=_(()=>{"use strict";W();qn=".maind/spec-contracts.json";s(zn,"endOfString");s(Jn,"skipComment");s(Gt,"isQuote");s(Yn,"isCommentStart");s(Vn,"sliceBalanced");s(mg,"stripLeadingTrivia");s(it,"splitTopLevel");s(Tc,"readStringLiteral");s(hg,"escapeRe");s(Hi,"findSymbolArray");s(Ui,"parseObjectFields");s(gg,"objectFieldRaw");s(Ic,"pickFields");s(Cc,"makeOrdinals");s(Nc,"extractObjectArray");s(Pc,"extractNestedList");s(xc,"extractRecords");s(Dc,"isGrounded");s(Oc,"findingId");s(yg,"partitionOf");s(Mc,"compareContract");s(bg,"checkAssertions");s(Rc,"unreadable");Ac={open:0,warn:1,info:2,passed:3};s(Fc,"computeSpecDrift");s(ji,"trimOrNull");s(Xn,"parseManifest");s(_g,"resolveDefaultBranch");s(wg,"declaredPaths");s(Lc,"gatherSpecDriftFacts");s(Ne,"checkSpecDrift");s(Gi,"isSpecDriftGraded")});import{readFileSync as kg}from"node:fs";import{join as vg,posix as Sg}from"node:path";function $c(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],o=e[n+1];if(i==="-"&&o==="-"){for(;n<r&&e[n]!==`
29
- `;)n++;continue}if(i==="/"&&o==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],u=e.indexOf(l,n+l.length);n=u===-1?r:u+l.length,t+=" ";continue}}let a=(i==="E"||i==="e")&&o==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||a){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function X(e){let t=[],n="",r=!1,i=!1,o=s(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){o();continue}n+=l}o();let a=t.filter(c=>c.length>0);return a.length===0||a.length>2?null:a.length===2?{schema:a[0],name:a[1]}:{schema:"public",name:a[0]}}function fe(e){let t=[],n=0,r="";for(let i of e){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}function Eg(e){let t=/^ALTER\s+DEFAULT\s+PRIVILEGES\s+([\s\S]*?)(REVOKE|GRANT)\s+(?:GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+TABLES\s+(?:FROM|TO)\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT|WITH\s+GRANT\s+OPTION))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,o]=t;if(/REVOKE\s+GRANT\s+OPTION\s+FOR/i.test(e))return null;let a=/\bFOR\s+ROLE\s+([\s\S]+?)(?=\s+IN\s+SCHEMA\b|$)/i.exec(n);if(a&&!fe(a[1]).map(m=>X(m)?.name??"").filter(Boolean).includes("postgres"))return null;let c=/\bIN\s+SCHEMA\s+([\s\S]+?)(?=\s+FOR\s+ROLE\b|$)/i.exec(n);if(!c||!fe(c[1]).map(p=>X(p)?.name??"").filter(Boolean).includes("public"))return null;let u=fe(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>X(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(u.length===0)return null;let d=[];for(let p of fe(i)){let m=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!m)continue;let f=m[1].toUpperCase();if(f==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:u,writePrivs:[...Kt]};m[2]!=="("&&Kt.includes(f)&&d.push(f)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:u,writePrivs:d}}function jc(e){let t=/^REVOKE\s+(GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+([\s\S]+?)\s+FROM\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,o]=t;if(n)return null;let a=i.trim();if(xg.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!fe(l[1]).map(m=>X(m)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),m=fe(p).map(f=>X(f)).filter(f=>f!==null).filter(f=>f.schema==="public").map(f=>f.name);if(m.length===0)return null;c=m}let u=fe(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>X(p)?.name??"").filter(p=>p.length>0&&p!=="public"),d=[];for(let p of fe(r)){let m=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!m)continue;let f=m[1].toUpperCase(),h=m[2]==="(";if(f==="ALL")return{tables:c,roles:u,writePrivs:[...Kt]};!h&&Kt.includes(f)&&d.push(f)}return{tables:c,roles:u,writePrivs:d}}function Ki(e){let t=new Map,n=[...e].sort((i,o)=>ue(i.version,o.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let o=$c(i.content);for(let a of o.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=Eg(c);if(!p)continue;let m=p.roles.includes("anon"),f=p.roles.includes("authenticated");if(p.action==="revoke"){if(m&&(r.anonAddressed=!0),f)for(let h of p.writePrivs)r.authWritesRevoked.add(h)}else if(m&&(r.anonAddressed=!1),f)for(let h of p.writePrivs)r.authWritesRevoked.delete(h);continue}let l=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(c);if(l){if(/\bTEMP(?:ORARY)?\b/i.test(l[1]??""))continue;let p=X(l[2]);if(!p||p.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(c)&&t.has(p.name))continue;t.set(p.name,{createdIn:i.version,anonAddressed:r.anonAddressed,authWritesRevoked:new Set(r.authWritesRevoked)});continue}let u=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(c);if(u){let p=u[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let m of fe(p)){let f=X(m);f&&f.schema==="public"&&t.delete(f.name)}continue}let d=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(d){let p=X(d[1]),m=X(d[2]);if(p&&m&&p.schema==="public"){let f=t.get(p.name);f&&(t.delete(p.name),t.set(m.name,f))}continue}if(/^REVOKE\b/i.test(c)){let p=jc(c);if(!p)continue;let m=p.tables==="all_in_public"?[...t.keys()]:p.tables,f=p.roles.includes("anon"),h=p.roles.includes("authenticated");if(!f&&!h)continue;for(let g of m){let y=t.get(g);if(y&&(f&&(y.anonAddressed=!0),h))for(let b of p.writePrivs)y.authWritesRevoked.add(b)}continue}}}return t}function Wi(e){let t=[];for(let[n,r]of Ki(e)){let i=[];r.anonAddressed||i.push("anon"),Kt.every(o=>r.authWritesRevoked.has(o))||i.push("authenticated_writes"),i.length>0&&t.push({table:n,createdIn:r.createdIn,missing:i})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function Hc(e){let t=Wi(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Wi(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),a=i!=null&&r.missing.every(l=>i.has(l))?"info":"open",c=r.missing.map(l=>l==="anon"?"kein Tabellen-REVOKE nennt anon":"authenticated beh\xE4lt Schreibrechte (kumulierte REVOKEs decken INSERT/UPDATE/DELETE nicht)").join("; ");return{id:`table.acl:${e.dir}#${r.table}`,status:a,project:e.dir,table:r.table,createdIn:r.createdIn,missing:r.missing,title:`public.${r.table}: Default-Grants nie adressiert (${r.missing.join(", ")})`,detail:`\xDCber den gesamten Migrations-Bestand von ${e.dir}: ${c}. Supabase' ALTER DEFAULT PRIVILEGES grantet vollen CRUD an anon UND authenticated auf jede neue public-Tabelle; ohne Tabellen-REVOKE ist RLS die einzige Verteidigungslinie. Tabelle erzeugt in Migration ${r.createdIn}.`,hint:`REVOKE ALL ON public.${r.table} FROM PUBLIC, anon; REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.${r.table} FROM authenticated; \u2014 SELECT f\xFCr authenticated darf bewusst bleiben (RLS-gedecktes Lese-Muster). PUBLIC allein reicht NICHT (Default-Privileges sind direkte Rollen-Grants). Ein REVOKE in einer sp\xE4teren Migration z\xE4hlt ebenfalls; in DO-Bl\xF6cken z\xE4hlt es nicht (aufs Top-Level ziehen). Eine Tabelle, die NACH der Wurzelbehandlung entsteht (ALTER DEFAULT PRIVILEGES \u2026 IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated), kommt bereits geschlossen zur Welt und braucht kein eigenes REVOKE \u2014 diese Tabelle hier ist \xE4lter als die Wurzelbehandlung oder es gibt keine.`}})}function Uc(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function Vi(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(Qn)||t.endsWith(Bi))}function Ag(e,t){try{let n=kg(e,"utf8");return n.length>t?null:n}catch{return null}}function Tg(e,t,n,r,i){let o=S(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(o===null)return i.push(`could not diff ${t} against ${r} ${Qn}`),null;let a=new Set,c=[];for(let d of o.split(`
30
- `).filter(Boolean)){let[p,...m]=d.split(" ");p.startsWith("A")?a.add(m[0]):p.startsWith("R")?(c.push(m[0]),a.add(m[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(m[0])}let l=[],u=new Set(c);for(let{ref:d,content:p}of n)!a.has(d.path)&&!u.has(d.path)&&l.push({name:d.name,version:d.version,content:p});for(let d of c){let p=Sg.basename(d),m=et(p);if(m===null)continue;let f=S(e,["show",`${r}:${d}`]);if(f===null)return i.push(`could not read ${d} at ${r} ${Bi}`),null;l.push({name:p,version:m,content:f})}return l}function Pe(e,t={}){let n=t.maxFileBytes??Rg,r=[],i=Te(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let o=t.includeBaseline!==!1,a=null;if(o)if(t.baseRef)a=t.baseRef;else{let m=oc(e);a=m?`origin/${m}`:null,a===null&&r.push(`no default branch resolvable ${Qn}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let m of i){let f=[];for(let y of m.files){let b=Ag(vg(e,y.path),n);if(b===null){r.push(`could not read ${y.path} \u2014 excluded from the fold`);continue}f.push({ref:y,content:b})}let h=f.map(({ref:y,content:b})=>({name:y.name,version:y.version,content:b})),g=a===null?null:Tg(e,m.dir,f,a,r);c.push(...Hc({dir:m.dir,files:h,baseFiles:g})),l.push({dir:m.dir,migrationCount:h.length,tableCount:Ki(h).size})}let u=l.reduce((m,f)=>m+f.migrationCount,0),d=Uc(u,c.length),p={open:0,info:1};return c.sort((m,f)=>p[m.status]-p[f.status]||m.id.localeCompare(f.id)),{ok:d!=="no_opinion"&&!c.some(m=>m.status==="open"),verdict:d,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var Kt,xg,Rg,Qn,Bi,Zn=_(()=>{"use strict";W();Lt();s($c,"stripSql");s(X,"normalizeQualifiedIdent");s(fe,"splitTopLevel");Kt=["INSERT","UPDATE","DELETE"];s(Eg,"parseDefaultAclTables");xg=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(jc,"parseTableRevoke");s(Ki,"foldTableAcl");s(Wi,"evaluateTableAcl");s(Hc,"computeTableAclFindings");s(Uc,"deriveTableAclVerdict");Rg=5e6,Qn="\u2014 findings reported ungraded (open)",Bi="\u2014 baseline degraded";s(Vi,"isTableAclGraded");s(Ag,"safeRead");s(Tg,"baseFilesFor");s(Pe,"checkTableAclLint")});import{readFileSync as Ig}from"node:fs";import{join as qi}from"node:path";function Ji(e){return e.verdict!=="no_opinion"&&e.graded}function Yi(e){let t=new Set;for(let n of e.matchAll(Cg))t.add(n[1]);return t}function Xi(e){return new Set([...e].map(t=>t.split("-")[0]))}function qc(e){return e.split(`
9
+ [Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},p=o.hooks?.[t.event]??[],d={...o,hooks:{...o.hooks??{},[t.event]:[...p,l]}},u=JSON.stringify(d,null,2)+`
10
+ `;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:n};try{await L(n,u,384)}catch(f){return{target:r,action:"merge",status:"failed",detail:`write: ${ti(f)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function ma(e){let t=ri.join(e.homeDir,ua);return fa(e,{event:"SessionStart",command:`cat ${t}`,timeout:5,matchPattern:/maind-session-start-reminder\.md/,targetKey:"hook:~/.claude/settings.json",skipDetail:s(()=>"SessionStart hook already references the reminder file","skipDetail"),consentDescription:`It 'cat's ${ua} into every new Claude Code session.`})}function jm(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function ii(e,t){let n=e.launch??ee({entryPath:te(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=Je(n);return fa(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:jm(t),skipDetail:s(i=>{let o=`${t.label} already runs maind ${t.subcommand}`;return Sn(i)?`${o}, but via the retired @maind/claude-code-hook \u2014 the bridge now owns that subcommand and that package is not published. Replace its command with: ${r}`:vn(i)?`${o}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:o},"skipDetail"),consentDescription:t.consentDescription})}async function ha(e){let t=[];for(let n of Zr)t.push(await ii(e,n));return t}function Hm(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!ni(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!ni(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function Um(e,t){e.write(t);let n=pa.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function ni(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ti(e){return e instanceof Error?e.message:String(e)}var ua,oi=_(()=>{"use strict";ce();Ye();Ot();ua=".claude/maind-session-start-reminder.md";s(fa,"mergeClaudeHook");s(ma,"mergeSessionStartHook");s(jm,"targetKeyFor");s(ii,"mergeSubcommandHook");s(ha,"mergeAllSubcommandHooks");s(Hm,"findExistingHookCommand");s(Um,"promptYesNo");s(ni,"isObject");s(ti,"errMessage")});import{existsSync as Gm,readFileSync as Wm}from"node:fs";import{join as Km}from"node:path";function de(){return Km(Tt(),"config.json")}function ne(){try{let e=de();if(!Gm(e))return null;let t=JSON.parse(Wm(e,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r={};return typeof n.auto_announce=="boolean"&&(r.auto_announce=n.auto_announce),typeof n.machine_label=="string"&&(r.machine_label=n.machine_label),typeof n.auto_working_paths=="boolean"&&(r.auto_working_paths=n.auto_working_paths),(n.guard_mode==="off"||n.guard_mode==="warn"||n.guard_mode==="block")&&(r.guard_mode=n.guard_mode),typeof n.guard_stop_gate=="boolean"&&(r.guard_stop_gate=n.guard_stop_gate),(n.gateway_mode==="off"||n.gateway_mode==="warn"||n.gateway_mode==="enforce")&&(r.gateway_mode=n.gateway_mode),typeof n.gateway_attest=="boolean"&&(r.gateway_attest=n.gateway_attest),(n.gateway_sha_proof==="off"||n.gateway_sha_proof==="warn"||n.gateway_sha_proof==="enforce")&&(r.gateway_sha_proof=n.gateway_sha_proof),r}catch{return null}}var Xe=_(()=>{"use strict";B();s(de,"bridgeConfigPath");s(ne,"readBridgeConfig")});import{execFileSync as Qm}from"node:child_process";import{createHash as Zm}from"node:crypto";function si(e){return Zm("sha256").update(e).digest("hex")}function eh(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function th(e){let t=eh(e);return t?si(t):null}function rh(e){return typeof e=="string"&&nh.test(e)}function Sa(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(rh(t))return t;let n;try{n=Qm("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?th(n):null}var nh,ai=_(()=>{"use strict";s(si,"sha256Hex");s(eh,"normalizeRemoteUrl");s(th,"projectKeyFromRemote");nh=/^[a-f0-9]{64}$/;s(rh,"isProjectKey");s(Sa,"computeProjectKey")});function Tn(e){return`${e}#<module>`}function In(e,t,n){return`${e}#${t}:${n}`}var Mt=_(()=>{"use strict";s(Tn,"moduleKey");s(In,"symbolKey")});function Cn(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}function ci(e){return e.toLowerCase().endsWith(".d.ts")}var Nn=_(()=>{"use strict";s(Cn,"languageForPath");s(ci,"isSkippablePath")});function Pn(){return{nodes:[],edges:[],refs:[],imports:[]}}function _e(e){return e+1}function Dn(e){return(e.text.split(`
11
+ `,1)[0]??"").trim().slice(0,200)}function ih(e){if(!e)return null;switch(e.type){case"identifier":case"property_identifier":case"type_identifier":return e.text;case"member_expression":return e.childForFieldName("property")?.text??null;case"attribute":return e.childForFieldName("attribute")?.text??null;default:return null}}function oh(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=ih(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Qe(e,t,n,r){for(let i of oh(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}var On=_(()=>{"use strict";s(Pn,"newResult");s(_e,"line1");s(Dn,"signatureOf");s(ih,"calleeName");s(oh,"collectCallTargets");s(Qe,"addCallRefs")});function xa(e,t){let n=Pn();for(let r of e.namedChildren)sh(r,t,n);return n}function Ra(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function sh(e,t,n){let r=Ra(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??ch(r);o&&n.imports.push({fromModuleKey:t.moduleKey,specifier:o});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let o=Mn(r,t,i,i,"function");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&Qe(n,o.nodeKey,a,Ea);return}case"class_definition":ah(r,t,n);return;case"expression_statement":{let o=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(o&&o.type==="identifier"){let a=Mn(r,t,o.text,o.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function ah(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Mn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let o=e.childForFieldName("superclasses");if(o){for(let c of o.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=Ra(c);if(l.type!=="function_definition")continue;let p=l.childForFieldName("name")?.text;if(!p)continue;let d=`${r}.${p}`,u=Mn(l,t,p,d,"method");n.nodes.push(u),n.edges.push({srcKey:i.nodeKey,dstKey:u.nodeKey,kind:"contains"});let f=l.childForFieldName("body");f&&Qe(n,u.nodeKey,f,Ea)}}function Mn(e,t,n,r,i){return{nodeKey:In(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:_e(e.startPosition.row),endLine:_e(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Dn(e),doc:null}}function ch(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var Ea,Aa=_(()=>{"use strict";Mt();On();Ea="call";s(xa,"extractPython");s(Ra,"unwrapDecorated");s(sh,"handleTopLevel");s(ah,"addClass");s(Mn,"makeNode");s(ch,"firstDottedName")});function Ca(e,t){let n=Pn();for(let r of e.namedChildren)dh(r,t,n);return n}function lh(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function dh(e,t,n){let r=lh(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:ph(i)});return}case"function_declaration":case"generator_function_declaration":{Ta(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{uh(r,t,n);return}case"interface_declaration":li(r,t,n,"interface");return;case"type_alias_declaration":li(r,t,n,"type_alias");return;case"enum_declaration":li(r,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let i of r.namedChildren){if(i.type!=="variable_declarator")continue;let o=i.childForFieldName("name");if(!o||o.type!=="identifier")continue;let a=i.childForFieldName("value"),c=a?.type==="arrow_function"||a?.type==="function_expression"||a?.type==="function";Ta(i,t,n,c?"function":"variable",o,a)}return}default:return}}function Ta(e,t,n,r,i,o){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=Fn(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let p=o??e.childForFieldName("body")??e;r==="function"&&p&&Qe(n,l.nodeKey,p,Ia)}function li(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=Fn(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}function uh(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Fn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let a of e.descendantsOfType("class_heritage"))for(let c of a.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let p of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:p.text});for(let p of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:p.text})}let o=e.childForFieldName("body");if(o)for(let a of o.namedChildren){if(a.type!=="method_definition")continue;let c=a.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,p=Fn(a,t,c,l,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let d=a.childForFieldName("body");d&&Qe(n,p.nodeKey,d,Ia)}}function Fn(e,t,n,r,i){return{nodeKey:In(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:_e(e.startPosition.row),endLine:_e(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Dn(e),doc:null}}function ph(e){return e.replace(/^["'`]|["'`]$/g,"")}var Ia,Na=_(()=>{"use strict";Mt();On();Ia="call_expression";s(Ca,"extractTypescript");s(lh,"unwrapExport");s(dh,"handleTopLevel");s(Ta,"addFunctionLike");s(li,"addSimpleNamed");s(uh,"addClass");s(Fn,"makeNode");s(ph,"stripQuotes")});import{createRequire as fh}from"node:module";import{join as mh}from"node:path";function Oa(e,t){return t?mh(t,Pa[e]):fh(import.meta.url).resolve(`tree-sitter-wasms/out/${Pa[e]}`)}var Pa,Da,Ma=_(()=>{"use strict";Pa={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Da="tree-sitter.wasm";s(Oa,"grammarPath")});import{join as hh}from"node:path";import di from"web-tree-sitter";var gh,Ln,Fa=_(()=>{"use strict";Mt();Nn();Aa();Na();On();Ma();gh=["typescript","tsx","javascript","python"],Ln=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await di.init(this.assetDir?{locateFile:s(t=>hh(this.assetDir,t||Da),"locateFile")}:void 0),this.parser=new di,this.initialized=!0)}supports(t){return gh.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let o=i.parse(n);if(!o)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[]};let a=o.rootNode,c=Tn(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:_e(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},p={filePath:t,language:r,source:n,moduleKey:c},d=r==="python"?xa(a,p):Ca(a,p);return o.delete(),{filePath:t,language:r,nodes:[l,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await di.Language.load(Oa(t,this.assetDir)),this.grammars.set(t,n)),n}}});function La(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
12
+ `).slice(0,1e3)}var $a=_(()=>{"use strict";s(La,"nodeEmbedText")});var ui,pi=_(()=>{"use strict";ui=["function","method","class","interface","enum","type_alias"]});function ja(e,t){let n=Math.min(e.length,t.length),r=0,i=0,o=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,i+=c*c,o+=l*l}return i===0||o===0?0:r/(Math.sqrt(i)*Math.sqrt(o))}var Ha=_(()=>{"use strict";s(ja,"cosineSimilarity")});import{posix as fi}from"node:path";function Ua(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!yh.has(r.kind))continue;let i=t.get(r.name);i?i.push(r.nodeKey):t.set(r.name,[r.nodeKey])}return{nameToKeys:t,files:n}}function Ga(e,t){let n=new Set,r=[],i=new Set,o=s((a,c,l)=>{if(a===c)return;let p=`${a}\0${c}\0${l}`;n.has(p)||(n.add(p),r.push({srcKey:a,dstKey:c,kind:l}),i.add(a))},"push");for(let a of e.edges)o(a.srcKey,a.dstKey,a.kind);for(let a of e.nodes)i.add(a.nodeKey);for(let a of e.refs){let c=t.nameToKeys.get(a.targetName);!c||c.length!==1||o(a.fromKey,c[0],a.kind)}for(let a of e.imports){let c=bh(e.filePath,a.specifier,t.files);c&&o(a.fromModuleKey,Tn(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}function bh(e,t,n){if(!t.startsWith("."))return null;let r=fi.normalize(fi.join(fi.dirname(e),t)),i=[],o=$n.some(c=>r.endsWith(c));o&&i.push(r);let a=/\.(js|jsx|mjs|cjs)$/.exec(r);if(a){let c=r.slice(0,-a[0].length);for(let l of $n)i.push(c+l)}if(!o){for(let c of $n)i.push(r+c);for(let c of $n)i.push(`${r}/index${c}`)}for(let c of i)if(n.has(c))return c;return null}var yh,$n,Wa=_(()=>{"use strict";Mt();yh=new Set(["function","method","class","interface","enum","type_alias"]),$n=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];s(Ua,"buildResolutionIndex");s(Ga,"resolveFileEdges");s(bh,"resolveImportTarget")});import{execFileSync as _h}from"node:child_process";import{createHash as wh}from"node:crypto";import{readdirSync as kh,statSync as vh}from"node:fs";import{posix as qa,sep as Ka}from"node:path";function S(e,t){try{return _h("git",[...Sh,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function Eh(e){return Ka==="/"?e:e.split(Ka).join("/")}function jn(e){let t=[];for(let n of e){let r=Eh(n).trim();if(!r||ci(r))continue;let i=Cn(r);i&&t.push({path:r,language:i})}return t}function za(e){return jn(e)}function Ja(e){let t=Ze(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return jn(t.split(`
13
+ `));let n=[];return Ya(e,"",n),jn(n)}function Ya(e,t,n){let r;try{r=kh(qa.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&Ba.has(i.name)||Ba.has(i.name))continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?Ya(e,o,n):i.isFile()&&n.push(o)}}function mi(e,t){let r=S(e,["merge-base",t,"HEAD"])?.trim();return r&&r.length>0?r:t}function Hn(e,t={}){if(Ft(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?mi(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let o=Ze(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of o.split(`
14
+ `)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let p=l[0][0],d=Va((l.length>=3?l[l.length-1]:l[1]).trim());d&&(p==="A"||p==="C"?a.set(d,"added"):p==="R"?a.set(d,"renamed"):a.set(d,"modified"))}if(n){let c=Ze(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
15
+ `)){if(l.length<4)continue;let p=l[0],d=l[1];if(p==="D"||d==="D")continue;let u=l.slice(3),f=u.indexOf(" -> ");f>=0&&(u=u.slice(f+4)),u=Va(u),!(!u||a.has(u))&&(p==="?"||p==="A"||d==="A"?a.set(u,"added"):p==="R"?a.set(u,"renamed"):a.set(u,"modified"))}}return a}function Va(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Xa(e,t={}){let n=Hn(e,t);return n===null?null:jn(n.keys())}function Qa(e,t){try{let n=vh(qa.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Un(e){return wh("sha256").update(e).digest("hex")}function Ft(e){return Ze(e,["rev-parse","HEAD"])?.trim()??null}function Gn(e,t){return Ze(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function Za(e){let t=Ze(e,["status","--porcelain","-uall"]);return t!==null&&t.trim().length>0}var Ba,Sh,Ze,W=_(()=>{"use strict";Nn();Ba=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),Sh=["-c","diff.renames=true","-c","core.quotePath=false"];s(S,"runGit");Ze=S;s(Eh,"toPosix");s(jn,"classify");s(za,"classifyPaths");s(Ja,"discoverSourceFiles");s(Ya,"walk");s(mi,"resolveDiffBase");s(Hn,"enumerateChangedPaths");s(Va,"unquote");s(Xa,"changedSourceFiles");s(Qa,"statFile");s(Un,"hashContent");s(Ft,"headCommit");s(Gn,"resolveCommitSha");s(Za,"isWorktreeDirty")});function tc(e,t={}){if(S(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?mi(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let o=S(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(o,"utf8")>xh?c="none":Ih(o,a,()=>{c="partial"}),n){let l=S(e,["status","--porcelain","-uall"])??"";for(let p of l.split(`
16
+ `)){if(p.length<4||p[0]!=="?")continue;let d=p.slice(3);d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),!(!d||a.has(d))&&a.set(d,{path:d,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:a,coverage:c}}function Ih(e,t,n){let r=null,i=0,o=!1,a=!1,c=s(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
17
+ `)){if(l.startsWith("diff --git ")){c(),o=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){o=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let d=l.slice(4).trim();if(d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),d.startsWith("b/")&&(d=d.slice(2)),d==="/dev/null")continue;r={path:d,status:a?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let p=Th.exec(l);if(p){if(i++,i>Rh){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let d=Number(p[1]),u=p[2]===void 0?1:Number(p[2]);u>0?r.addedRanges.push({start:d,end:d+u-1}):r.deletionPoints.push(d);continue}l.startsWith("+")&&!l.startsWith("+++")&&!r.degraded&&r.addedLines.length<Ah&&r.addedLines.push(l.slice(1))}c()}var xh,Rh,Ah,ec,Th,nc=_(()=>{"use strict";W();xh=16*1024*1024,Rh=500,Ah=4e3,ec=256*1024,Th=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(tc,"changedHunks");s(Ih,"parseUnifiedDiff")});function Ph(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function ic(e){return e.split(Ch).filter(t=>t.trim().length>0)}function oc(e){let[t,n,r,i,o]=e.replace(/\n+$/,"").split(Nh);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:o??""}}function Dh(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,i=t.get(r);i?i.commits+=1:t.set(r,{name:n.authorName,email:n.authorEmail,commits:1,lastDateIso:n.dateIso})}return[...t.values()].sort((n,r)=>r.commits-n.commits||n.email.localeCompare(r.email)).slice(0,10)}function ac(e,t,n={}){let r=Ph(n.limit,20,100),i=n.includeOwnership!==!1,o=Math.max(r,sc),a=t.map(d=>d.trim()).filter(d=>d.length>0&&!d.startsWith(":")),c=a.slice(0,hi),l=[];for(let d of c){let u=S(e,["log","-n",String(o),rc,"--",d]),f=u===null?[]:ic(u).map(oc).filter(m=>m!==null);l.push({path:d,lastCommits:f.slice(0,r),ownership:i?{topAuthors:Dh(f),commitsInWindow:f.length}:null})}let p=null;if(n.since){let d=Gn(e,n.since),u=d!==null?[`${d}..HEAD`]:[`--since=${n.since}`],f=S(e,["log",...u,"-n",String(Wn+1),rc,"--name-only","--",...c]),m=[];if(f!==null)for(let h of ic(f)){let g=h.split(`
18
+ `),y=oc(g[0]??"");if(!y)continue;let b=g.slice(1).filter(w=>w.trim().length>0).length;m.push({sha:y.sha,dateIso:y.dateIso,authorName:y.authorName,subject:y.subject,filesTouched:b})}p={sinceInput:n.since,sinceResolved:d,commits:m.slice(0,Wn),truncated:m.length>Wn}}return{history:l,regression:p,ownershipWindowCommits:o,pathsTruncated:a.length>hi}}var Ch,Nh,sc,hi,Wn,rc,gi=_(()=>{"use strict";W();Ch="",Nh="\0",sc=200,hi=50,Wn=100,rc="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";s(Ph,"clamp");s(ic,"splitRecords");s(oc,"parseHistoryRecord");s(Dh,"aggregateOwnership");s(ac,"readFileHistory")});import{execFileSync as Oh}from"node:child_process";import{readdirSync as Mh,statSync as cc}from"node:fs";import{isAbsolute as Fh,join as yi,relative as Lh,resolve as $h}from"node:path";function Hh(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function Uh(e,t){try{let n=Oh("git",["-C",e,"config","--get",t],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n.length>0?n:null}catch{return null}}function Gh(e){let t;try{t=Mh(e)}catch{return null}for(let n of t.filter(Hh))try{let r=cc(yi(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function Wh(e){try{return cc(e).isDirectory()}catch{return!1}}function Kh(e,t){let n=Lh(e,t);return!n||n.startsWith("..")?t:n}function bi(e){let t=jh.filter(c=>Wh(yi(e,c))),n=Uh(e,"core.hooksPath"),r=n?Fh(n)?n:$h(e,n):yi(e,".git","hooks"),i=Kh(e,r),o=Gh(r);if(o===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?o===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:a,hookDirs:t,hooksPath:n,effectiveDir:i}}function _i(e){switch(e.reason){case"wired":return`Git-Gates aktiv (core.hooksPath \u2192 ${e.effectiveDir}).`;case"default_path":return"Git-Gates aktiv (.git/hooks, nicht versioniert).";case"path_unset":return`${e.hookDirs.join(", ")} liegt im Repo, aber core.hooksPath ist ungesetzt \u2014 kein Gate feuert.`;case"path_missing":return`core.hooksPath zeigt auf ${e.effectiveDir}, das es nicht gibt \u2014 git f\xFChrt keinen Hook aus.`;case"path_empty":return`core.hooksPath zeigt auf ${e.effectiveDir}, dort liegt kein ausf\xFChrbarer Hook.`;case"no_hooks":return"Keine Git-Hooks im Repo."}}var jh,wi=_(()=>{"use strict";jh=[".githooks",".husky"];s(Hh,"isRealHook");s(Uh,"gitConfig");s(Gh,"hasExecutableHook");s(Wh,"isDir");s(Kh,"displayPath");s(bi,"resolveHookState");s(_i,"describeHookState")});import{posix as lc}from"node:path";function et(e){let t=Bh.exec(e);return t?t[1]:null}function ue(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Te(e,t){let n=S(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=s(o=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||o===c||o.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let o of n.split("\0").filter(Boolean)){if(!r(o))continue;let a=lc.basename(o),c=et(a);if(c===null)continue;let l=lc.dirname(o),p=i.get(l)??[];p.push({path:o,name:a,version:c}),i.set(l,p)}return[...i.entries()].map(([o,a])=>({dir:o,files:a.sort((c,l)=>ue(c.version,l.version))})).sort((o,a)=>o.dir.localeCompare(a.dir))}function dc(e){let t=S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var Bh,Lt=_(()=>{"use strict";W();Bh=/^(\d+)_.+\.sql$/;s(et,"parseMigrationVersion");s(ue,"compareVersions");s(Te,"discoverSupabaseProjects");s(dc,"resolveDefaultBranch")});import{execFileSync as Vh}from"node:child_process";import{existsSync as H,readFileSync as we,readdirSync as Kn,statSync as vi}from"node:fs";import{posix as x}from"node:path";function Yh(e,t){let n=(()=>{let i=S(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=x.dirname(e);for(let i=0;i<8&&r&&r!==x.dirname(r);i++){if(H(x.join(r,".git"))){let o=(()=>{let c=S(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&o!=null&&Ei(n,o))){let c=Xh(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=x.dirname(r)}return null}function Xh(e,t){let n=[];for(let r of zh){let i;try{i=Kn(x.join(e,r),{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>o.name)}catch{continue}for(let o of i){let a=`${r}/${o}`,c=x.join(e,a),l=x.join(t,a);try{let p=vi(c),d=vi(l);if(!d.isFile())continue;if(p.size!==d.size){n.push(a);continue}if(p.size>Jh)continue;we(c).equals(we(l))||n.push(a)}catch{continue}}}return n.sort()}function yc(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let a=e.upstream.split("/").slice(1).join("/");a&&a!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;if(r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`}),e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let a=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${a} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let a=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${a.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${xi}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let a=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${a.map(c=>c.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:a.map(c=>`${c.install} (in ${x.dirname(c.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:a,diverging:c}=e.toolCopyDrift,l=c.slice(0,3).join(", "),p=c.length>3?` (+${c.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${a} ships ${l}${p} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${c[0]}\` from this repo root), not via a path into ${a}.`})}if(e.stalePackageBuilds.length>0){let a=e.stalePackageBuilds,c=s(p=>p.impact==="runtime"?`${p.packageDir} (runtime)`:p.packageDir,"label"),l=a.every(p=>p.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:a.some(p=>p.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${a.map(c).join(", ")}: src/ is newer than the built ${[...new Set(a.map(p=>p.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${l}`,hint:`Rebuild: pnpm --filter ./${a[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let o=Qh(e.hooks);return o&&t.push(o),Zh(t)}function Qh(e){return!e||e.verdict!=="present_unwired"?null:{id:"setup.hooks-unwired",status:"warn",scope:"setup",title:"Git-Hooks liegen im Repo, feuern aber nicht",detail:_i(e),hint:e.reason==="path_missing"?`core.hooksPath zeigt ins Leere. Korrigieren: git config core.hooksPath ${e.hookDirs[0]??".githooks"}`:`git config core.hooksPath ${e.hookDirs[0]??".githooks"} \u2014 git klont das Verzeichnis mit, den Pfad nie.`}}function Zh(e){return[...e].sort((t,n)=>uc[t.status]-uc[n.status]||t.id.localeCompare(n.id))}function bc(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function pe(e){let t=e?.trim();return t||null}function eg(e){let t=pe(S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function tg(e){let t=pe(S(e,["rev-parse","--git-dir"]));if(!t)return null;let n=x.isAbsolute(t)?t:x.join(e,t);return H(x.join(n,"rebase-merge"))||H(x.join(n,"rebase-apply"))?"rebase":H(x.join(n,"MERGE_HEAD"))?"merge":H(x.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function ng(e){let t=[],n=null,r=s(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
19
+ `))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function rg(e){let t=x.join(e,xi);if(!H(t))return[];try{return we(t,"utf8").split(`
20
+ `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function ig(e){try{return Te(e).map(t=>x.join(x.dirname(t.dir),"config.toml"))}catch{return[]}}function og(e){let t=S(e,["ls-files","-z","--",...qh]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=gc[x.basename(r)];if(i===void 0)continue;let o=x.dirname(r);if(!sg(e,o))continue;let a=o==="."?"node_modules":x.join(o,"node_modules");n.has(a)||n.set(a,{dir:a,install:i})}return[...n.values()]}function sg(e,t){return t==="."?!0:Si(e,t)}function Si(e,t){if(H(x.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(we(x.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function _c(e,t={}){if(pe(S(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,branch:null,defaultBranch:null,upstream:null,headMatchesUpstream:null,remoteTrackingExists:null,ahead:null,behind:null,uncommitted:0,detachedHead:!1,inProgressOp:null,isSharedMainTree:!1,otherWorktrees:0,worktreeParity:null,toolCopyDrift:null,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=pe(S(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",o=i?null:r,a=eg(e),c=pe(S(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,p=null;if(c){let T=pe(S(e,["rev-parse","HEAD"])),D=pe(S(e,["rev-parse","@{u}"]));l=T!=null&&D!=null?T===D:null,p=S(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let d=null,u=null;if(a){let T=pe(S(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(T){let[D,A]=T.split(/\s+/).map(N=>Number.parseInt(N,10));Number.isFinite(D)&&(u=D),Number.isFinite(A)&&(d=A)}}let m=(S(e,["status","--porcelain"])??"").split(`
21
+ `).filter(T=>T.trim().length>0).length,h=tg(e),g=pe(S(e,["rev-parse","--show-toplevel"]))??e,y=ng(S(e,["worktree","list","--porcelain"])??""),b=y[0]?.path??null,w=b!=null&&Ei(b,g),v=Math.max(0,y.length-1),k=null;if(b&&!Ei(b,g)){let T=s(A=>H(x.join(b,A))&&!H(x.join(g,A)),"here"),D=[...hc,...ig(g),...rg(g),...t.probePaths??[]];k={mainWorktreePath:b,currentWorktreePath:g,missing:[...new Set(D.filter(T))],missingDeps:og(g).filter(A=>T(A.dir))}}let E=Yh(g,e),R=t.includeRelease===!1?null:fg(e,o),I=[];return a&&(I=(S(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
22
+ `).map(D=>D.trim()).filter(D=>D.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:p,ahead:d,behind:u,uncommitted:m,detachedHead:i,inProgressOp:h,isSharedMainTree:w,otherWorktrees:v,worktreeParity:k,toolCopyDrift:E,stalePackageBuilds:wc(g),release:R,unmergedMigrations:I,hooks:bi(e)}}function Ei(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function lg(e){let t=new Set;Si(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<fc;){let i=n.pop();if(i===void 0)break;if(i.depth>=cg)continue;let o;try{o=Kn(x.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=i.rel==="."?a.name:x.join(i.rel,a.name);if(r+=1,r>=fc)break;Si(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function dg(e){let t=[];try{let n=x.join(e,"pnpm-workspace.yaml");if(H(n)){let r=!1;for(let i of we(n,"utf8").split(`
23
+ `)){let o=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(o)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(o);a?t.push(a[1]):o.trim().length>0&&!/^\s/.test(o)&&(r=!1)}}}else{let r=x.join(e,"package.json");if(H(r)){let i=JSON.parse(we(r,"utf8")),o=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(o)&&t.push(...o.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function ug(e){let t=[];for(let n of lg(e)){let r=n==="."?e:x.join(e,n),i=s(o=>n==="."?o:x.join(n,o),"prefix");for(let o of dg(r)){if(t.length>=ki)break;if(!(o.startsWith("!")||o.includes("**")))try{if(o.endsWith("/*")){let a=o.slice(0,-2),c=x.join(r,a);if(!H(c))continue;for(let l of Kn(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(x.join(a,l.name))),t.length>=ki)break}else o.includes("*")||t.push(i(o))}catch{}}}return t.slice(0,ki)}function mc(e){let t=null,n=0,r=[e];for(;r.length>0&&n<pc;){let i=r.pop();if(i===void 0)break;let o;try{o=Kn(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=x.join(i,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=vi(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=pc)break}}}return t}function pg(e,t){let n=new Set;for(let r of t)try{let i=x.join(e,r,"package.json");if(!H(i))continue;let o=JSON.parse(we(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=o[a];if(!(c===null||typeof c!="object"))for(let[l,p]of Object.entries(c))typeof p=="string"&&p.startsWith("workspace:")&&n.add(l)}}catch{}return n}function wc(e){let t=[],n=ug(e),r=pg(e,n);for(let i of n)try{let o=x.join(e,i,"package.json");if(!H(o))continue;let a=JSON.parse(we(o,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(b=>{if(typeof b!="string")return null;let w=b.replace(/^\.\//,"").split("/")[0];return w==="build"||w==="dist"?w:null},"builtSeg"),l=c(a.types??a.typings),p=c(a.main),d=l??p;if(d===null)continue;let u=l!==null&&p!==null?"both":l!==null?"types":"runtime",f=x.join(e,i,"src"),m=x.join(e,i,d);if(!H(f)||!H(m))continue;let h=mc(f),g=mc(m);if(h===null||g===null)continue;let y=h-g;y>ag&&t.push({packageDir:i,buildDir:d,srcNewerByMs:Math.round(y),impact:u})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}function fg(e,t){if(!t)return null;let n=mg(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(o=>o.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}function mg(e,t){try{return Vh("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function $t(e,t={}){let n=await _c(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=yc(n),i=bc(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var hc,xi,gc,qh,zh,Jh,uc,ag,ki,pc,cg,fc,Ri=_(()=>{"use strict";wi();W();Lt();hc=["supabase/config.toml","supabase/.temp",".env"],xi=".maind/worktree-requirements",gc={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},qh=Object.keys(gc).flatMap(e=>[e,"*/"+e]),zh=["scripts"],Jh=512*1024;s(Yh,"gatherToolCopyDrift");s(Xh,"compareToolDirs");s(yc,"computeDivergence");s(Qh,"computeHookFinding");uc={open:0,warn:1,info:2,passed:3};s(Zh,"sortFindings");s(bc,"isHealthy");s(pe,"trimOrNull");s(eg,"resolveDefaultBranch");s(tg,"detectInProgressOp");s(ng,"parseWorktrees");s(rg,"readWorktreeRequirements");s(ig,"discoverSupabaseConfigProbes");s(og,"discoverDependencyDirs");s(sg,"isWorkspaceRoot");s(Si,"hasWorkspaceMarkers");s(_c,"gatherRepoHealthFacts");s(Ei,"samePath");ag=2e3,ki=64,pc=4e3,cg=3,fc=400;s(lg,"findWorkspaceRoots");s(dg,"workspacePatternsAt");s(ug,"listWorkspacePackageDirs");s(mc,"newestMtimeUnder");s(pg,"consumedWorkspaceNames");s(wc,"gatherStalePackageBuilds");s(fg,"gatherReleaseFact");s(mg,"runGh");s($t,"checkDivergence")});import{existsSync as Ai,readdirSync as kc}from"node:fs";import{posix as re}from"node:path";function Ii(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Ti)}function Sc(e,t={}){let n=t.minFiles??Ci;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??vc)}function nt(e){return`${e.dir}#${e.prefix}`}function jt(e){let t=hg.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function Ec(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let o=nt(i),a=e.sightingsByNamespace.get(o);if(!a)continue;let c=new Set(a.keys());for(let[l,p]of a){let d=[...new Set(p.map(h=>h.path))];if(d.length<2)continue;let u=d.find(h=>n.has(h)),f=d.filter(h=>h!==u),m=`${i.prefix}${l}`;t.push(u?{id:`number.collision:${o}#${l}`,status:"open",namespace:i,number:l,title:`${m} is already taken`,detail:`This branch adds ${u}, but ${m} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${m} stop being unambiguous.`,ownPath:u,sightings:p.filter(h=>h.path!==u),suggestion:`${i.prefix}${Ni(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${o}#${l}`,status:"info",namespace:i,number:l,title:`${m} is used more than once (pre-existing)`,detail:`${m} is carried by ${d.length} files: ${d.join(", ")}.`,sightings:p,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,o)=>r[i.status]-r[o.status]||i.id.localeCompare(o.id))}function xc(e){return!e.some(t=>t.status==="open")}function Ni(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}function Pi(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Rc(e,t){let n=Pi(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=jt(re.basename(n));if(!i)return r;let o=`${re.dirname(n)}#${i.prefix}`,a=e.namespaces.find(d=>nt(d)===o)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(o)??new Map,l=new Set,p=[];for(let d of c.get(i.number)??[])d.path===n||l.has(d.path)||(l.add(d.path),p.push(d));return{path:n,namespace:a,number:i.number,taken:p.length>0,sightings:p,suggestion:Ni(c.keys(),i.number)}}function Bn(e){let t=e?.trim();return t||null}function tt(e){return e?e.split(`
24
+ `).filter(Boolean):[]}function gg(e){let t=Bn(S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Ac(e,t={}){let n=t.minFiles??Ci,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=S(e,r);if(i===null)return[];let o=new Map;for(let a of i.split("\0").filter(Boolean)){let c=re.dirname(a),l=jt(re.basename(a));if(!l)continue;let p=`${c}#${l.prefix}`,d=o.get(p);d?d.numbers.push(l.number):o.set(p,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...o.values()].filter(a=>Sc(a.numbers,{...t,minFiles:n})).map(a=>({dir:a.dir,prefix:a.prefix,fileCount:a.numbers.length,distinctRatio:new Set(a.numbers).size/a.numbers.length})).sort((a,c)=>nt(a).localeCompare(nt(c)))}async function Di(e,t={}){let n=[];if(Bn(S(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,baseRef:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=Ac(e,t),o=new Map(i.map(h=>[nt(h),h])),a=[...new Set(i.map(h=>h.dir))],c=new Map,l=s((h,g,y)=>{let b=re.dirname(h),w=jt(re.basename(h));if(!w)return;let v=`${b}#${w.prefix}`;if(!o.has(v))return;let k=c.get(v)??new Map,E=k.get(w.number)??[];E.push({kind:g,where:y,path:h}),k.set(w.number,E),c.set(v,k)},"record"),p=s((h,g,y)=>{if(a.length===0)return;let b=S(e,["ls-tree","-r","--name-only",h,"--",...a]);if(b===null){n.push(`could not read ${y}`);return}for(let w of tt(b))l(w,g,y)},"scanTree");for(let h of a){let g=re.join(e,h);if(Ai(g))try{for(let y of kc(g))l(`${h}/${y}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let d=gg(e),u=t.baseRef??(d?`origin/${d}`:null);u?p(u,"default_branch",u):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let f=Bn(S(e,["rev-parse","--abbrev-ref","HEAD"]));for(let h of tt(S(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))h!==f&&p(h,"branch",`Branch ${h}`);if(t.includeWorktrees!==!1){let h=Bn(S(e,["rev-parse","--show-toplevel"]));for(let g of tt(S(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===h||!Ai(y)))for(let b of a){let w=re.join(y,b);if(Ai(w))try{for(let v of kc(w))l(`${b}/${v}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${b} in ${y}`)}}}}let m=[];if(u&&a.length>0){let h=S(e,["diff","--name-only","--diff-filter=A",`${u}...HEAD`,"--",...a]);h===null?n.push(Ti):m=tt(h);let g=S(e,["ls-files","--others","--exclude-standard","--",...a]);g!==null&&(m=[...m,...tt(g)]);let y=S(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);y!==null&&(m=[...m,...tt(y)])}return{isRepo:!0,defaultBranch:d,baseRef:u,namespaces:i,sightingsByNamespace:c,addedPaths:m,skipped:n}}async function Ie(e,t={}){let n=await Di(e,t),r=Ec(n);return{ok:xc(r),findings:r,facts:n}}async function Ce(e,t,n={}){let r=Pi(t);if(!jt(re.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Di(e,{...n,dirs:n.dirs??[re.dirname(r)]});return Rc(i,r)}var Ti,hg,Ci,vc,Ht=_(()=>{"use strict";W();Ti="could not diff against the base ref \u2014 everything reported as info";s(Ii,"isNumberCollisionsGraded");hg=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Ci=3,vc=.8;s(Sc,"isCounterNamespace");s(nt,"namespaceKey");s(jt,"parseNumbered");s(Ec,"computeNumberCollisions");s(xc,"isCollisionFree");s(Ni,"suggestNextNumber");s(Pi,"normaliseRepoPath");s(Rc,"checkProposedNumber");s(Bn,"trimOrNull");s(tt,"lines");s(gg,"resolveDefaultBranch");s(Ac,"detectNamespaces");s(Di,"gatherNumberCollisionFacts");s(Ie,"checkNumberCollisions");s(Ce,"checkNumberForPath")});function $i(e){return`spec.${e}`}function rt(e,t={}){switch(e){case"open":return{level:"open",baseline:"introduced"};case"warn":return{level:"warn",baseline:"introduced"};case"info":return t.excepted?{level:"info",baseline:"introduced"}:{level:"open",baseline:"pre_existing"};default:throw new Error(`gradeEngineStatus: '${String(e)}' is not a finding status`)}}function yg(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let o=0;o<i;o++){let a=(n[o].codePointAt(0)??0)-(r[o].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function Tc(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(yg)}function Ut(e){return si(JSON.stringify(Tc(e)))}var Oi,Mi,Fi,Li,ji=_(()=>{"use strict";ai();Oi={det_number_collisions:{version:"1.1.0",rules:["number.collision"]},det_spec_drift:{version:"1.1.0",rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"]},det_theme_class_drift:{version:"1.1.0",rules:["theme.dead_class"]},det_table_acl_lint:{version:"1.0.0",rules:["acl.missing_revoke"]}},Mi="number.collision",Fi="theme.dead_class",Li="acl.missing_revoke";s($i,"specDriftRuleId");s(rt,"gradeEngineStatus");s(yg,"codePointCompare");s(Tc,"normalizeEvidenceForHash");s(Ut,"hashDetectorEvidence")});import{existsSync as bg,readFileSync as Ic}from"node:fs";import{posix as _g}from"node:path";function zn(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}function Jn(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
25
+ `,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}function Gt(e){return e==='"'||e==="'"||e==="`"}function Yn(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function Vn(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let o=e[i];if(Gt(o)){i=zn(e,i);continue}if(Yn(e,i)){i=Jn(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function wg(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Yn(e,t)){t=Jn(e,t);continue}break}return e.slice(t)}function it(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let o=e[i];if(Gt(o)){i=zn(e,i);continue}if(Yn(e,i)){i=Jn(e,i);continue}o==="["||o==="{"||o==="("?n++:o==="]"||o==="}"||o===")"?n--:o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(o=>wg(o).trim()).filter(o=>o.length>0)}function Dc(e){let t=zn(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
26
+ `:i==="r"?"\r":i==="t"?" ":i)}function kg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ui(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${kg(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,o=!1;for(;i<e.length;){let a=e[i];if(Gt(a)){i=zn(e,i);continue}if(Yn(e,i)){i=Jn(e,i);continue}if(!o){if(a==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))o=!0;else if(a===";")return null;i++;continue}if(a==="[")return Vn(e,i);if(a===";")return null;i++}return null}function Gi(e){let t={};if(!e.startsWith("{"))return t;for(let n of it(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],o=r[4].trim();Gt(o[0]??"")&&(t[i]=Dc(o))}return t}function vg(e,t){if(!e.startsWith("{"))return null;for(let n of it(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===t)return r[4].trim()}return null}function Oc(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Mc(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Fc(e,t){let n=Ui(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Mc(),i=[],o=0;for(let a of it(n.slice(1,-1))){if(!a.startsWith("{")){o++;continue}let c=Gi(a),l=c[t.key_field];if(!l){o++;continue}let p=(t.partition_by??[]).map(d=>c[d]??"");i.push({key:l,fields:Oc(c,t.fields),orderPath:p,ordinal:r(p)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function Lc(e,t){let n=Ui(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};if(t.levels.length===0)return{records:[],error:`contract declares no levels for \`${t.symbol}\``,dropped:0};let r=Mc(),i=[],o=0,a=s((c,l,p)=>{let d=t.levels[l],u=l===t.levels.length-1;for(let f of it(c.slice(1,-1))){let m={...p},h=null;if(d.shape==="object"){if(!f.startsWith("{")){o++;continue}let g=Gi(f);for(let[y,b]of Object.entries(d.fields??{}))m[y]=g[String(b)]??"";if(!u&&typeof d.children=="string"){let y=vg(f,d.children);h=y&&y.startsWith("[")?Vn(y,0):null}}else{if(!f.startsWith("[")){o++;continue}let g=it(f.slice(1,-1));for(let[y,b]of Object.entries(d.fields??{})){let w=g[Number(b)];m[y]=w!==void 0&&Gt(w[0]??"")?Dc(w):""}if(!u&&typeof d.children=="number"){let y=g[d.children];h=y!==void 0&&y.startsWith("[")?Vn(y,0):null}}if(u){let g=m[t.key_field];if(!g){o++;continue}let y=(t.partition_by??[]).map(b=>m[b]??"");i.push({key:g,fields:Oc(m,t.fields),orderPath:y,ordinal:r(y)});continue}h!==null&&a(h,l+1,m)}},"walk");return a(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function Cc(e,t){return t.extractor==="object-array"?Fc(e,t):Lc(e,t)}function $c(e,t,n){let r=e;return t.strip_prefix&&r.startsWith(t.strip_prefix)&&(r=r.slice(t.strip_prefix.length)),t.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}function jc(e,t,n){return`spec.drift:${e}#${t}:${n}`}function Sg(e){return e.orderPath.join(" / ")||"(flat)"}function Hc(e,t,n,r){let i=[],o=s((p,d,u,f,m,h)=>{i.push({id:jc(e.id,p,u),contract:e.id,dimension:p,status:d,key:u,title:f,detail:m,hint:h})},"push"),a=new Map(n.map(p=>[p.key,p])),c=new Map(t.map(p=>[p.key,p]));for(let p of t){let d=a.get(p.key);if(!d){o("coverage","open",p.key,`${p.key} is declared by the specification but missing from the implementation`,`Partition ${Sg(p)}, position ${p.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let u of e.compare_fields??[]){let f=p.fields[u]??"",m=d.fields[u]??"";f!==m&&o("fields","open",`${p.key}.${u}`,`${p.key}: ${u} is "${m||"\u2014"}", the specification says "${f||"\u2014"}"`,`Field \`${u}\` disagrees between the two sides.`)}}let l=new Map;for(let p of t){let d=p.orderPath.join("\0"),u=l.get(d);u?u.push(p):l.set(d,[p])}for(let[p,d]of l){let u=d.filter(g=>a.has(g.key)).map(g=>g.key),f=n.filter(g=>g.orderPath.join("\0")===p).filter(g=>c.has(g.key)).map(g=>g.key),m=new Set(f),h=u.filter(g=>m.has(g));if(f.join("|")!==h.join("|")){let g=p.split("\0").join(" / ")||"(flat)";o("order","open",g,`Partition ${g}: sequence differs from the specification`,`implementation: ${f.join(" \u2192 ")}
27
+ specification: ${h.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let p of n)c.has(p.key)||o("extra","warn",p.key,`${p.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let p of new Set([...a.keys(),...c.keys()])){if($c(p,e.grounding,r))continue;let d=a.has(p);o("unrealized",d?"open":"warn",p,d?`${p} is referenced by the implementation but has no artefact`:`${p} is declared by the specification but not built yet`,d?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}function Eg(e,t,n){let r=[];for(let i of e.assertions??[]){let o=n.get(i.path);if(!o)continue;let a=o.indexOf(i.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(o.slice(a+i.prefix.length));if(!c)continue;let l=Number(c[1]),p=t[i.counts];l!==p&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${p}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function Nc(e,t){return{id:`contract.unreadable:${e}`,contract:e,dimension:"contract",status:"open",key:null,title:`Contract "${e}" could not be evaluated`,detail:t,hint:"This is NOT a drift finding. An anchor moved, or a declared file is gone \u2014 repair the contract in the manifest, then re-run. Nothing has been compared for this contract."}}function Uc(e,t={}){let n=s(d=>({ok:!1,verdict:"no_opinion",reason:d,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(d=>t.contracts.includes(d.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(d=>`"${d}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=s(d=>{let u=[],f=[];for(let m of r){let h=d.get(m.spec.path),g=d.get(m.impl.path);if(h==null||g==null){let v=h==null?m.spec.path:m.impl.path;u.push(Nc(m.id,`Declared file could not be read: ${v}`)),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let y=Cc(h,m.spec),b=Cc(g,m.impl);if(y.error||b.error){u.push(Nc(m.id,y.error??b.error??"unknown")),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let w=y.dropped>0||b.dropped>0;f.push({id:m.id,measured:!0,specRecords:y.records.length,implRecords:b.records.length,partial:w}),w&&u.push({id:`contract.partial:${m.id}`,contract:m.id,dimension:"contract",status:"warn",key:null,title:`Contract "${m.id}" was measured incompletely`,detail:`${y.dropped} specification and ${b.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),u.push(...Hc(m,y.records,b.records,e.files)),u.push(...Eg(m,{spec:y.records.length,impl:b.records.length},d))}return{findings:u,contracts:f}},"runOnce"),o=i(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let d of i(e.baselineSources).findings)d.id.startsWith("contract.unreadable:")||a.add(d.id);let c=new Map;for(let d of r)for(let u of d.exceptions??[])c.set(jc(d.id,u.dimension,u.key),u);let l=o.findings.map(d=>{let u=c.get(d.id);return u?{...d,status:"info",exceptionReason:u.reason}:a.has(d.id)?{...d,status:"info",detail:`${d.detail}
28
+ Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:d});l.sort((d,u)=>Pc[d.status]-Pc[u.status]||d.id.localeCompare(u.id));let p=l.some(d=>d.status==="open");return{ok:!p,verdict:p?"drifted":"aligned",reason:null,findings:l,contracts:o.contracts}}function Hi(e){let t=e?.trim();return t||null}function Xn(e){let t;try{t=JSON.parse(e)}catch(a){return{manifest:null,error:`manifest is not valid JSON: ${a.message}`}}let n=s(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,"obj"),r=s(a=>typeof a=="string"?a:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let o=s(a=>({manifest:null,error:a}),"bad");for(let[a,c]of i.contracts.entries()){let l=n(c),p=r(l?.id),d=p?`contract "${p}"`:`contract #${a+1}`;if(!l)return o(`${d}: not an object`);if(!p)return o(`${d}: \`id\` is missing`);if(!r(l.reason))return o(`${d}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let u of["spec","impl"]){let f=n(l[u]);if(!f)return o(`${d}: \`${u}\` is missing`);let m=r(f.extractor);if(!m)return o(`${d}: \`${u}.extractor\` is missing`);if(m!=="object-array"&&m!=="nested-literal-list")return o(`${d}: unknown \`${u}.extractor\` "${m}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return o(`${d}: \`${u}\` needs \`path\`, \`symbol\` and \`key_field\``);if(m==="nested-literal-list"&&!Array.isArray(f.levels))return o(`${d}: \`${u}\` is a nested-literal-list and needs \`levels\``)}for(let u of Array.isArray(l.exceptions)?l.exceptions:[]){let f=n(u);if(!f||!r(f.reason))return o(`${d}: exception for "${r(f?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}function xg(e){let t=Hi(S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Rg(e){let t=new Set;for(let n of e.contracts){t.add(n.spec.path),t.add(n.impl.path);for(let r of n.assertions??[])t.add(r.path)}return[...t]}async function Gc(e,t={}){let n=s((h,g)=>_g.join(h,g),"join"),r=t.manifestPath??qn,i=[],o={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(Hi(S(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...o,manifestError:"not a git work tree"};let a=n(e,r);if(!bg(a))return{...o,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,l=null;try{({manifest:c,error:l}=Xn(Ic(a,"utf8")))}catch(h){l=`manifest at ${r} could not be read: ${h.message}`}if(!c)return{...o,isRepo:!0,manifestError:l};let p=new Map;for(let h of Rg(c))try{p.set(h,Ic(n(e,h),"utf8"))}catch{p.set(h,null),i.push(`declared file unreadable in the working tree: ${h}`)}let d=new Set,u=S(e,["ls-files","-z"]);if(u===null)i.push("could not list tracked files \u2014 grounding is skipped");else for(let h of u.split("\0"))h&&d.add(h);let f=null,m=new Map;if(t.includeBaseline!==!1){let h=t.baseRef?null:xg(e),g=t.baseRef??(h?`origin/${h}`:null);if(!g)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(f=Hi(S(e,["merge-base",g,"HEAD"])),!f)i.push(`no merge-base with ${g} \u2014 every finding reported as new`);else for(let y of p.keys())m.set(y,S(e,["show",`${f}:${y}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:p,baselineSources:m,baseRef:f,files:d,skipped:i}}async function Ne(e,t={}){let n=await Gc(e,t);return{...Uc(n,t),facts:n}}function Wi(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var qn,Pc,Wt=_(()=>{"use strict";W();qn=".maind/spec-contracts.json";s(zn,"endOfString");s(Jn,"skipComment");s(Gt,"isQuote");s(Yn,"isCommentStart");s(Vn,"sliceBalanced");s(wg,"stripLeadingTrivia");s(it,"splitTopLevel");s(Dc,"readStringLiteral");s(kg,"escapeRe");s(Ui,"findSymbolArray");s(Gi,"parseObjectFields");s(vg,"objectFieldRaw");s(Oc,"pickFields");s(Mc,"makeOrdinals");s(Fc,"extractObjectArray");s(Lc,"extractNestedList");s(Cc,"extractRecords");s($c,"isGrounded");s(jc,"findingId");s(Sg,"partitionOf");s(Hc,"compareContract");s(Eg,"checkAssertions");s(Nc,"unreadable");Pc={open:0,warn:1,info:2,passed:3};s(Uc,"computeSpecDrift");s(Hi,"trimOrNull");s(Xn,"parseManifest");s(xg,"resolveDefaultBranch");s(Rg,"declaredPaths");s(Gc,"gatherSpecDriftFacts");s(Ne,"checkSpecDrift");s(Wi,"isSpecDriftGraded")});import{readFileSync as Ag}from"node:fs";import{join as Tg,posix as Ig}from"node:path";function Wc(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],o=e[n+1];if(i==="-"&&o==="-"){for(;n<r&&e[n]!==`
29
+ `;)n++;continue}if(i==="/"&&o==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],p=e.indexOf(l,n+l.length);n=p===-1?r:p+l.length,t+=" ";continue}}let a=(i==="E"||i==="e")&&o==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||a){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function X(e){let t=[],n="",r=!1,i=!1,o=s(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){o();continue}n+=l}o();let a=t.filter(c=>c.length>0);return a.length===0||a.length>2?null:a.length===2?{schema:a[0],name:a[1]}:{schema:"public",name:a[0]}}function fe(e){let t=[],n=0,r="";for(let i of e){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}function Cg(e){let t=/^ALTER\s+DEFAULT\s+PRIVILEGES\s+([\s\S]*?)(REVOKE|GRANT)\s+(?:GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+TABLES\s+(?:FROM|TO)\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT|WITH\s+GRANT\s+OPTION))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,o]=t;if(/REVOKE\s+GRANT\s+OPTION\s+FOR/i.test(e))return null;let a=/\bFOR\s+ROLE\s+([\s\S]+?)(?=\s+IN\s+SCHEMA\b|$)/i.exec(n);if(a&&!fe(a[1]).map(f=>X(f)?.name??"").filter(Boolean).includes("postgres"))return null;let c=/\bIN\s+SCHEMA\s+([\s\S]+?)(?=\s+FOR\s+ROLE\b|$)/i.exec(n);if(!c||!fe(c[1]).map(u=>X(u)?.name??"").filter(Boolean).includes("public"))return null;let p=fe(o).map(u=>u.replace(/^GROUP\s+/i,"").trim()).map(u=>X(u)?.name??"").filter(u=>u.length>0&&u!=="public");if(p.length===0)return null;let d=[];for(let u of fe(i)){let f=/^([A-Za-z]+)\s*(\()?/.exec(u.trim());if(!f)continue;let m=f[1].toUpperCase();if(m==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:p,writePrivs:[...Kt]};f[2]!=="("&&Kt.includes(m)&&d.push(m)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:p,writePrivs:d}}function Kc(e){let t=/^REVOKE\s+(GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+([\s\S]+?)\s+FROM\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,o]=t;if(n)return null;let a=i.trim();if(Ng.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!fe(l[1]).map(f=>X(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let u=a.replace(/^TABLE\s+/i,""),f=fe(u).map(m=>X(m)).filter(m=>m!==null).filter(m=>m.schema==="public").map(m=>m.name);if(f.length===0)return null;c=f}let p=fe(o).map(u=>u.replace(/^GROUP\s+/i,"").trim()).map(u=>X(u)?.name??"").filter(u=>u.length>0&&u!=="public"),d=[];for(let u of fe(r)){let f=/^([A-Za-z]+)\s*(\()?/.exec(u.trim());if(!f)continue;let m=f[1].toUpperCase(),h=f[2]==="(";if(m==="ALL")return{tables:c,roles:p,writePrivs:[...Kt]};!h&&Kt.includes(m)&&d.push(m)}return{tables:c,roles:p,writePrivs:d}}function Bi(e){let t=new Map,n=[...e].sort((i,o)=>ue(i.version,o.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let o=Wc(i.content);for(let a of o.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let u=Cg(c);if(!u)continue;let f=u.roles.includes("anon"),m=u.roles.includes("authenticated");if(u.action==="revoke"){if(f&&(r.anonAddressed=!0),m)for(let h of u.writePrivs)r.authWritesRevoked.add(h)}else if(f&&(r.anonAddressed=!1),m)for(let h of u.writePrivs)r.authWritesRevoked.delete(h);continue}let l=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(c);if(l){if(/\bTEMP(?:ORARY)?\b/i.test(l[1]??""))continue;let u=X(l[2]);if(!u||u.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(c)&&t.has(u.name))continue;t.set(u.name,{createdIn:i.version,anonAddressed:r.anonAddressed,authWritesRevoked:new Set(r.authWritesRevoked)});continue}let p=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(c);if(p){let u=p[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let f of fe(u)){let m=X(f);m&&m.schema==="public"&&t.delete(m.name)}continue}let d=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(d){let u=X(d[1]),f=X(d[2]);if(u&&f&&u.schema==="public"){let m=t.get(u.name);m&&(t.delete(u.name),t.set(f.name,m))}continue}if(/^REVOKE\b/i.test(c)){let u=Kc(c);if(!u)continue;let f=u.tables==="all_in_public"?[...t.keys()]:u.tables,m=u.roles.includes("anon"),h=u.roles.includes("authenticated");if(!m&&!h)continue;for(let g of f){let y=t.get(g);if(y&&(m&&(y.anonAddressed=!0),h))for(let b of u.writePrivs)y.authWritesRevoked.add(b)}continue}}}return t}function Ki(e){let t=[];for(let[n,r]of Bi(e)){let i=[];r.anonAddressed||i.push("anon"),Kt.every(o=>r.authWritesRevoked.has(o))||i.push("authenticated_writes"),i.length>0&&t.push({table:n,createdIn:r.createdIn,missing:i})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function Bc(e){let t=Ki(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Ki(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),a=i!=null&&r.missing.every(l=>i.has(l))?"info":"open",c=r.missing.map(l=>l==="anon"?"kein Tabellen-REVOKE nennt anon":"authenticated beh\xE4lt Schreibrechte (kumulierte REVOKEs decken INSERT/UPDATE/DELETE nicht)").join("; ");return{id:`table.acl:${e.dir}#${r.table}`,status:a,project:e.dir,table:r.table,createdIn:r.createdIn,missing:r.missing,title:`public.${r.table}: Default-Grants nie adressiert (${r.missing.join(", ")})`,detail:`\xDCber den gesamten Migrations-Bestand von ${e.dir}: ${c}. Supabase' ALTER DEFAULT PRIVILEGES grantet vollen CRUD an anon UND authenticated auf jede neue public-Tabelle; ohne Tabellen-REVOKE ist RLS die einzige Verteidigungslinie. Tabelle erzeugt in Migration ${r.createdIn}.`,hint:`REVOKE ALL ON public.${r.table} FROM PUBLIC, anon; REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.${r.table} FROM authenticated; \u2014 SELECT f\xFCr authenticated darf bewusst bleiben (RLS-gedecktes Lese-Muster). PUBLIC allein reicht NICHT (Default-Privileges sind direkte Rollen-Grants). Ein REVOKE in einer sp\xE4teren Migration z\xE4hlt ebenfalls; in DO-Bl\xF6cken z\xE4hlt es nicht (aufs Top-Level ziehen). Eine Tabelle, die NACH der Wurzelbehandlung entsteht (ALTER DEFAULT PRIVILEGES \u2026 IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated), kommt bereits geschlossen zur Welt und braucht kein eigenes REVOKE \u2014 diese Tabelle hier ist \xE4lter als die Wurzelbehandlung oder es gibt keine.`}})}function Vc(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function qi(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(Qn)||t.endsWith(Vi))}function Dg(e,t){try{let n=Ag(e,"utf8");return n.length>t?null:n}catch{return null}}function Og(e,t,n,r,i){let o=S(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(o===null)return i.push(`could not diff ${t} against ${r} ${Qn}`),null;let a=new Set,c=[];for(let d of o.split(`
30
+ `).filter(Boolean)){let[u,...f]=d.split(" ");u.startsWith("A")?a.add(f[0]):u.startsWith("R")?(c.push(f[0]),a.add(f[1])):(u.startsWith("M")||u.startsWith("D"))&&c.push(f[0])}let l=[],p=new Set(c);for(let{ref:d,content:u}of n)!a.has(d.path)&&!p.has(d.path)&&l.push({name:d.name,version:d.version,content:u});for(let d of c){let u=Ig.basename(d),f=et(u);if(f===null)continue;let m=S(e,["show",`${r}:${d}`]);if(m===null)return i.push(`could not read ${d} at ${r} ${Vi}`),null;l.push({name:u,version:f,content:m})}return l}function Pe(e,t={}){let n=t.maxFileBytes??Pg,r=[],i=Te(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let o=t.includeBaseline!==!1,a=null;if(o)if(t.baseRef)a=t.baseRef;else{let f=dc(e);a=f?`origin/${f}`:null,a===null&&r.push(`no default branch resolvable ${Qn}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let f of i){let m=[];for(let y of f.files){let b=Dg(Tg(e,y.path),n);if(b===null){r.push(`could not read ${y.path} \u2014 excluded from the fold`);continue}m.push({ref:y,content:b})}let h=m.map(({ref:y,content:b})=>({name:y.name,version:y.version,content:b})),g=a===null?null:Og(e,f.dir,m,a,r);c.push(...Bc({dir:f.dir,files:h,baseFiles:g})),l.push({dir:f.dir,migrationCount:h.length,tableCount:Bi(h).size})}let p=l.reduce((f,m)=>f+m.migrationCount,0),d=Vc(p,c.length),u={open:0,info:1};return c.sort((f,m)=>u[f.status]-u[m.status]||f.id.localeCompare(m.id)),{ok:d!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:d,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var Kt,Ng,Pg,Qn,Vi,Zn=_(()=>{"use strict";W();Lt();s(Wc,"stripSql");s(X,"normalizeQualifiedIdent");s(fe,"splitTopLevel");Kt=["INSERT","UPDATE","DELETE"];s(Cg,"parseDefaultAclTables");Ng=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(Kc,"parseTableRevoke");s(Bi,"foldTableAcl");s(Ki,"evaluateTableAcl");s(Bc,"computeTableAclFindings");s(Vc,"deriveTableAclVerdict");Pg=5e6,Qn="\u2014 findings reported ungraded (open)",Vi="\u2014 baseline degraded";s(qi,"isTableAclGraded");s(Dg,"safeRead");s(Og,"baseFilesFor");s(Pe,"checkTableAclLint")});import{readFileSync as Mg}from"node:fs";import{join as zi}from"node:path";function Yi(e){return e.verdict!=="no_opinion"&&e.graded}function Xi(e){let t=new Set;for(let n of e.matchAll(Fg))t.add(n[1]);return t}function Qi(e){return new Set([...e].map(t=>t.split("-")[0]))}function Qc(e){return e.split(`
31
31
  `).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
32
- `)}function Qi(e){let t=Xi(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let o=qc(i),a=new Set;for(let c of o.matchAll(Ng)){let l=c[2],u=l.split("-")[0];if(!t.has(u)||e.tokens.has(l))continue;let d=`${c[1]}-${l}`;a.has(d)||(a.add(d),n.push({file:r,klass:d,token:l,namespace:u}))}}return n}function Gc(e){return`${e.file} ${e.klass}`}function Pg(e,t){let n=t===null?null:new Set(t.map(Gc));return e.map(r=>({...r,status:n!==null&&n.has(Gc(r))?"info":"open"}))}function zc(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function Zi(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Kc(e,t){let n=S(e,["ls-files","--",...t]);return n===null?[]:n.split(`
33
- `).filter(Boolean)}function De(e,t={}){let n=t.maxFileBytes??Dg,r=new Set;for(let d of Kc(e,["*.css"])){let p=zi(qi(e,d),n);if(p!==null)for(let m of Yi(p))r.add(m)}if(r.size===0)return{ok:!1,verdict:"no_opinion",tokenCount:0,namespaceCount:0,findings:[],scannedFiles:0,graded:!1,baseRef:null};let i=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(d=>Wc.map(p=>`${d.replace(/\/+$/,"")}/**/${p}`)):Wc,o=[];for(let d of Kc(e,i)){if(!Zi(d))continue;let p=zi(qi(e,d),n);p!==null&&o.push({path:d,content:p})}let a=Qi({tokens:r,sources:o}),c=t.includeBaseline===!1?null:Og(e,i,n,t.baseRef),l=Pg(a,c?.findings??null),u=zc(r.size,l.length);return{ok:u!=="no_opinion"&&!l.some(d=>d.status==="open"),verdict:u,tokenCount:r.size,namespaceCount:Xi(r).size,findings:l,scannedFiles:o.length,graded:c!==null,baseRef:c?.mergeBase??null}}function Og(e,t,n,r){let i=r??Fg(e);if(i===null)return null;let o=S(e,["merge-base",i,"HEAD"])?.trim();if(!o)return null;let a=S(e,["diff","--name-only","--no-renames",o]);if(a===null)return null;let c=new Set(a.split(`
34
- `).filter(Boolean)),l=s(p=>c.has(p)?S(e,["show",`${o}:${p}`]):zi(qi(e,p),n),"atBase"),u=new Set;for(let p of Bc(e,o,["*.css"])){let m=l(p);if(m!==null)for(let f of Yi(m))u.add(f)}if(u.size===0)return{findings:[],mergeBase:o};let d=[];for(let p of Bc(e,o,t)){if(!Zi(p))continue;let m=l(p);m===null||m.length>n||d.push({path:p,content:m})}return{findings:Qi({tokens:u,sources:d}),mergeBase:o}}function Bc(e,t,n){let r=S(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
35
- `).filter(i=>i.length>0&&n.some(o=>Mg(i,o)))}function Mg(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let o=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?o.endsWith(r.slice(1)):o===r}function Fg(e){let t=S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>S(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function zi(e,t){try{let n=Ig(e,"utf8");return n.length>t?null:n}catch{return null}}var Vc,Cg,Ng,Wc,Dg,er=_(()=>{"use strict";W();s(Ji,"isThemeClassDriftGraded");Vc=["bg","text","border","border-x","border-y","border-t","border-r","border-b","border-l","divide","outline","ring","ring-offset","fill","stroke","accent","caret","decoration","placeholder","shadow","from","via","to"],Cg=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,Ng=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Vc.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(Yi,"extractTokens");s(Xi,"deriveNamespaces");s(qc,"stripCommentLines");s(Qi,"evaluateThemeClasses");s(Gc,"findingKey");s(Pg,"gradeAgainstBaseline");s(zc,"deriveThemeClassVerdict");Wc=["*.ts","*.tsx","*.js","*.jsx"],Dg=15e5;s(Zi,"isScannableSource");s(Kc,"listTracked");s(De,"checkThemeClassDrift");s(Og,"baselineFindings");s(Bc,"listTrackedAt");s(Mg,"matchesSourcePattern");s(Fg,"resolveBaseRef");s(zi,"safeRead")});function eo(e){return Di[e].version}function Vt(e,t,n,r){return{detector_id:e,detector_version:eo(e),state:t,finding_count:n,...r?{reason:r}:{}}}function K(e,t,n){return{summary:Vt(e,t,0,n),findings:[]}}function Zc(e){return e==="open"||e==="warn"||e==="info"}function $g(e){let t="det_number_collisions";if(!e.ok)return K(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return K(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return K(t,"not_applicable","no numbered namespaces");if(!Ti(n))return K(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let o of r){if(!Zc(o.status))continue;let{level:a,baseline:c}=rt(o.status);i.push({detector_id:t,rule_id:Oi,level:a,baseline:c,evidence:[...o.ownPath?[o.ownPath]:[],...o.sightings.map(l=>l.path)],title:o.title})}return{summary:Vt(t,"ran",i.length),findings:i}}function jg(e){let t="det_spec_drift";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return K(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return K(t,"not_applicable",n.reason??"no opinion");if(!Gi(n))return K(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!Zc(i.status))continue;let{level:o,baseline:a}=rt(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:Li(i.dimension),level:o,baseline:a,evidence:[i.id],title:i.title})}return{summary:Vt(t,"ran",r.length),findings:r}}function Hg(e){let t="det_theme_class_drift";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return K(t,"not_applicable","no theme tokens");if(!Ji(n))return K(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=rt(i.status);r.push({detector_id:t,rule_id:Mi,level:o,baseline:a,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:Vt(t,"ran",r.length),findings:r}}function Ug(e){let t="det_table_acl_lint";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return K(t,"not_applicable","no supabase migrations");if(!Vi(n))return K(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=rt(i.status);r.push({detector_id:t,rule_id:Fi,level:o,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:Vt(t,"ran",r.length),findings:r}}function to(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||nr[e.level]-nr[t.level]||Yc[e.baseline]-Yc[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Xc(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function Gg(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let o=Ut(i.evidence),a=`${i.detector_id}|${i.rule_id}|${i.level}|${o}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:i.detector_id,detector_version:eo(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:o,count:1})}else{let o=`${i.detector_id}|${i.rule_id}`,a=n.get(o);a?(a.evidence.push(...i.evidence),a.count+=1,nr[i.level]<nr[a.level]&&(a.level=i.level)):n.set(o,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:eo(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Ut(i.evidence),count:i.count});return r.sort(to)}function Wg(e,t){let n=e.filter(r=>r.state==="ran"||r.state==="not_applicable").length;return n===0?"none":n<e.length||t>0?"partial":"full"}function ot(e){let t={det_number_collisions:$g(e.number),det_spec_drift:jg(e.spec),det_theme_class_drift:Hg(e.theme),det_table_acl_lint:Ug(e.acl)},n=Jc.map(l=>t[l].summary),r=Jc.flatMap(l=>t[l].findings),i=Gg(r),o=[...i].sort((l,u)=>Xc(l)-Xc(u)||to(l,u)).slice(0,Qc).sort(to),a=i.length-o.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Ut(l.evidence),title:l.title}));return{findings:o,coverage:Wg(n,a),engines:n,local:c,truncated:a}}function Bt(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e}}}function el(e){return e instanceof Error?e.message:String(e)}async function tr(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:el(t)}}}async function no(e,t={}){let n={...Lg,...t.engines};try{if(S(e,["rev-parse","--is-inside-work-tree"])?.trim()!=="true")return ot(Bt("not a git work tree"));let i=t.baseRef,o={number:await tr(()=>n.number(e,{...i?{baseRef:i}:{},...t.includeWorktrees===void 0?{}:{includeWorktrees:t.includeWorktrees}})),spec:await tr(()=>n.spec(e,i?{baseRef:i}:{})),theme:await tr(()=>n.theme(e,i?{baseRef:i}:{})),acl:await tr(()=>n.acl(e,i?{baseRef:i}:{}))};return ot(o)}catch(r){return ot(Bt(`detector adapter failed: ${el(r)}`))}}var Qc,Lg,Jc,nr,Yc,ro=_(()=>{"use strict";W();$i();Ht();Wt();Zn();er();Qc=64,Lg={number:s((e,t)=>Ie(e,t),"number"),spec:s((e,t)=>Ne(e,t),"spec"),theme:s((e,t)=>De(e,t),"theme"),acl:s((e,t)=>Pe(e,t),"acl")},Jc=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint"];s(eo,"versionOf");s(Vt,"summary");s(K,"noFindings");s(Zc,"isFindingStatus");s($g,"adaptNumber");s(jg,"adaptSpec");s(Hg,"adaptTheme");s(Ug,"adaptAcl");nr={open:0,warn:1,info:2},Yc={introduced:0,pre_existing:1};s(to,"compareWire");s(Xc,"capPriority");s(Gg,"buildWire");s(Wg,"deriveCoverage");s(ot,"adaptDetectorReports");s(Bt,"unavailableDetectorReports");s(el,"errorText");s(tr,"attempt");s(no,"runRepoHealthDetectors")});var tl,io=_(()=>{"use strict";tl=[{flag:"sql_migration_added",path:/(^|\/)migrations\/[^/]+\.sql$/i,onlyWhenAdded:!0},{flag:"security_definer_touched",path:/\.sql$/i,content:/\bSECURITY\s+DEFINER\b/i},{flag:"rls_policy_changed",path:/\.sql$/i,content:/\b(CREATE|ALTER|DROP)\s+POLICY\b|\bROW\s+LEVEL\s+SECURITY\b/i},{flag:"auth_config_changed",path:/(^|\/)supabase\/config\.toml$|(^|\/)(middleware|proxy)\.(ts|js)$/},{flag:"package_manifest_changed",path:/(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|requirements\.txt|pyproject\.toml|Cargo\.toml|go\.mod)$/},{flag:"ci_workflow_changed",path:/^\.github\/workflows\/[^/]+\.ya?ml$|^\.gitlab-ci\.yml$/},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function nl(e){let t=new Set;for(let[n,r]of e.paths)for(let i of tl){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let o=Kg(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function Kg(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
36
- `):t.readUntracked(e)}var rl=_(()=>{"use strict";io();s(nl,"scanRiskFlags");s(Kg,"contentForPath")});var st,il,at,ct,oo,rr,ir,or,so,ol,qt=_(()=>{"use strict";st="1",il=`
32
+ `)}function Zi(e){let t=Qi(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let o=Qc(i),a=new Set;for(let c of o.matchAll(Lg)){let l=c[2],p=l.split("-")[0];if(!t.has(p)||e.tokens.has(l))continue;let d=`${c[1]}-${l}`;a.has(d)||(a.add(d),n.push({file:r,klass:d,token:l,namespace:p}))}}return n}function qc(e){return`${e.file} ${e.klass}`}function $g(e,t){let n=t===null?null:new Set(t.map(qc));return e.map(r=>({...r,status:n!==null&&n.has(qc(r))?"info":"open"}))}function Zc(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function eo(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Jc(e,t){let n=S(e,["ls-files","--",...t]);return n===null?[]:n.split(`
33
+ `).filter(Boolean)}function De(e,t={}){let n=t.maxFileBytes??jg,r=new Set;for(let d of Jc(e,["*.css"])){let u=Ji(zi(e,d),n);if(u!==null)for(let f of Xi(u))r.add(f)}if(r.size===0)return{ok:!1,verdict:"no_opinion",tokenCount:0,namespaceCount:0,findings:[],scannedFiles:0,graded:!1,baseRef:null};let i=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(d=>zc.map(u=>`${d.replace(/\/+$/,"")}/**/${u}`)):zc,o=[];for(let d of Jc(e,i)){if(!eo(d))continue;let u=Ji(zi(e,d),n);u!==null&&o.push({path:d,content:u})}let a=Zi({tokens:r,sources:o}),c=t.includeBaseline===!1?null:Hg(e,i,n,t.baseRef),l=$g(a,c?.findings??null),p=Zc(r.size,l.length);return{ok:p!=="no_opinion"&&!l.some(d=>d.status==="open"),verdict:p,tokenCount:r.size,namespaceCount:Qi(r).size,findings:l,scannedFiles:o.length,graded:c!==null,baseRef:c?.mergeBase??null}}function Hg(e,t,n,r){let i=r??Gg(e);if(i===null)return null;let o=S(e,["merge-base",i,"HEAD"])?.trim();if(!o)return null;let a=S(e,["diff","--name-only","--no-renames",o]);if(a===null)return null;let c=new Set(a.split(`
34
+ `).filter(Boolean)),l=s(u=>c.has(u)?S(e,["show",`${o}:${u}`]):Ji(zi(e,u),n),"atBase"),p=new Set;for(let u of Yc(e,o,["*.css"])){let f=l(u);if(f!==null)for(let m of Xi(f))p.add(m)}if(p.size===0)return{findings:[],mergeBase:o};let d=[];for(let u of Yc(e,o,t)){if(!eo(u))continue;let f=l(u);f===null||f.length>n||d.push({path:u,content:f})}return{findings:Zi({tokens:p,sources:d}),mergeBase:o}}function Yc(e,t,n){let r=S(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
35
+ `).filter(i=>i.length>0&&n.some(o=>Ug(i,o)))}function Ug(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let o=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?o.endsWith(r.slice(1)):o===r}function Gg(e){let t=S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>S(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function Ji(e,t){try{let n=Mg(e,"utf8");return n.length>t?null:n}catch{return null}}var Xc,Fg,Lg,zc,jg,er=_(()=>{"use strict";W();s(Yi,"isThemeClassDriftGraded");Xc=["bg","text","border","border-x","border-y","border-t","border-r","border-b","border-l","divide","outline","ring","ring-offset","fill","stroke","accent","caret","decoration","placeholder","shadow","from","via","to"],Fg=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,Lg=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Xc.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(Xi,"extractTokens");s(Qi,"deriveNamespaces");s(Qc,"stripCommentLines");s(Zi,"evaluateThemeClasses");s(qc,"findingKey");s($g,"gradeAgainstBaseline");s(Zc,"deriveThemeClassVerdict");zc=["*.ts","*.tsx","*.js","*.jsx"],jg=15e5;s(eo,"isScannableSource");s(Jc,"listTracked");s(De,"checkThemeClassDrift");s(Hg,"baselineFindings");s(Yc,"listTrackedAt");s(Ug,"matchesSourcePattern");s(Gg,"resolveBaseRef");s(Ji,"safeRead")});function to(e){return Oi[e].version}function Vt(e,t,n,r){return{detector_id:e,detector_version:to(e),state:t,finding_count:n,...r?{reason:r}:{}}}function K(e,t,n){return{summary:Vt(e,t,0,n),findings:[]}}function il(e){return e==="open"||e==="warn"||e==="info"}function Kg(e){let t="det_number_collisions";if(!e.ok)return K(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return K(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return K(t,"not_applicable","no numbered namespaces");if(!Ii(n))return K(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let o of r){if(!il(o.status))continue;let{level:a,baseline:c}=rt(o.status);i.push({detector_id:t,rule_id:Mi,level:a,baseline:c,evidence:[...o.ownPath?[o.ownPath]:[],...o.sightings.map(l=>l.path)],title:o.title})}return{summary:Vt(t,"ran",i.length),findings:i}}function Bg(e){let t="det_spec_drift";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return K(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return K(t,"not_applicable",n.reason??"no opinion");if(!Wi(n))return K(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!il(i.status))continue;let{level:o,baseline:a}=rt(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:$i(i.dimension),level:o,baseline:a,evidence:[i.id],title:i.title})}return{summary:Vt(t,"ran",r.length),findings:r}}function Vg(e){let t="det_theme_class_drift";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return K(t,"not_applicable","no theme tokens");if(!Yi(n))return K(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=rt(i.status);r.push({detector_id:t,rule_id:Fi,level:o,baseline:a,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:Vt(t,"ran",r.length),findings:r}}function qg(e){let t="det_table_acl_lint";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return K(t,"not_applicable","no supabase migrations");if(!qi(n))return K(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=rt(i.status);r.push({detector_id:t,rule_id:Li,level:o,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:Vt(t,"ran",r.length),findings:r}}function no(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||nr[e.level]-nr[t.level]||tl[e.baseline]-tl[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function nl(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function zg(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let o=Ut(i.evidence),a=`${i.detector_id}|${i.rule_id}|${i.level}|${o}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:i.detector_id,detector_version:to(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:o,count:1})}else{let o=`${i.detector_id}|${i.rule_id}`,a=n.get(o);a?(a.evidence.push(...i.evidence),a.count+=1,nr[i.level]<nr[a.level]&&(a.level=i.level)):n.set(o,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:to(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Ut(i.evidence),count:i.count});return r.sort(no)}function Jg(e,t){let n=e.filter(r=>r.state==="ran"||r.state==="not_applicable").length;return n===0?"none":n<e.length||t>0?"partial":"full"}function ot(e){let t={det_number_collisions:Kg(e.number),det_spec_drift:Bg(e.spec),det_theme_class_drift:Vg(e.theme),det_table_acl_lint:qg(e.acl)},n=el.map(l=>t[l].summary),r=el.flatMap(l=>t[l].findings),i=zg(r),o=[...i].sort((l,p)=>nl(l)-nl(p)||no(l,p)).slice(0,rl).sort(no),a=i.length-o.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Ut(l.evidence),title:l.title}));return{findings:o,coverage:Jg(n,a),engines:n,local:c,truncated:a}}function Bt(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e}}}function ol(e){return e instanceof Error?e.message:String(e)}async function tr(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:ol(t)}}}async function ro(e,t={}){let n={...Wg,...t.engines};try{if(S(e,["rev-parse","--is-inside-work-tree"])?.trim()!=="true")return ot(Bt("not a git work tree"));let i=t.baseRef,o={number:await tr(()=>n.number(e,{...i?{baseRef:i}:{},...t.includeWorktrees===void 0?{}:{includeWorktrees:t.includeWorktrees}})),spec:await tr(()=>n.spec(e,i?{baseRef:i}:{})),theme:await tr(()=>n.theme(e,i?{baseRef:i}:{})),acl:await tr(()=>n.acl(e,i?{baseRef:i}:{}))};return ot(o)}catch(r){return ot(Bt(`detector adapter failed: ${ol(r)}`))}}var rl,Wg,el,nr,tl,io=_(()=>{"use strict";W();ji();Ht();Wt();Zn();er();rl=64,Wg={number:s((e,t)=>Ie(e,t),"number"),spec:s((e,t)=>Ne(e,t),"spec"),theme:s((e,t)=>De(e,t),"theme"),acl:s((e,t)=>Pe(e,t),"acl")},el=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint"];s(to,"versionOf");s(Vt,"summary");s(K,"noFindings");s(il,"isFindingStatus");s(Kg,"adaptNumber");s(Bg,"adaptSpec");s(Vg,"adaptTheme");s(qg,"adaptAcl");nr={open:0,warn:1,info:2},tl={introduced:0,pre_existing:1};s(no,"compareWire");s(nl,"capPriority");s(zg,"buildWire");s(Jg,"deriveCoverage");s(ot,"adaptDetectorReports");s(Bt,"unavailableDetectorReports");s(ol,"errorText");s(tr,"attempt");s(ro,"runRepoHealthDetectors")});var sl,oo=_(()=>{"use strict";sl=[{flag:"sql_migration_added",path:/(^|\/)migrations\/[^/]+\.sql$/i,onlyWhenAdded:!0},{flag:"security_definer_touched",path:/\.sql$/i,content:/\bSECURITY\s+DEFINER\b/i},{flag:"rls_policy_changed",path:/\.sql$/i,content:/\b(CREATE|ALTER|DROP)\s+POLICY\b|\bROW\s+LEVEL\s+SECURITY\b/i},{flag:"auth_config_changed",path:/(^|\/)supabase\/config\.toml$|(^|\/)(middleware|proxy)\.(ts|js)$/},{flag:"package_manifest_changed",path:/(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|requirements\.txt|pyproject\.toml|Cargo\.toml|go\.mod)$/},{flag:"ci_workflow_changed",path:/^\.github\/workflows\/[^/]+\.ya?ml$|^\.gitlab-ci\.yml$/},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function al(e){let t=new Set;for(let[n,r]of e.paths)for(let i of sl){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let o=Yg(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function Yg(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
36
+ `):t.readUntracked(e)}var cl=_(()=>{"use strict";oo();s(al,"scanRiskFlags");s(Yg,"contentForPath")});var st,ll,at,ct,so,rr,ir,or,ao,dl,qt=_(()=>{"use strict";st="1",ll=`
37
37
  CREATE TABLE IF NOT EXISTS meta (
38
38
  key TEXT PRIMARY KEY,
39
39
  value TEXT NOT NULL
@@ -92,20 +92,20 @@ CREATE TABLE IF NOT EXISTS embeddings (
92
92
  vec BLOB NOT NULL,
93
93
  content_hash TEXT NOT NULL
94
94
  );
95
- `,at="schema_version",ct="last_index_commit",oo="last_indexed_at",rr="embed_recipe_version",ir="embed_model",or="embed_dim",so="last_synced_at",ol="last_synced_commit"});function ao(e){return e.replace(/[_\-./]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(t=>t.length>0)}function sl(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of ao(e.name))t.add(i);for(let i of ao(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function al(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let i of ao(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var co=_(()=>{"use strict";s(ao,"splitIdentifier");s(sl,"buildSearchText");s(al,"toFtsMatchQuery")});import{readFileSync as cl}from"node:fs";import{posix as ll}from"node:path";function dl(e){return{nodeKey:e.nodeKey,kind:e.kind,name:e.name,qualifiedName:e.qualifiedName,filePath:e.filePath,language:e.language,startLine:e.startLine,endLine:e.endLine}}function Oe(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function ul(e){return e==="added"?0:e==="modified"?1:2}function Bg(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(i+=l-c+1)}let o=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||o?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var zt,lo=_(()=>{"use strict";Da();ui();Ma();$a();W();Xa();hi();xi();Ht();ro();Wt();rl();qt();co();zt=class{static{s(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(at),i=await this.store.countFiles()>0;(t.full||i&&r!==st)&&await this.wipe();let o=Ka(this.repoRoot),a=new Set(o.map(h=>h.path)),c=await this.store.getAllFiles(),l=new Map(c.map(h=>[h.path,h])),u=c.length>0&&!t.full,d={filesScanned:o.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u};for(let h of c)a.has(h.path)||(await this.store.deleteFile(h.path),d.filesDeleted++);let p=[],m=0;for(let h of o){m++;let g=qa(this.repoRoot,h.path);if(!g){d.filesSkipped++;continue}let y=l.get(h.path);if(y&&y.mtimeMs===g.mtimeMs&&y.size===g.size){d.filesSkipped++;continue}let b=this.readRepoFile(h.path);if(b===null){d.filesSkipped++;continue}let w=Un(b);if(y&&y.contentHash===w){await this.store.upsertFile({...y,mtimeMs:g.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let v=await this.parser.parse(h.path,b,h.language),k=new Map;for(let R of v.nodes)k.set(R.nodeKey,sl(R));let E={path:h.path,language:h.language,contentHash:w,mtimeMs:g.mtimeMs,size:g.size,indexedAt:n};await this.store.replaceFileNodes(E,v.nodes,k),p.push(v),d.filesParsed++,t.onProgress?.({path:h.path,done:m,total:o.length})}if(p.length>0){let h=await this.store.getNameIndex(),g=Fa(h);for(let y of p){let b=La(y,g);await this.store.replaceOutgoingEdges(b.srcKeys,b.edges)}}if(this.embedder&&t.embed){let h=await this.store.getNodesByKinds([...di]),g=await this.store.getEmbeddingContentHashes(),y=[];for(let w of h){let v=Pa(w),k=Un(`${this.embedder.recipeVersion}\0${v}`);g.get(w.nodeKey)!==k&&y.push({nodeKey:w.nodeKey,text:v,hash:k})}let b=64;for(let w=0;w<y.length;w+=b){let v=y.slice(w,w+b),k=await this.embedder.embedDocuments(v.map(R=>R.text));await this.store.upsertEmbeddings(v.map((R,I)=>({nodeKey:R.nodeKey,dim:this.embedder.dim,vec:k[I],contentHash:R.hash})));let E=Math.min(w+b,y.length);t.onProgress?.({path:"embedding symbols",done:E,total:y.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(rr,this.embedder.recipeVersion),await this.store.setMeta(ir,this.embedder.model),await this.store.setMeta(or,String(this.embedder.dim))}await this.store.setMeta(at,st),await this.store.setMeta(oo,String(n));let f=Ft(this.repoRoot);return f&&await this.store.setMeta(ct,f),d.nodeCount=await this.store.countNodes(),d.edgeCount=await this.store.countEdges(),d.durationMs=(t.now??Date.now())-n,d}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let o of n)r[o.language]=o.count;let i=await this.store.getMeta(oo);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(ct),schemaVersion:await this.store.getMeta(at),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Oe(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),o=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&o.push({...dl(c),score:a.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Oe(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:Oa(i,l.vec)})).sort((l,u)=>u.score-l.score).slice(0,r),c=[];for(let l of a){let u=await this.store.getNode(l.nodeKey);u&&c.push({...dl(u),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Oe(n.maxDepth,3,5),o=Oe(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,u=new Set([t]),d=[t];for(let p=0;p<i&&d.length>0;p++){let m=[];for(let f of d){let h=await this.store.neighbors(f,r,a,o);for(let g of h){let y=`${g.srcKey} ${g.dstKey} ${g.kind}`;if(l.has(y))continue;if(l.add(y),c.push({srcKey:g.srcKey,dstKey:g.dstKey,kind:g.kind}),c.length>=o)return c;let b=r==="out"?g.dstKey:g.srcKey;u.has(b)||(u.add(b),m.push(b))}}d=m}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=cl(ll.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let a of n)i[a.kind]=a.count;let o={};for(let a of r)o[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:o,topModules:await this.store.topModulesByFanIn(Oe(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Va(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Oe(t.limit,64,200),i=[],o=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&o++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:o,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Hn(this.repoRoot,{since:t.since});if(r===null)throw new Error("fileHistory requires a git repository (history is git-based)");n=[...r.keys()]}else if(Ft(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return nc(this.repoRoot,n,t)}async checkDivergence(t={}){return $t(this.repoRoot,t)}async checkNumberCollisions(t={}){return Ie(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Ce(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Ne(this.repoRoot,t)}async reviewDetectors(t={}){return no(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Hn(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Ya(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=nl({paths:n,hunks:i,readUntracked:s(m=>this.readRepoFileHead(m,Ja),"readUntracked")}),c=Wa(n.keys()),l=Oe(t.limit,64,200),u=[],d=0,p=0;for(let m of c){let f=await this.store.getNodesByFile(m.path);if(f.length===0)continue;d++;let h=await this.store.getFile(m.path),g=this.readRepoFile(m.path),y=h!==null&&g!==null&&Un(g)!==h.contentHash;y&&(p++,o==="full"&&(o="partial"));let b=n.get(m.path)??"modified",w=i.get(m.path);for(let v of f)u.push(Bg(v,b,w,y))}return u.sort((m,f)=>ul(m.change)-ul(f.change)||m.filePath.localeCompare(f.filePath)||m.startLine-f.startLine),{changedFiles:c.length,indexedFiles:d,staleFiles:p,symbols:u.slice(0,l),truncated:u.length>l,riskFlags:a,hunkCoverage:o,baseKind:t.since?"ref":"uncommitted",headSha:Ft(this.repoRoot),dirty:za(this.repoRoot),baseSha:t.since?Gn(this.repoRoot,t.since):null}}async close(){await this.store.close()}readRepoFileHead(t,n){let r=this.readRepoFile(t);return r===null?null:r.slice(0,n)}readRepoFile(t){try{return cl(ll.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};s(dl,"toHit");s(Oe,"clampLimit");s(ul,"changeRank");s(Bg,"classifyReviewSymbol")});import{createRequire as Vg}from"node:module";function fl(){return pl("node:sqlite")}function lt(){if(Jt)return Jt;try{let{DatabaseSync:e}=fl(),t=new e(":memory:");try{t.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),t.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),t.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),Jt={ok:!0}}finally{t.close()}}catch(e){Jt={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Jt}function qg(e){let{DatabaseSync:t}=fl(),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>n.exec(r),"exec"),close:s(()=>n.close(),"close"),transaction:s(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function zg(e){let t=pl("better-sqlite3"),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>{n.exec(r)},"exec"),close:s(()=>{n.close()},"close"),transaction:s(r=>n.transaction(r),"transaction")}}function Jg(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function sr(e){let t=Jg(),n=s(i=>{let o=i==="node:sqlite"?qg(e):zg(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=lt();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=lt();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${o})`)}}var pl,Jt,uo=_(()=>{"use strict";pl=Vg(import.meta.url);s(fl,"loadBuiltin");Jt=null;s(lt,"probeBuiltinSqlite");s(qg,"openBuiltin");s(zg,"openBetter");s(Jg,"backendOverride");s(sr,"openSqliteDatabase")});function ar(e){return{nodeKey:e.node_key,kind:e.kind,name:e.name,qualifiedName:e.qualified_name,filePath:e.file_path,language:e.language,startLine:e.start_line,endLine:e.end_line,startByte:e.start_byte,endByte:e.end_byte,signature:e.signature,doc:e.doc}}var ml,Yt,hl=_(()=>{"use strict";uo();qt();co();s(ar,"toNodeRow");ml=400,Yt=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=sr(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(il)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r){this.db.transaction(()=>{this.deleteFileGraph(t.path);let o=this.insertNodeStmt(),a=this.insertFtsStmt();for(let c of n)o.run(c.nodeKey,c.kind,c.name,c.qualifiedName,c.filePath,c.language,c.startLine,c.endLine,c.startByte,c.endByte,c.signature,c.doc),a.run(c.nodeKey,r.get(c.nodeKey)??c.name);this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)i.run(a);let o=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)o.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?ar(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(ar)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(ar)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(ar)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let o=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,o,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=al(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
95
+ `,at="schema_version",ct="last_index_commit",so="last_indexed_at",rr="embed_recipe_version",ir="embed_model",or="embed_dim",ao="last_synced_at",dl="last_synced_commit"});function co(e){return e.replace(/[_\-./]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(t=>t.length>0)}function ul(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of co(e.name))t.add(i);for(let i of co(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function pl(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let i of co(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var lo=_(()=>{"use strict";s(co,"splitIdentifier");s(ul,"buildSearchText");s(pl,"toFtsMatchQuery")});import{readFileSync as fl}from"node:fs";import{posix as ml}from"node:path";function hl(e){return{nodeKey:e.nodeKey,kind:e.kind,name:e.name,qualifiedName:e.qualifiedName,filePath:e.filePath,language:e.language,startLine:e.startLine,endLine:e.endLine}}function Oe(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function gl(e){return e==="added"?0:e==="modified"?1:2}function Xg(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(i+=l-c+1)}let o=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||o?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var zt,uo=_(()=>{"use strict";$a();pi();Ha();Wa();W();nc();gi();Ri();Ht();io();Wt();cl();qt();lo();zt=class{static{s(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(at),i=await this.store.countFiles()>0;(t.full||i&&r!==st)&&await this.wipe();let o=Ja(this.repoRoot),a=new Set(o.map(h=>h.path)),c=await this.store.getAllFiles(),l=new Map(c.map(h=>[h.path,h])),p=c.length>0&&!t.full,d={filesScanned:o.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:p};for(let h of c)a.has(h.path)||(await this.store.deleteFile(h.path),d.filesDeleted++);let u=[],f=0;for(let h of o){f++;let g=Qa(this.repoRoot,h.path);if(!g){d.filesSkipped++;continue}let y=l.get(h.path);if(y&&y.mtimeMs===g.mtimeMs&&y.size===g.size){d.filesSkipped++;continue}let b=this.readRepoFile(h.path);if(b===null){d.filesSkipped++;continue}let w=Un(b);if(y&&y.contentHash===w){await this.store.upsertFile({...y,mtimeMs:g.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let v=await this.parser.parse(h.path,b,h.language),k=new Map;for(let R of v.nodes)k.set(R.nodeKey,ul(R));let E={path:h.path,language:h.language,contentHash:w,mtimeMs:g.mtimeMs,size:g.size,indexedAt:n};await this.store.replaceFileNodes(E,v.nodes,k),u.push(v),d.filesParsed++,t.onProgress?.({path:h.path,done:f,total:o.length})}if(u.length>0){let h=await this.store.getNameIndex(),g=Ua(h);for(let y of u){let b=Ga(y,g);await this.store.replaceOutgoingEdges(b.srcKeys,b.edges)}}if(this.embedder&&t.embed){let h=await this.store.getNodesByKinds([...ui]),g=await this.store.getEmbeddingContentHashes(),y=[];for(let w of h){let v=La(w),k=Un(`${this.embedder.recipeVersion}\0${v}`);g.get(w.nodeKey)!==k&&y.push({nodeKey:w.nodeKey,text:v,hash:k})}let b=64;for(let w=0;w<y.length;w+=b){let v=y.slice(w,w+b),k=await this.embedder.embedDocuments(v.map(R=>R.text));await this.store.upsertEmbeddings(v.map((R,I)=>({nodeKey:R.nodeKey,dim:this.embedder.dim,vec:k[I],contentHash:R.hash})));let E=Math.min(w+b,y.length);t.onProgress?.({path:"embedding symbols",done:E,total:y.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(rr,this.embedder.recipeVersion),await this.store.setMeta(ir,this.embedder.model),await this.store.setMeta(or,String(this.embedder.dim))}await this.store.setMeta(at,st),await this.store.setMeta(so,String(n));let m=Ft(this.repoRoot);return m&&await this.store.setMeta(ct,m),d.nodeCount=await this.store.countNodes(),d.edgeCount=await this.store.countEdges(),d.durationMs=(t.now??Date.now())-n,d}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let o of n)r[o.language]=o.count;let i=await this.store.getMeta(so);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(ct),schemaVersion:await this.store.getMeta(at),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Oe(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),o=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&o.push({...hl(c),score:a.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Oe(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:ja(i,l.vec)})).sort((l,p)=>p.score-l.score).slice(0,r),c=[];for(let l of a){let p=await this.store.getNode(l.nodeKey);p&&c.push({...hl(p),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Oe(n.maxDepth,3,5),o=Oe(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,p=new Set([t]),d=[t];for(let u=0;u<i&&d.length>0;u++){let f=[];for(let m of d){let h=await this.store.neighbors(m,r,a,o);for(let g of h){let y=`${g.srcKey} ${g.dstKey} ${g.kind}`;if(l.has(y))continue;if(l.add(y),c.push({srcKey:g.srcKey,dstKey:g.dstKey,kind:g.kind}),c.length>=o)return c;let b=r==="out"?g.dstKey:g.srcKey;p.has(b)||(p.add(b),f.push(b))}}d=f}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=fl(ml.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let a of n)i[a.kind]=a.count;let o={};for(let a of r)o[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:o,topModules:await this.store.topModulesByFanIn(Oe(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Xa(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Oe(t.limit,64,200),i=[],o=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&o++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:o,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Hn(this.repoRoot,{since:t.since});if(r===null)throw new Error("fileHistory requires a git repository (history is git-based)");n=[...r.keys()]}else if(Ft(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return ac(this.repoRoot,n,t)}async checkDivergence(t={}){return $t(this.repoRoot,t)}async checkNumberCollisions(t={}){return Ie(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Ce(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Ne(this.repoRoot,t)}async reviewDetectors(t={}){return ro(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Hn(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=tc(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=al({paths:n,hunks:i,readUntracked:s(f=>this.readRepoFileHead(f,ec),"readUntracked")}),c=za(n.keys()),l=Oe(t.limit,64,200),p=[],d=0,u=0;for(let f of c){let m=await this.store.getNodesByFile(f.path);if(m.length===0)continue;d++;let h=await this.store.getFile(f.path),g=this.readRepoFile(f.path),y=h!==null&&g!==null&&Un(g)!==h.contentHash;y&&(u++,o==="full"&&(o="partial"));let b=n.get(f.path)??"modified",w=i.get(f.path);for(let v of m)p.push(Xg(v,b,w,y))}return p.sort((f,m)=>gl(f.change)-gl(m.change)||f.filePath.localeCompare(m.filePath)||f.startLine-m.startLine),{changedFiles:c.length,indexedFiles:d,staleFiles:u,symbols:p.slice(0,l),truncated:p.length>l,riskFlags:a,hunkCoverage:o,baseKind:t.since?"ref":"uncommitted",headSha:Ft(this.repoRoot),dirty:Za(this.repoRoot),baseSha:t.since?Gn(this.repoRoot,t.since):null}}async close(){await this.store.close()}readRepoFileHead(t,n){let r=this.readRepoFile(t);return r===null?null:r.slice(0,n)}readRepoFile(t){try{return fl(ml.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};s(hl,"toHit");s(Oe,"clampLimit");s(gl,"changeRank");s(Xg,"classifyReviewSymbol")});import{createRequire as Qg}from"node:module";function bl(){return yl("node:sqlite")}function lt(){if(Jt)return Jt;try{let{DatabaseSync:e}=bl(),t=new e(":memory:");try{t.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),t.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),t.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),Jt={ok:!0}}finally{t.close()}}catch(e){Jt={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Jt}function Zg(e){let{DatabaseSync:t}=bl(),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>n.exec(r),"exec"),close:s(()=>n.close(),"close"),transaction:s(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function ey(e){let t=yl("better-sqlite3"),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>{n.exec(r)},"exec"),close:s(()=>{n.close()},"close"),transaction:s(r=>n.transaction(r),"transaction")}}function ty(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function sr(e){let t=ty(),n=s(i=>{let o=i==="node:sqlite"?Zg(e):ey(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=lt();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=lt();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${o})`)}}var yl,Jt,po=_(()=>{"use strict";yl=Qg(import.meta.url);s(bl,"loadBuiltin");Jt=null;s(lt,"probeBuiltinSqlite");s(Zg,"openBuiltin");s(ey,"openBetter");s(ty,"backendOverride");s(sr,"openSqliteDatabase")});function ar(e){return{nodeKey:e.node_key,kind:e.kind,name:e.name,qualifiedName:e.qualified_name,filePath:e.file_path,language:e.language,startLine:e.start_line,endLine:e.end_line,startByte:e.start_byte,endByte:e.end_byte,signature:e.signature,doc:e.doc}}var _l,Yt,wl=_(()=>{"use strict";po();qt();lo();s(ar,"toNodeRow");_l=400,Yt=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=sr(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(ll)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r){this.db.transaction(()=>{this.deleteFileGraph(t.path);let o=this.insertNodeStmt(),a=this.insertFtsStmt();for(let c of n)o.run(c.nodeKey,c.kind,c.name,c.qualifiedName,c.filePath,c.language,c.startLine,c.endLine,c.startByte,c.endByte,c.signature,c.doc),a.run(c.nodeKey,r.get(c.nodeKey)??c.name);this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)i.run(a);let o=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)o.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?ar(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(ar)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(ar)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(ar)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let o=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,o,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=pl(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
96
96
  FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
97
97
  WHERE nodes_fts MATCH ? AND n.kind = ?
98
98
  ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
99
99
  FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
100
100
  WHERE nodes_fts MATCH ?
101
- ORDER BY score LIMIT ?`,a=this.db.prepare(o);return(n?a.all(i,n,r):a.all(i,r)).map(l=>({nodeKey:l.node_key,score:-l.score}))}async neighbors(t,n,r,i){let a=`SELECT src_key, dst_key, kind FROM edges WHERE ${n==="out"?"src_key":"dst_key"} = ?`,c=[t];return r&&r.length>0&&(a+=` AND kind IN (${r.map(()=>"?").join(",")})`,c.push(...r)),a+=" LIMIT ?",c.push(i),this.db.prepare(a).all(...c).map(u=>({srcKey:u.src_key,dstKey:u.dst_key,kind:u.kind}))}async countFiles(){return this.db.prepare("SELECT COUNT(*) AS c FROM files").get().c}async countNodes(){return this.db.prepare("SELECT COUNT(*) AS c FROM nodes").get().c}async countEdges(){return this.db.prepare("SELECT COUNT(*) AS c FROM edges").get().c}async kindDistribution(){return this.db.prepare("SELECT kind, COUNT(*) AS c FROM nodes GROUP BY kind ORDER BY c DESC").all().map(n=>({kind:n.kind,count:n.c}))}async languageDistribution(){return this.db.prepare("SELECT language, COUNT(*) AS c FROM files GROUP BY language ORDER BY c DESC").all().map(n=>({language:n.language,count:n.c}))}async topModulesByFanIn(t){return this.db.prepare(`SELECT n.file_path AS file_path, n.language AS language,
101
+ ORDER BY score LIMIT ?`,a=this.db.prepare(o);return(n?a.all(i,n,r):a.all(i,r)).map(l=>({nodeKey:l.node_key,score:-l.score}))}async neighbors(t,n,r,i){let a=`SELECT src_key, dst_key, kind FROM edges WHERE ${n==="out"?"src_key":"dst_key"} = ?`,c=[t];return r&&r.length>0&&(a+=` AND kind IN (${r.map(()=>"?").join(",")})`,c.push(...r)),a+=" LIMIT ?",c.push(i),this.db.prepare(a).all(...c).map(p=>({srcKey:p.src_key,dstKey:p.dst_key,kind:p.kind}))}async countFiles(){return this.db.prepare("SELECT COUNT(*) AS c FROM files").get().c}async countNodes(){return this.db.prepare("SELECT COUNT(*) AS c FROM nodes").get().c}async countEdges(){return this.db.prepare("SELECT COUNT(*) AS c FROM edges").get().c}async kindDistribution(){return this.db.prepare("SELECT kind, COUNT(*) AS c FROM nodes GROUP BY kind ORDER BY c DESC").all().map(n=>({kind:n.kind,count:n.c}))}async languageDistribution(){return this.db.prepare("SELECT language, COUNT(*) AS c FROM files GROUP BY language ORDER BY c DESC").all().map(n=>({language:n.language,count:n.c}))}async topModulesByFanIn(t){return this.db.prepare(`SELECT n.file_path AS file_path, n.language AS language,
102
102
  (SELECT COUNT(*) FROM nodes n2 WHERE n2.file_path = n.file_path) AS symbol_count,
103
103
  (SELECT COUNT(*) FROM edges e WHERE e.src_key = n.node_key AND e.kind = 'imports') AS imports_out,
104
104
  (SELECT COUNT(*) FROM edges e WHERE e.dst_key = n.node_key AND e.kind = 'imports') AS imports_in
105
105
  FROM nodes n
106
106
  WHERE n.kind = 'module'
107
107
  ORDER BY imports_in DESC, symbol_count DESC
108
- LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(o=>o.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let o=0;o<n.length;o+=ml)for(let a of n.slice(o,o+ml))r.run(a),i.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
108
+ LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(o=>o.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let o=0;o<n.length;o+=_l)for(let a of n.slice(o,o+_l))r.run(a),i.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
109
109
  node_key, kind, name, qualified_name, file_path, language,
110
110
  start_line, end_line, start_byte, end_byte, signature, doc
111
111
  ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)),this._insNode}_insFts=null;insertFtsStmt(){return this._insFts||(this._insFts=this.db.prepare("INSERT INTO nodes_fts(node_key, search_text) VALUES(?, ?)")),this._insFts}_upsertFile=null;upsertFileStmt(){return this._upsertFile||(this._upsertFile=this.db.prepare(`INSERT INTO files(path, language, content_hash, mtime_ms, size, indexed_at)
@@ -115,22 +115,22 @@ CREATE TABLE IF NOT EXISTS embeddings (
115
115
  content_hash = excluded.content_hash,
116
116
  mtime_ms = excluded.mtime_ms,
117
117
  size = excluded.size,
118
- indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as Yg}from"node:crypto";function dt(e){return Yg("sha256").update(e,"utf8").digest("hex")}function gl(e){return{node_key_hash:dt(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:dt(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?dt(e.signature):null}}function yl(e){return{src_key_hash:dt(e.srcKey),dst_key_hash:dt(e.dstKey),kind:e.kind}}function bl(e,t,n){return{node_key_hash:dt(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var _l=_(()=>{"use strict";s(dt,"sha256");s(gl,"toCloudNode");s(yl,"toCloudEdge");s(bl,"toCloudEmbedding")});function po(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function wl(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Qg(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var ut,pt,Xg,fo=_(()=>{"use strict";qt();_l();ut=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},pt=class{static{s(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(ct),lastSyncedAt:wl(await this.store.getMeta(so))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(gl),n=(await this.store.getAllEdges()).map(yl),r=await this.store.getMeta(at)??st,i=await this.store.getMeta(ct),o=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(g=>[g.language,g.count])),c={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:o,lang_dist:a},l=0,u=po(t,this.chunk),d=po(n,this.chunk*2),p=Math.max(1,u.length+d.length);for(let g of u)await this.post("/api/codebase/push",{...c,nodes:g,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:p});for(let g of d)await this.post("/api/codebase/push",{...c,nodes:[],edges:g}),this.cfg.onProgress?.({phase:"edges",done:++l,total:p});u.length===0&&d.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let m=t.map(g=>g.node_key_hash),f=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:m});this.cfg.onProgress?.({phase:"prune",done:p,total:p});let h=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(so,String(Date.now())),i&&await this.store.setMeta(ol,i),{nodes:t.length,edges:n.length,pruned:Qg(f.nodes_deleted),embeddings:h,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),o=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(u=>bl(u,t.get(u.nodeKey)??"",n)).filter(u=>u.content_hash!==""&&o[u.node_key_hash]!==u.content_hash);if(a.length===0)return 0;let c=po(a,Xg),l=0;for(let u of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:u}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(rr),n=await this.store.getMeta(ir),r=wl(await this.store.getMeta(or));if(!t||!n||!r)throw new ut("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let o=i?.error;throw new ut(`${n} failed (HTTP ${t.status})${o?`: ${o}`:""}`,t.status,o)}return i}},Xg=250;s(po,"chunkArray");s(wl,"numOrNull");s(Qg,"numOr0")});var kl={};q(kl,{CodeIndexSync:()=>pt,DEFAULT_DB_RELPATH:()=>ho,SyncError:()=>ut,createCodeIndexSync:()=>ey,createNodeCodeIndex:()=>go,openSqliteDatabase:()=>sr,probeBuiltinSqlite:()=>lt});import{mkdirSync as Zg}from"node:fs";import{posix as mo}from"node:path";function go(e){let t=e.dbPath??mo.join(e.repoRoot,ho);Zg(mo.dirname(t),{recursive:!0});let n=new Yt(t),r=new Ln;return new zt({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function ey(e){let t=e.dbPath??mo.join(e.repoRoot,ho),n=e.projectKey??ba(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new Yt(t);return new pt(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var ho,yo=_(()=>{"use strict";si();Na();lo();hl();fo();fo();uo();ho=".maind/code-index.sqlite";s(go,"createNodeCodeIndex");s(ey,"createCodeIndexSync")});import{execFileSync as vl}from"node:child_process";import{existsSync as Sl,realpathSync as El}from"node:fs";import{createRequire as ty}from"node:module";import{basename as ny,dirname as ry,isAbsolute as xl,join as iy,relative as Rl,resolve as cr,sep as Al}from"node:path";function Tl(){let e=lt();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return ty(import.meta.url)("better-sqlite3"),{ok:!0,backend:"better-sqlite3"}}catch(t){let n=t instanceof Error?t.message:String(t);return{ok:!1,reason:`node:sqlite: ${e.reason}; better-sqlite3: ${n}`}}}function Il(e){let t=e?.code??"",n=e instanceof Error?e.message:String(e);return/better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(`${t} ${n}`)||t==="ERR_DLOPEN_FAILED"||/NODE_MODULE_VERSION/.test(n)}function z(e=process.cwd()){try{let t=vl("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function Nl(e,t=z(),n=process.cwd()){let r=xl(e)?[e]:[cr(t,e),cr(n,e)];for(let i of r){let o=ry(i);if(!Sl(o))continue;let a;try{a=El(o)}catch{continue}let c=Pl(a);if(c===null)continue;let l=Rl(c,iy(a,ny(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Al).join("/")}}return null}function lr(e,t=z(),n=process.cwd()){let r=xl(e)?[e]:[cr(t,e),cr(n,e)];for(let i of r){if(!Sl(i))continue;let o;try{o=El(i)}catch{continue}let a=Pl(o);if(a===null)continue;let c=Rl(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Al).join("/")}}return null}function Pl(e){try{let t=vl("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function Dl(){return go({repoRoot:z()})}var Cl,Xt=_(()=>{"use strict";yo();s(Tl,"probeNativeStore");s(Il,"isNativeStoreUnavailable");Cl="codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";s(z,"resolveRepoRoot");s(Nl,"resolveRepoRootForPath");s(lr,"resolveRepoRootForDir");s(Pl,"gitToplevelOf");s(Dl,"defaultEngineFactory")});var Hl=_(()=>{"use strict"});var Ul=_(()=>{"use strict";W()});var cy,vR,Gl=_(()=>{"use strict";W();cy=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],vR=new RegExp(cy.join("|"),"g")});import{existsSync as bo,readdirSync as ly,readFileSync as dy}from"node:fs";import{spawnSync as uy}from"node:child_process";import{dirname as py,join as _o,posix as fy}from"node:path";function Kl(e){let t=[],n={host:"127.0.0.1",port:e.config.source==="missing"?null:e.config.port,configSource:e.config.source,reachable:null,ledgerCount:null};if(e.config.source==="missing")return t.push({id:`db.config_missing:${e.dir}`,status:"open",project:e.dir,title:"supabase/config.toml nirgends auffindbar \u2014 DB-Ziel unbekannt",detail:`Weder dieser Tree noch der Haupt-Worktree tragen eine config.toml f\xFCr ${e.dir}. Die Supabase-CLI w\xFCrde hier still auf ihren Default-Port ${wo} ausweichen \u2014 dorthin schreibt ein Werkzeug ohne Fehlermeldung, ggf. in die Datenbank eines FREMDEN Projekts (real passiert 2026-08-26: 'INSERT 0 1' in den falschen Ledger). Dieses Tool r\xE4t deshalb NIE einen Port und hat keine Verbindung versucht.`,hint:"config.toml aus dem Haupt-Checkout kopieren (sie ist bewusst gitignored \u2014 Ports/Keys sind lokal), dann erneut pr\xFCfen. `.maind/worktree-requirements` deklariert die Datei bereits f\xFCr check_divergence."}),{dir:e.dir,verdict:"blind",findings:t,db:n};e.config.source==="main_worktree"&&t.push({id:`db.config_missing_here:${e.dir}`,status:"open",project:e.dir,title:`config.toml fehlt in DIESEM Tree \u2014 Vergleich lief \xFCber den Haupt-Worktree (Port ${e.config.port})`,detail:`Der Ledger-Vergleich nutzt die config.toml des Haupt-Worktrees und ist damit aussagekr\xE4ftig. Aber jedes Supabase-CLI-Kommando, das HIER l\xE4uft, sieht keine config.toml und weicht still auf Port ${wo} aus \u2014 die Silent-Redirect-Falle vom 2026-08-26.`,hint:"config.toml aus dem Haupt-Checkout in diesen Worktree kopieren, bevor irgendein `supabase \u2026`-Kommando l\xE4uft."});let r=e.ledger;if(r===null||r.ok===!1){n.reachable=r===null?null:!1;let p=r===null?"unreachable":r.reason,m=r!==null&&r.ok===!1?r.detail:void 0,h={psql_missing:{title:"psql nicht im PATH \u2014 Ledger nicht lesbar",detailText:"Ohne psql kann der lokale Ledger nicht gelesen werden. Kein Urteil \xFCber Drift m\xF6glich.",hint:"psql installieren (z. B. `brew install libpq` + PATH) oder den lokalen Stack-Client nachr\xFCsten."},unreachable:{title:`lokale Datenbank auf 127.0.0.1:${e.config.port} nicht erreichbar`,detailText:"Der Port aus config.toml antwortet nicht \u2014 der Stack schl\xE4ft vermutlich. Scheitert wenigstens laut (anders als die Default-Port-Falle); ein Urteil \xFCber Drift ist trotzdem nicht m\xF6glich.",hint:"`npx supabase start` im Projekt, dann erneut pr\xFCfen."},no_ledger:{title:`Port ${e.config.port} antwortet, tr\xE4gt aber KEINEN Supabase-Ledger`,detailText:"supabase_migrations.schema_migrations existiert dort nicht. Mutma\xDFlich lauscht auf diesem Port eine FREMDE Datenbank \u2014 dieselbe Verwechslungsklasse wie die 54322-Panne, nur von der anderen Seite gesehen.",hint:"Pr\xFCfen, wer auf dem Port lauscht (`lsof -nP -iTCP:<port> -sTCP:LISTEN`), und die config.toml gegen das Projekt halten."},query_failed:{title:"Ledger-Abfrage fehlgeschlagen",detailText:`Die SELECT-Abfrage gegen supabase_migrations.schema_migrations scheiterte${m?`: ${m}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:h.title,detail:h.detailText,hint:h.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),o=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!i.has(p)).sort(ue);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:"`npx supabase migration up` im Projektverzeichnis (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen.",versions:a});let c=r.versions.filter(p=>!o.has(p)).sort(ue),l=new Map,u=[];for(let p of c){let m=e.siblingVersions.get(p);if(m){let f=l.get(m)??[];f.push(p),l.set(m,f)}else u.push(p)}for(let[p,m]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${m.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${m.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:m});if(u.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${u.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${u.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:u}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),m=e.fileVersions.filter(h=>!p.has(h)).sort(ue),f=e.remote.versions.filter(h=>!o.has(h)).sort(ue);m.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${m.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${m.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:m}),f.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${f.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${f.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:f})}let d=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:d,findings:t,db:n}}function Bl(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function ql(e,t){if(t==="enoent")return{ok:!1,reason:"psql_missing"};let n=e.toLowerCase();return n.includes("does not exist")&&n.includes("schema_migrations")?{ok:!1,reason:"no_ledger"}:n.includes("connection refused")||n.includes("could not connect")||n.includes("timeout expired")||n.includes("server closed the connection")||n.includes("connection timed out")?{ok:!1,reason:"unreachable"}:{ok:!1,reason:"query_failed",detail:e.split(`
119
- `).filter(Boolean).slice(-1)[0]}}function Wl(e,t,n){let r=e(t,my,n);return r.ok===!1?ql(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
120
- `).map(i=>i.trim()).filter(Boolean)}}function zl(e){for(let t of e.split(/^\[/m)){if(!/^db\]/.test(t))continue;let n=/^\s*port\s*=\s*(\d+)/m.exec(t.slice(t.indexOf("]")+1));if(n)return Number(n[1])}return null}function hy(e){let t=S(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=py(t);return n===e?null:n}function gy(e,t,n){let r=fy.dirname(t),o=[{path:_o(e,r,"config.toml"),source:"worktree"}],a=hy(e);a&&o.push({path:_o(a,r,"config.toml"),source:"main_worktree"});for(let c of o)if(bo(c.path))try{let l=zl(dy(c.path,"utf8"));if(l===null){n.push(`${c.path}: kein [db].port lesbar \u2014 Kandidat \xFCbersprungen`);continue}return{source:c.source,port:l}}catch{n.push(`${c.path}: nicht lesbar \u2014 Kandidat \xFCbersprungen`)}return{source:"missing"}}function yy(e,t){let n=new Map,r=S(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=S(e,["rev-parse","--show-toplevel"])?.trim();for(let o of r.split(`
121
- `)){if(!o.startsWith("worktree "))continue;let a=o.slice(9).trim();if(!a||a===i||!bo(a))continue;let c=_o(a,t);if(bo(c))try{for(let l of ly(c)){let u=et(l);u!==null&&!n.has(u)&&n.set(u,a)}}catch{}}return n}function ko(e,t={}){let n=t.runPsql??Vl,r=t.timeoutMs??15e3,i=[],o=Te(e,t.dirs);if(o.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let a=[],c=[],l=[];for(let p of o){let m=gy(e,p.dir,i),f=m.source==="missing"?null:Wl(n,`postgresql://postgres:postgres@127.0.0.1:${m.port}/postgres`,r),h=t.remoteDbUrl!==void 0?Wl(n,t.remoteDbUrl,r):null,g=Kl({dir:p.dir,fileVersions:p.files.map(y=>y.version),config:m,ledger:f,siblingVersions:yy(e,p.dir),remote:h});a.push(...g.findings),l.push(g.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:g.verdict,db:g.db})}let u=Bl(l),d={open:0,warn:1,info:2};return a.sort((p,m)=>d[p.status]-d[m.status]||p.id.localeCompare(m.id)),{ok:u==="in_sync",verdict:u,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var wo,Vl,my,Jl=_(()=>{"use strict";W();Lt();wo=54322;s(Kl,"evaluateLedgerProject");s(Bl,"deriveLedgerVerdict");Vl=s((e,t,n)=>{let r=uy("psql",[e,"-tAc",t],{encoding:"utf8",timeout:n,env:{...process.env,PGCONNECT_TIMEOUT:"5"}});return r.error&&r.error.code==="ENOENT"?{ok:!1,code:"enoent",stderr:""}:r.status!==0?{ok:!1,code:"error",stderr:(r.stderr??"").trim()}:{ok:!0,stdout:r.stdout??""}},"defaultRunPsql"),my="select version from supabase_migrations.schema_migrations order by version";s(ql,"classifyLedgerError");s(Wl,"readLedger");s(zl,"parseDbPort");s(hy,"mainWorktreeRoot");s(gy,"resolveConfig");s(yy,"gatherSiblingVersions");s(ko,"checkMigrationLedgerDrift")});var Yl,Qt=_(()=>{"use strict";Hl();lo();hi();io();xi();Ul();Gl();_i();Ht();er();Wt();Lt();Zn();Jl();$i();ro();Ht();Wt();er();Zn();Nn();ui();qt();Yl="0.1.0"});import{execFile as id}from"node:child_process";import{randomUUID as Ry}from"node:crypto";function Py(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return So.test(t)?t:Ry()}function Eo(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function Dy(e,t){let n=(e.MAIND_AUTO_WORKING_PATHS??"").trim().toLowerCase();return n==="on"||n==="1"||n==="true"?!0:n==="off"||n==="0"||n==="false"?!1:t?.auto_working_paths===!0}async function Oy(e){return await new Promise(t=>{id("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(My(r))})})}function My(e){let t=(e??"").trim().toLowerCase();return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t)?t:null}async function Fy(){return await new Promise(e=>{id("git",["rev-parse","--abbrev-ref","HEAD"],{timeout:2e3,encoding:"utf8"},(t,n)=>{if(t)return e(null);let r=n.trim();e(r.length>0&&r!=="HEAD"?r:null)})})}function Ly(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function $y(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=So.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(o=>{So.test(o)&&(n=o.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var rd,od,Ay,Ty,Iy,Cy,Ny,So,mr,xo=_(()=>{"use strict";Xe();rd=45e3,od=3e4,Ay=5,Ty=120,Iy=3e4,Cy=15*6e4,Ny=1500,So=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Py,"resolveClientSessionId");s(Eo,"autoAnnounceDisabled");s(Dy,"autoWorkingPathsEnabled");mr=class{static{s(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;lastBranch=null;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??ne)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??Fy,this.gitBranchObject=t.gitBranchObject??Oy,this.log=t.log??(i=>process.stderr.write(i+`
122
- `)),this.machineLabel=Ly(r?.machine_label),this.enabled=this.projectKey!==null&&!Eo(n,r),this.workingPathsEnabled=Dy(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??$y(n,Py(n)),this.sessionMeta=t.sessionMeta??null}get sessionId(){return this.identity.current().id}get isEnabled(){return this.enabled}onSessionReady(){!this.enabled||this.ended||this.lastAnnounceAt>0||this.announce("active")}onActivity(){!this.enabled||this.ended||this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<rd||this.announce("active"))}pollActivity(){if(!this.enabled||this.ended)return;let t=this.identity.activityAtMs();if(t===null){this.noteMissingSideChannel();return}this.missingSideChannelPolls=0,!(t<=this.lastActivityAt)&&this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<rd||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<Ay||(this.warnedMissingSideChannel=!0,this.log("[maind-mcp-bridge] presence: no activity side channel for this session \u2014 presence now refreshes only on MAIND tool calls, so a session that is working can still appear stale. Re-run `maind-mcp-bridge install` to wire the hooks."))}async end(){if(!this.enabled||this.ended||(this.ended=!0,this.lastAnnounceAt===0))return;let t=new Promise(n=>setTimeout(n,Ny).unref());await Promise.race([this.send("ended"),t])}async announce(t){if(!this.inFlight&&!(this.now()<this.nextAttemptAt)){this.inFlight=!0;try{await this.send(t),this.consecutiveFailures>0&&this.log("[maind-mcp-bridge] presence announce recovered."),this.consecutiveFailures=0,this.nextAttemptAt=0,this.lastAnnounceAt=this.now()}catch(n){this.consecutiveFailures+=1;let r=Math.min(Iy*2**(this.consecutiveFailures-1),Cy);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{t==="active"&&this.identity.tryUpgrade()}catch{}let n=this.identity.current(),r={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:Ty,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let o=await this.gitBranch();if(o&&(r.branch=o),this.lastBranch=o,o)try{let a=await this.gitBranchObject(o);a!==null&&a!==this.lastSentObjectId&&(r.object_ids=[a],this.lastSentObjectId=a)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.sessionMeta!==null)try{let a=await this.sessionMeta();a?.model&&(r.model=a.model),a?.title&&(r.title=a.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let a=await this.deriveWorkingPaths();a&&a.length>0&&(r.working_paths=a)}catch{}}let i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let o=i;if(o.ok===!0&&typeof o.session_id=="string")try{this.identity.adopt(o.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let o={sessionId:this.sessionId,branch:this.lastBranch},a=typeof i=="object"?i:null;if(a!==null&&a.ok===!0)this.snapshot.write(i,o);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,o)}}}catch{}}};s(Oy,"defaultGitBranchObject");s(My,"normalizeObjectId");s(Fy,"defaultGitBranch");s(Ly,"normalizeMachineLabel");s($y,"staticIdentity")});import{mkdirSync as sd,readdirSync as dd,readFileSync as jy,renameSync as ad,statSync as Hy,unlinkSync as ud,writeFileSync as cd}from"node:fs";import{homedir as Uy}from"node:os";import{join as ft}from"node:path";function pd(){return ft(Uy(),".maind","presence")}function fd(e,t){return ft(e,t)}function md(e){let t=e.baseDir??pd(),n=fd(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,o=e.cwd??process.cwd(),a=e.now??Date.now,c=null;return{write(l,u){try{if(typeof l!="object"||l===null)return;let d=l;if(d.ok!==!0)return;let p={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:Array.isArray(d.peers)?d.peers:[],conflicts:Array.isArray(d.conflicts)?d.conflicts:[]};sd(n,{recursive:!0,mode:448}),c=ft(n,`${u.sessionId}.json`);let m=`${c}.tmp-${r}`;cd(m,JSON.stringify(p),{mode:384}),ad(m,c),ld(n,a(),c)}catch{}},endSession(){try{c&&ud(c)}catch{}},markFailed(l,u){try{let d={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:[],conflicts:[],announce_error:l};sd(n,{recursive:!0,mode:448}),c=ft(n,`${u.sessionId}.json`);let p=`${c}.tmp-${r}`;cd(p,JSON.stringify(d),{mode:384}),ad(p,c),ld(n,a(),c)}catch{}}}}function ld(e,t,n){try{for(let r of dd(e)){if(!r.endsWith(".json"))continue;let i=ft(e,r);if(i!==n)try{t-Hy(i).mtimeMs>Gy&&ud(i)}catch{}}}catch{}}function mt(e,t=pd()){try{let n=fd(t,e),r=[];for(let i of dd(n))if(i.endsWith(".json"))try{let o=JSON.parse(jy(ft(n,i),"utf8")),a=Wy(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function Wy(e){if(typeof e!="object"||e===null)return null;let t=e;return t.v!==1||typeof t.written_at!="string"||typeof t.project_key!="string"||typeof t.own_session_id!="string"||typeof t.own_pid!="number"||typeof t.own_ppid!="number"||typeof t.cwd!="string"?null:{v:1,written_at:t.written_at,project_key:t.project_key,own_session_id:t.own_session_id,own_pid:t.own_pid,own_ppid:t.own_ppid,cwd:t.cwd,branch:typeof t.branch=="string"?t.branch:null,peers:Array.isArray(t.peers)?t.peers:[],conflicts:Array.isArray(t.conflicts)?t.conflicts:[],...typeof t.announce_error=="string"?{announce_error:t.announce_error}:{}}}var Gy,hr=_(()=>{"use strict";Gy=120*6e4;s(pd,"presenceSnapshotBaseDir");s(fd,"projectDir");s(md,"createSnapshotStore");s(ld,"pruneStale");s(mt,"readSnapshots");s(Wy,"parseSnapshot")});import{execFileSync as Ky}from"node:child_process";import{createHash as By,randomUUID as Vy}from"node:crypto";import{existsSync as qy,mkdirSync as zy,readdirSync as Jy,readFileSync as gd,renameSync as Yy,statSync as Ro,unlinkSync as yd,writeFileSync as Xy}from"node:fs";import{homedir as Qy}from"node:os";import{basename as Zy,join as ke}from"node:path";function ht(e){return ke(e??ke(Qy(),".maind","presence"),"identity")}function bd(e,t){if(e){let n=Zy(e).replace(/\.jsonl$/i,"");if(Zt.test(n))return n.toLowerCase()}return t&&Zt.test(t)?t.toLowerCase():null}function _d(e){let t=e.nowMs??Date.now();zy(e.dir,{recursive:!0,mode:448});let n=ke(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(gd(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let o=e.transcriptPath??i.transcript_path,a=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...o?{transcript_path:o}:{},...a?{model:a}:{}};Xy(r,JSON.stringify(c,null,2)+`
123
- `,{mode:384}),Yy(r,n),ib(e.dir,t)}function wd(e,t,n,r=Date.now()){try{let i=Ro(ke(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function kd(e,t){try{yd(ke(e,`${t}.json`))}catch{}}function ib(e,t){try{for(let n of Jy(e))if(n.endsWith(".json"))try{let r=Ro(ke(e,n));t-r.mtimeMs>tb&&yd(ke(e,n))}catch{}}catch{}}function ob(e){return vd(e)?.file??null}function vd(e){let t=ke(e.dir,`${e.agentPid}.json`);try{if(!qy(t))return null;let n=Ro(t);if(n.mtimeMs<e.bridgeStartMs-nb)return null;let r=JSON.parse(gd(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Zt.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!sb(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function hd(e){return e.replace(/\/+$/,"")}function sb(e,t){let n=hd(e),r=hd(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function ab(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=By("sha1").update(n).update(e,"utf8").digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let o=i.toString("hex");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function cb(e){if(process.platform==="win32")return null;try{let t=Ky("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function lb(){try{return U()}catch{return null}}var Zt,eb,tb,nb,rb,gr,yr=_(()=>{"use strict";B();Zt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,eb=8,tb=48*60*6e4,nb=6e4,rb="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(ht,"identityDirPath");s(bd,"transcriptStemOf");s(_d,"writeAgentIdentityFile");s(wd,"identityFileStale");s(kd,"deleteAgentIdentityFile");s(ib,"pruneIdentityDir");s(ob,"readAgentIdentityFile");s(vd,"readAgentIdentityEntry");s(hd,"normDir");s(sb,"sameSessionTree");s(ab,"uuidV5");s(cb,"processStartTime");gr=class{static{s(this,"SessionIdentityManager")}env;agentPid;cwd;dir;bridgeStartMs;nowMs;envId;id;source;aliases=[];constructor(t){this.env=t.env??process.env,this.agentPid=t.agentPid??process.ppid,this.cwd=t.cwd??process.cwd(),this.dir=t.identityDir??ht(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Zt.test(n)?n:null;let r=this.readStem();if(r!==null){this.id=r,this.source="client_native",this.envId&&this.envId!==r&&(this.aliases=[this.envId]);return}if(this.envId!==null){this.id=this.envId,this.source="env";return}let i=(t.deviceId??lb)(),o=(t.ppidStart??cb)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=ab(`${i}|${this.agentPid}|${o}|${t.projectKey}`,rb),this.source="derived";return}this.id=Vy(),this.source="random"}current(){return{id:this.id,source:this.source,aliases:[...this.aliases]}}tryUpgrade(){if(this.source==="client_native")return!1;let t=this.readStem();if(t===null||t===this.id)return!1;let n=this.id;return this.id=t,this.source="client_native",this.pushAlias(n),this.envId!==null&&this.pushAlias(this.envId),!0}adopt(t){let n=t.trim().toLowerCase();if(!Zt.test(n)||n===this.id)return;let r=this.id;this.id=n,this.pushAlias(r)}pushAlias(t){t===this.id||this.aliases.includes(t)||(this.aliases.push(t),this.aliases.length>eb&&this.aliases.shift())}activityAtMs(){return vd({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let t=this.sideChannel();return t===null?null:t.transcript_stem.toLowerCase()}sideChannel(){return ob({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(lb,"defaultDeviceId")});function Ao(){return{ultracode:!1,planMode:!1,autoMode:!1}}var To=_(()=>{"use strict";s(Ao,"newModeState")});import{createReadStream as db,existsSync as ub}from"node:fs";import{stat as pb}from"node:fs/promises";import{createInterface as fb}from"node:readline";async function Io(e){if(!e||!ub(e))return null;let t;try{t=await pb(e)}catch{return null}let n=new Set,r=0,i=0,o=0;return await new Promise(a=>{let c=db(e,{encoding:"utf-8"}),l=fb({input:c});l.on("line",u=>{let d=u.trim();if(d){o++;try{let p=JSON.parse(d),m=p.message?.usage;if(!m)return;let f=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,h=typeof p.requestId=="string"&&p.requestId?p.requestId:null,g=f??h;if(g!==null){if(n.has(g))return;n.add(g)}typeof m.input_tokens=="number"&&(r+=m.input_tokens),typeof m.output_tokens=="number"&&(i+=m.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:o,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var Sd=_(()=>{"use strict";s(Io,"summariseTranscript")});var Ed=_(()=>{"use strict"});function en(e){if(!e)return null;let t=null;for(let n of e.matchAll(hb)){let r=n[1].toLowerCase();mb.has(r)&&(t=r)}return t}var mb,hb,br=_(()=>{"use strict";mb=new Set(["low","medium","high","xhigh","max"]),hb=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(en,"detectEffortLevel")});import{createReadStream as gb,existsSync as yb,readdirSync as bb}from"node:fs";import{basename as Ad,dirname as _b,join as xd}from"node:path";import{createInterface as wb}from"node:readline";function gt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function Sb(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let i=vb[r.name];if(!i||!r.input||typeof r.input!="object")continue;let o=r.input[i];typeof o=="string"&&o.length>0&&t.push(o)}return t}function _r(e){let t=Ad(e).replace(/\.jsonl$/,""),n=xd(_b(e),t,"subagents"),r;try{r=bb(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>xd(n,i))}async function Rd(e,t,n,r,i){yb(e)&&await new Promise(o=>{let a=gb(e,{encoding:"utf-8"}),c=wb({input:a}),l=0;c.on("line",u=>{l++;let d=u.trim();if(!d)return;let p;try{p=JSON.parse(d)}catch{return}if(p.message?.role!=="assistant")return;let m=typeof p.message.id=="string"&&p.message.id?p.message.id:null,f=typeof p.requestId=="string"&&p.requestId?p.requestId:null,h=m??f??`${e}#${l}`,g=Sb(p.message.content),y=r.get(h);if(y){for(let E of g)y.edited_paths.includes(E)||y.edited_paths.push(E);return}if(n.has(h))return;n.add(h);let b=p.message.usage??{},w=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,v=typeof p.message.model=="string"&&p.message.model?p.message.model:"",k={ts:Number.isFinite(w)?w:0,model:v||"<unknown>",synthetic:v===kb,input_tokens:gt(b.input_tokens),output_tokens:gt(b.output_tokens),cache_read_tokens:gt(b.cache_read_input_tokens),cache_creation_tokens:gt(b.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(gt(b.cache_creation?.ephemeral_1h_input_tokens),gt(b.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:t,edited_paths:g,cwd:typeof p.cwd=="string"&&p.cwd?p.cwd:null};r.set(h,k),i.push(k)}),c.on("close",()=>o()),c.on("error",()=>o()),a.on("error",()=>o())})}function Co(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];i.ts>0?n=i.ts:n>0&&(i.ts=n)}}async function tn(e){let t=new Set,n=new Map,r=[],i=e?_r(e):[];if(!e)return{turns:r,subagent_files:i};let o=[];await Rd(e,Fe,t,n,o),Co(o),r.push(...o);for(let a of i){let c=[],l=Ad(a).replace(/\.jsonl$/,"");await Rd(a,l,t,n,c),Co(c);for(let u of c)u.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:i}}var Fe,kb,vb,wr=_(()=>{"use strict";Fe="main",kb="<synthetic>",vb={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(gt,"num");s(Sb,"editedPathsOf");s(_r,"subagentFilesOf");s(Rd,"readStream");s(Co,"fillTimestamps");s(tn,"collectTurns")});import{createReadStream as Td,existsSync as Eb}from"node:fs";import{createInterface as Id}from"node:readline";function Nb(e,t,n,r,i){let o=`${n?"s":"m"}:${t}`,a=e.get(o);if(!a){e.set(o,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}a.turns++,a.output_tokens+=r,i>0&&((a.first_ts===0||i<a.first_ts)&&(a.first_ts=i),i>a.last_ts&&(a.last_ts=i))}function kr(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function Pb(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
124
- `)}function Db(e,t){let n=s(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[o,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of o)a.has(l)&&c++;return c/o.size>=.8}function Ob(e,t,n){return xb.test(e)?{polarity:-1,magnitude:yt.rework,kind:"rework"}:n&&Rb.test(e)?{polarity:-1,magnitude:yt.correction,kind:"correction"}:Ab.test(e)?{polarity:1,magnitude:yt.acceptance,kind:"acceptance"}:t!==null&&Db(t,e)?{polarity:-1,magnitude:yt.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function Mb(e){return{session_id:e,user_turns:0,assistant_turns:0,tool_calls:0,agent_questions:0,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,user_chars:0,user_token_estimate:0,human_share:0,reactions_pos:0,reactions_neg:0,net_sentiment:0,corrections:0,reworks:0,interrupts:0,tool_denials:0,repeated_instructions:0,acceptances:0,momentum_series:[],momentum_final:0,momentum_auc:0,ended_positive:!1,recovery_events:0,effort_at_end:null,model_mix:[],ai_title:null,session_slug:null,maind_tool_calls:{},maind_connected:"unknown",lines_seen:0,analyzer_version:Cd}}async function Fb(e,t){for(let n of _r(e))await new Promise(r=>{let i=Id({input:Td(n,{encoding:"utf-8"})});i.on("line",o=>{let a=o.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of kr(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(vr))continue;let u=l.name.slice(vr.length);u&&(t.maind_tool_calls[u]=(t.maind_tool_calls[u]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function No(e,t={}){let n=Mb("");if(!e||!Eb(e))return n;let r=t.turns??(await tn(e)).turns;for(let f of r)n.input_tokens+=f.input_tokens,n.output_tokens+=f.output_tokens,n.cache_read_tokens+=f.cache_read_tokens,n.cache_creation_tokens+=f.cache_creation_tokens,f.sidechain||n.assistant_turns++;let i=[],o=new Map,a=null,c=!1,l=null;await new Promise(f=>{let h=Td(e,{encoding:"utf-8"}),g=Id({input:h}),y=s(b=>{let w=b.trim();if(!w)return;let v;try{v=JSON.parse(w)}catch{return}if(n.lines_seen++,!n.session_id){let N=v.sessionId??v.session_id;typeof N=="string"&&N&&(n.session_id=N)}v.type==="ai-title"&&typeof v.aiTitle=="string"&&v.aiTitle&&(n.ai_title=v.aiTitle),typeof v.slug=="string"&&v.slug&&(n.session_slug=v.slug);let k=v.message?.role,E=v.isSidechain===!0;if(k==="assistant")for(let N of kr(v.message?.content)){if(N.type!=="tool_use"||typeof N.name!="string"||!N.name.startsWith(vr))continue;let Ke=N.name.slice(vr.length);Ke&&(n.maind_tool_calls[Ke]=(n.maind_tool_calls[Ke]??0)+1)}if(E)return;if(k==="assistant"){let N=kr(v.message?.content),Ke=!1;for(let bs of N)bs.type==="tool_use"&&(n.tool_calls++,Ke=!0,bs.name==="AskUserQuestion"&&n.agent_questions++);c=Ke;return}if(k!=="user")return;let R=kr(v.message?.content),I=Pb(R);if(I.includes(Tb)){n.interrupts++,i.push({polarity:-1,magnitude:yt.interrupt,kind:"interrupt"});return}if(R.some(N=>N.type==="tool_result"&&N.is_error===!0&&typeof N.content=="string"&&N.content.includes(Ib))){n.tool_denials++,i.push({polarity:-1,magnitude:yt.denial,kind:"denial"});return}if(R.some(N=>N.type==="tool_result")||!I.trim())return;n.user_turns++,n.user_chars+=I.length;let A=en(I);A&&(a=A);let j=Ob(I,l,c);l=I,j.kind==="correction"?n.corrections++:j.kind==="rework"?n.reworks++:j.kind==="repeat"?n.repeated_instructions++:j.kind==="acceptance"&&n.acceptances++,j.polarity!==0&&i.push(j),c=!1},"processLine");g.on("line",b=>{try{y(b)}catch{}}),g.on("close",()=>f()),g.on("error",()=>f()),h.on("error",()=>f())}),await Fb(e,n),n.effort_at_end=a;for(let f of r)f.synthetic||f.model==="<unknown>"||Nb(o,f.model,f.sidechain,f.output_tokens,f.ts);n.model_mix=[...o.values()].sort((f,h)=>f.first_ts-h.first_ts||f.model.localeCompare(h.model)),n.user_token_estimate=Math.round(n.user_chars/4);let u=n.user_token_estimate+n.output_tokens;n.human_share=u>0?Number((n.user_token_estimate/u).toFixed(4)):0;let d=0,p=0,m=[];return i.forEach((f,h)=>{f.polarity>0?n.reactions_pos++:f.polarity<0&&n.reactions_neg++,d=d*Cb+f.polarity*f.magnitude;let g=Number(d.toFixed(3));m.push({t:h,value:g,...f.kind!=="neutral"?{kind:f.kind}:{}}),p+=g,h>0&&i[h-1].polarity<0&&f.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=m,n.momentum_final=m.length?m[m.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls).length>0&&(n.maind_connected="connected"),n}var vr,Cd,xb,Rb,Ab,Tb,Ib,Cb,yt,Nd=_(()=>{"use strict";br();wr();vr="mcp__maind__",Cd="2026-09-09",xb=/(\brückgängig\b|zurücknehmen|\bnochmal(s)?\b|noch mal|\brevert\b|\bundo\b|\bredo\b|stattdessen|\binstead\b|mach(e)? das (nochmal|neu)|try again)/i,Rb=/(\bnein\b|\bfalsch\b|stimmt nicht|das ist nicht|so nicht|\bnicht so\b|warum hast du|wieso hast du|\bno\b|\bnope\b|\bwrong\b|\bincorrect\b|that'?s not|that is not|\bdon'?t\b|\bdoesn'?t\b|shouldn'?t)/i,Ab=/(\bdanke\b|\bperfekt\b|\bsuper\b|\bpasst\b|\bgenau\b|sieht gut|\bcommit\b|\bship\b|\bmerge\b|\bpush\b|looks good|\blgtm\b|\bthanks\b|thank you|\bperfect\b|\bgreat\b|\bexactly\b|\bnice\b|well done|👍|✅|🎉)/i,Tb="[Request interrupted by user",Ib="The user doesn't want to proceed with this tool use",Cb=.7,yt={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(Nb,"bumpModel");s(kr,"asBlocks");s(Pb,"textOf");s(Db,"isRepeat");s(Ob,"classifyGenuine");s(Mb,"emptyAnalysis");s(Fb,"tallySubagentMaindCalls");s(No,"analyzeSession")});function Po(e){let t=e!==null&&typeof e=="object"?e:{},n=typeof t.slices_stored=="boolean"?t.slices_stored:null;return{analyticsStored:t.analytics_stored===!0,spanStored:t.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof t.slices_reason=="string"?t.slices_reason:null,slicesCount:typeof t.slices_count=="number"&&Number.isFinite(t.slices_count)?t.slices_count:0}}function Do(e,t){return!t||e.slicesStored===!0?null:e.slicesStored===null?"cost slices sent, verdict unknown \u2014 the ingest endpoint predates slice verdicts (redeploy mcp-client-metrics-ingest)":`cost slices not stored: ${e.slicesReason??"no reason given"} (${e.slicesCount} sent)`}function Oo(e,t,n,r="unknown",i){let o={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};return t&&t.started_at&&(o.session_span=n?{...t,...n}:t),o}var Pd=_(()=>{"use strict";s(Po,"parseIngestResponse");s(Do,"describeSliceVerdict");s(Oo,"ingestBody")});import{isAbsolute as Dd,relative as Lb,resolve as Od,sep as Md}from"node:path";function Sr(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Lo(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=s(a=>{if(!Array.isArray(a))return[];let c=[];for(let l of a){if(!l||typeof l!="object")continue;let u=l,d=Sr(u.from);typeof u.object_id!="string"||!Mo.test(u.object_id)||d===null||c.push({object_id:u.object_id.toLowerCase(),from:d,to:Sr(u.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=Sr(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:Sr(c.to)})}let o=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let c=a;typeof c.object_id!="string"||!Mo.test(c.object_id)||typeof c.path_prefix=="string"&&o.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Mo.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:o}}function Ld(e,t){if(!Dd(e))return null;let n=Lb(Od(t),Od(e));return!n||n==="."||n.startsWith("..")||Dd(n)?null:Md==="/"?n:n.split(Md).join("/")}function $b(e,t){return t===""||e===t||e.startsWith(t+"/")}function $o(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function $d(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function jo(e,t){for(let n of $d(t))if($b(e,n.path_prefix))return n.object_id;return null}function jb(e,t){for(let n of $d(t))if($o(e,n.path_prefix))return n.object_id;return null}function Fo(e,t){return e>=t.from&&(t.to===null||e<t.to)}function jd(e,t,n,r){let i=e.ts,o=r?.anchors??[],a=t.map(c=>jo(c,o)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(d=>Fo(i,d));if(c.length)return c.sort((d,p)=>p.from-d.from||d.object_id.localeCompare(p.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(d=>Fo(i,d));if(l.length)return{object_id:(l.find(p=>a.includes(p.object_id))??l.find(p=>n!==null&&p.object_id===n.object_id)??[...l].sort((p,m)=>p.object_id.localeCompare(m.object_id))[0]).object_id,source:"binding"};let u=r.claims.filter(d=>Fo(i,d));if(u.length){let d=t[0]??n?.rel??null,p=(d===null?u:u.filter(m=>$o(m.path_prefix,d))).sort((m,f)=>f.path_prefix.length-m.path_prefix.length);for(let m of p){let f=jb(m.path_prefix,o);if(f)return{object_id:f,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function Ho(e,t,n){let r=t?.anchors??[],i=s(h=>{if(!n.repoRoot)return[];let g=[];for(let y of h.edited_paths){let b=Ld(y,n.repoRoot);b!==null&&!g.includes(b)&&g.push(b)}return g},"relOf"),o=s(h=>{for(let g of h){let y=jo(g,r);if(y)return{object_id:y,rel:g}}return null},"firstAnchoredEdit"),a=new Map;for(let h of e){let g=a.get(h.stream)??[];g.push(h),a.set(h.stream,g)}let c=[...a.entries()].sort(([h],[g])=>h===Fe?-1:g===Fe?1:0),l=[],u=s(h=>{let g=null;for(let y of l){if(y.ts>h&&h>0)break;g=y.seg}return g},"mainSegmentAt"),d=new Map;for(let[h,g]of c){let y=g.map((w,v)=>({t:w,i:v,rels:i(w)})).sort((w,v)=>w.t.ts-v.t.ts||w.i-v.i),b=null;for(let w of y){let v=o(w.rels);if(v){b=v;break}}!b&&h!==Fe&&y.length&&(b=u(y[0].t.ts));for(let w of y){let v=o(w.rels);v&&(b=v),h===Fe&&l.push({ts:w.t.ts,seg:b});let k=w.t;if(k.input_tokens+k.output_tokens+k.cache_read_tokens+k.cache_creation_tokens===0)continue;let R=jd(k,w.rels,b,t),I=k.input_tokens+k.cache_read_tokens+k.cache_creation_tokens>Fd?"above_200k":"standard",T=`${R.object_id??""}|${R.source}|${k.model}|${I}`,A=d.get(T);A||(A={object_id:R.object_id,attribution_source:R.source,model:k.model,context_tier:I,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},d.set(T,A)),A.input_tokens+=k.input_tokens,A.output_tokens+=k.output_tokens,A.cache_read_tokens+=k.cache_read_tokens,A.cache_creation_tokens+=k.cache_creation_tokens,A.cache_creation_1h_tokens+=k.cache_creation_1h_tokens,A.turns+=1,k.ts>0&&((A.firstMs===0||k.ts<A.firstMs)&&(A.firstMs=k.ts),k.ts>A.lastMs&&(A.lastMs=k.ts))}}let p=n.nowMs??Date.now(),m=[];for(let h of d.values()){let{firstMs:g,lastMs:y,...b}=h;b.first_ts=new Date(g>0?g:p).toISOString(),b.last_ts=new Date(y>0?y:p).toISOString(),m.push(b)}let f={lease:0,binding:1,claim:2,path:3,none:4};return m.sort((h,g)=>f[h.attribution_source]-f[g.attribution_source]||(h.object_id??"").localeCompare(g.object_id??"")||h.model.localeCompare(g.model)||h.context_tier.localeCompare(g.context_tier)),m}var Fd,Mo,Hd=_(()=>{"use strict";wr();Fd=2e5,Mo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Sr,"msOf");s(Lo,"parseCostContext");s(Ld,"toRepoRelative");s($b,"underPrefix");s($o,"prefixesOverlap");s($d,"sortedAnchors");s(jo,"anchorFor");s(jb,"bestAnchorOverlapping");s(Fo,"inWindow");s(jd,"assignTurn");s(Ho,"sliceSession")});import{createReadStream as Hb,existsSync as Ub}from"node:fs";import{createInterface as Gb}from"node:readline";function Ud(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function Bb(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
125
- `)}function Kd(e){return{session_id:e,started_at:null,ended_at:null,wall_seconds:0,agent_seconds:0,wait_seconds:0,pauses:[],pause_count:0,pause_seconds:0,pauses_truncated:!1,turn_count:0,event_count:0}}function Vb(e){let t=e.message?.role;if(t==="assistant")return{holder:Ud(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Ud(e.message?.content),r=Bb(n);return r.includes(Wb)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(Kb))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Uo(e){let t=Kd("");if(!e||!Ub(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(l=>{let u=Hb(e,{encoding:"utf-8"}),d=Gb({input:u}),p=s(m=>{let f=m.trim();if(!f)return;let h;try{h=JSON.parse(f)}catch{return}if(!t.session_id){let b=h.sessionId??h.session_id;typeof b=="string"&&b&&(t.session_id=b)}if(h.isSidechain===!0)return;let g=typeof h.timestamp=="string"?Date.parse(h.timestamp):NaN;if(!Number.isFinite(g)||o!==null&&g<o)return;let y=Vb(h);if(y!==null){if(t.event_count++,y.genuine&&t.turn_count++,n===null&&(n=g),r=g,o!==null){let b=g-o;a==="agent"?i+=b:b>=Gd*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<Wd&&c.push({offset_seconds:Math.round((o-n)/1e3),duration_seconds:Math.round(b/1e3)}))}o=g,a=y.holder}},"processLine");d.on("line",m=>{try{p(m)}catch{}}),d.on("close",()=>l()),d.on("error",()=>l()),u.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var Wb,Kb,Gd,Wd,Bd=_(()=>{"use strict";Wb="[Request interrupted by user",Kb="The user doesn't want to proceed with this tool use",Gd=60,Wd=200;s(Ud,"asBlocks");s(Bb,"textOf");s(Kd,"emptySpan");s(Vb,"classify");s(Uo,"analyzeSpan")});import{createReadStream as qb,existsSync as zb}from"node:fs";import{createInterface as Jb}from"node:readline";function Xb(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function Er(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Qb(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=[];for(let n of e)if(n&&typeof n=="object"&&"text"in n){let r=n.text;typeof r=="string"&&t.push(r)}return t.join(`
126
- `)}return""}async function Go(e,t={}){if(!e||!zb(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Ao(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,o=t.initialModes?{...t.initialModes}:Ao(),a=t.start??0;return await new Promise(c=>{let l=qb(e,{encoding:"utf-8",start:t.start??0}),u=Jb({input:l});u.on("line",p=>{a+=Buffer.byteLength(p,"utf-8")+1;let m=p.trim();if(!m)return;let f;try{f=JSON.parse(m)}catch{return}let h=f.sessionId??f.session_id??"",g=f.timestamp?Date.parse(f.timestamp):Date.now(),y=f.message?.role;if(f.type==="ai-title"&&typeof f.aiTitle=="string"){n.push({kind:"title",session_id:h,ts:g,title:f.aiTitle});return}if(f.type==="attachment"&&f.attachment?.type){let b=Yb[f.attachment.type];b&&(o[Xb(b.mode)]=b.active,n.push({kind:"mode",session_id:h,ts:g,mode:b.mode,active:b.active}));return}if(y==="user"){let b=Qb(f.message?.content),w=en(b);w&&(i=w);let v={session_id:h,ts:g,text:b,effort_directive:w};n.push({kind:"user",...v});return}if(y==="assistant"){let b=f.message?.usage,w=typeof f.message?.id=="string"&&f.message.id?f.message.id:null,v=typeof f.requestId=="string"&&f.requestId?f.requestId:null,k=w??v,E=k!==null&&r.has(k);k!==null&&!E&&r.add(k);let R={session_id:h,ts:g,model:f.message?.model??null,input_tokens:E?0:Er(b?.input_tokens),output_tokens:E?0:Er(b?.output_tokens),cache_read_input_tokens:E?0:Er(b?.cache_read_input_tokens),cache_creation_input_tokens:E?0:Er(b?.cache_creation_input_tokens),effort:i,isSidechain:f.isSidechain===!0,...o.ultracode?{ultracode:!0}:{},...o.planMode?{planMode:!0}:{},...o.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...R})}});let d=s(()=>({events:n,bytesRead:a,effortAtEnd:i,modesAtEnd:{...o},seenMessagesAtEnd:new Set(r)}),"finalResult");u.on("close",()=>c(d())),u.on("error",()=>c(d())),l.on("error",()=>c(d()))})}var Yb,Vd=_(()=>{"use strict";br();To();Yb={ultra_effort_enter:{mode:"ultracode",active:!0},ultra_effort_exit:{mode:"ultracode",active:!1},plan_mode:{mode:"plan",active:!0},plan_mode_reentry:{mode:"plan",active:!0},plan_mode_exit:{mode:"plan",active:!1},auto_mode:{mode:"auto",active:!0},auto_mode_exit:{mode:"auto",active:!1}};s(Xb,"modeFlagKey");s(Er,"num");s(Qb,"extractUserText");s(Go,"streamTranscript")});var qd=_(()=>{"use strict"});import{homedir as Zb}from"node:os";import{join as e_}from"node:path";function Ko(e){return e.replace(/[/.]/g,"-")}var t_,Wo,zd=_(()=>{"use strict";t_=Zb(),Wo=e_(t_,".claude","projects");s(Ko,"projectPathFromCwd")});var bt=_(()=>{"use strict";To();Sd();Ed();Nd();Pd();wr();Hd();Bd();Vd();br();qd();zd()});async function Xd(e){return Le("get_session_briefing",{tools:["claude-code"]},e)}async function Le(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??Bo,i=new AbortController,o=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let a={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n.apiKey}`,"x-maind-client-family":n.clientFamily??"claude-code","x-maind-client-version":n.bridgeVersion,"x-maind-bridge-version":n.bridgeVersion};n.deviceId&&(a["x-maind-device-id"]=n.deviceId),n.projectKey&&(a["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:a,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:d_,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),l=c.headers.get("mcp-session-id");if(await c.text().catch(()=>""),!c.ok||!l)return null;let u={...a,"mcp-session-id":l};await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(g=>g.text().catch(()=>"")).catch(()=>"");let d=await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!d.ok)return null;let m=(d.headers.get("content-type")??"").startsWith("text/event-stream")?await u_(d):await d.text();if(m.trim().length===0)return null;let f=JSON.parse(m);if(f.error||f.result?.isError)return null;let h=f.result?.content?.find(g=>g.type==="text"&&typeof g.text=="string")?.text;return typeof h=="string"&&h.trim().length>0?h:null}catch{return null}finally{clearTimeout(o)}}async function u_(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o="",a=s(()=>{if(i.length===0)return;let c=i.join(`
127
- `).trim();i=[],c.length>0&&(o=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let u;for(;(u=r.indexOf(`
128
- `))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let p=d.endsWith("\r")?d.slice(0,-1):d;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return a(),o}var Bo,d_,nn=_(()=>{"use strict";Bo="https://mcp.maind.dev/mcp",d_="2025-06-18";s(Xd,"fetchSessionBriefing");s(Le,"fetchToolText");s(u_,"readSseMessage")});function p_(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":U()}}async function Qd(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:p_(t),body:JSON.stringify({metrics:n})});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:o.slice(0,500)}}return{ok:!0,inserted:(await r.json().catch(()=>null))?.inserted_metrics??n.length,status:r.status}}catch(r){return{ok:!1,inserted:0,error:r instanceof Error?r.message:String(r)}}}var Rr,Vo=_(()=>{"use strict";B();Rr=process.env.MAIND_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";s(p_,"ingestHeaders");s(Qd,"postMetrics")});function Zd(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function tu(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,o=Array.isArray(i.active_claims)?i.active_claims:[],a=[];for(let c of o){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let d=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;d<=0||a.push({path_prefix:l.path_prefix,note:typeof l.note=="string"?l.note:null,remaining_seconds:Math.round(d)})}n.push({session_id_short:typeof i.session_id_short=="string"?i.session_id_short:"?",is_own_user:i.is_own_user===!0,branch:typeof i.branch=="string"?i.branch:null,focus:typeof i.focus=="string"?i.focus:null,machine_label:typeof i.machine_label=="string"?i.machine_label:null,last_seen_seconds:typeof i.last_seen_seconds=="number"?i.last_seen_seconds:0,claims:a,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function _t(e,t){if(t.hostPids.length>0){let r=e.find(i=>t.hostPids.includes(i.own_ppid));if(r)return{snap:r,via:"ppid"}}let n=e.find(r=>r.cwd===t.cwd);return n?{snap:n,via:"cwd"}:null}function rn(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function nu(e,t,n){let r=n.maxAgeMs??eu,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,a=tu(e,o),c=[];for(let l of a)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let u of l.claims)Zd(t,u.path_prefix)&&c.push(`'${u.path_prefix}' is CLAIMED by peer session ${l.session_id_short}${l.branch?` (branch ${l.branch}`:" ("}${l.machine_label?`, ${l.machine_label}`:""}${l.focus?`, focus: "${l.focus}"`:""}, last seen ${rn(l.last_seen_seconds+o)} ago)${u.note?` \u2014 note: "${u.note}"`:""}, claim expires in ${rn(u.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let u of l.working_paths)if(Zd(t,u)){c.push(`'${u}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${rn(l.last_seen_seconds+o)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${rn(o)} ago, advisory \u2014 never a lock):
118
+ indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as ny}from"node:crypto";function dt(e){return ny("sha256").update(e,"utf8").digest("hex")}function kl(e){return{node_key_hash:dt(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:dt(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?dt(e.signature):null}}function vl(e){return{src_key_hash:dt(e.srcKey),dst_key_hash:dt(e.dstKey),kind:e.kind}}function Sl(e,t,n){return{node_key_hash:dt(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var El=_(()=>{"use strict";s(dt,"sha256");s(kl,"toCloudNode");s(vl,"toCloudEdge");s(Sl,"toCloudEmbedding")});function fo(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function xl(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function iy(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var ut,pt,ry,mo=_(()=>{"use strict";qt();El();ut=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},pt=class{static{s(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(ct),lastSyncedAt:xl(await this.store.getMeta(ao))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(kl),n=(await this.store.getAllEdges()).map(vl),r=await this.store.getMeta(at)??st,i=await this.store.getMeta(ct),o=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(g=>[g.language,g.count])),c={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:o,lang_dist:a},l=0,p=fo(t,this.chunk),d=fo(n,this.chunk*2),u=Math.max(1,p.length+d.length);for(let g of p)await this.post("/api/codebase/push",{...c,nodes:g,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:u});for(let g of d)await this.post("/api/codebase/push",{...c,nodes:[],edges:g}),this.cfg.onProgress?.({phase:"edges",done:++l,total:u});p.length===0&&d.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let f=t.map(g=>g.node_key_hash),m=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:f});this.cfg.onProgress?.({phase:"prune",done:u,total:u});let h=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(ao,String(Date.now())),i&&await this.store.setMeta(dl,i),{nodes:t.length,edges:n.length,pruned:iy(m.nodes_deleted),embeddings:h,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),o=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(p=>Sl(p,t.get(p.nodeKey)??"",n)).filter(p=>p.content_hash!==""&&o[p.node_key_hash]!==p.content_hash);if(a.length===0)return 0;let c=fo(a,ry),l=0;for(let p of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:p}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(rr),n=await this.store.getMeta(ir),r=xl(await this.store.getMeta(or));if(!t||!n||!r)throw new ut("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let o=i?.error;throw new ut(`${n} failed (HTTP ${t.status})${o?`: ${o}`:""}`,t.status,o)}return i}},ry=250;s(fo,"chunkArray");s(xl,"numOrNull");s(iy,"numOr0")});var Rl={};q(Rl,{CodeIndexSync:()=>pt,DEFAULT_DB_RELPATH:()=>go,SyncError:()=>ut,createCodeIndexSync:()=>sy,createNodeCodeIndex:()=>yo,openSqliteDatabase:()=>sr,probeBuiltinSqlite:()=>lt});import{mkdirSync as oy}from"node:fs";import{posix as ho}from"node:path";function yo(e){let t=e.dbPath??ho.join(e.repoRoot,go);oy(ho.dirname(t),{recursive:!0});let n=new Yt(t),r=new Ln;return new zt({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function sy(e){let t=e.dbPath??ho.join(e.repoRoot,go),n=e.projectKey??Sa(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new Yt(t);return new pt(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var go,bo=_(()=>{"use strict";ai();Fa();uo();wl();mo();mo();po();go=".maind/code-index.sqlite";s(yo,"createNodeCodeIndex");s(sy,"createCodeIndexSync")});import{execFileSync as Al}from"node:child_process";import{existsSync as Tl,realpathSync as Il}from"node:fs";import{createRequire as ay}from"node:module";import{basename as cy,dirname as ly,isAbsolute as Cl,join as dy,relative as Nl,resolve as cr,sep as Pl}from"node:path";function Dl(){let e=lt();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return ay(import.meta.url)("better-sqlite3"),{ok:!0,backend:"better-sqlite3"}}catch(t){let n=t instanceof Error?t.message:String(t);return{ok:!1,reason:`node:sqlite: ${e.reason}; better-sqlite3: ${n}`}}}function Ol(e){let t=e?.code??"",n=e instanceof Error?e.message:String(e);return/better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(`${t} ${n}`)||t==="ERR_DLOPEN_FAILED"||/NODE_MODULE_VERSION/.test(n)}function z(e=process.cwd()){try{let t=Al("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function Fl(e,t=z(),n=process.cwd()){let r=Cl(e)?[e]:[cr(t,e),cr(n,e)];for(let i of r){let o=ly(i);if(!Tl(o))continue;let a;try{a=Il(o)}catch{continue}let c=Ll(a);if(c===null)continue;let l=Nl(c,dy(a,cy(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Pl).join("/")}}return null}function lr(e,t=z(),n=process.cwd()){let r=Cl(e)?[e]:[cr(t,e),cr(n,e)];for(let i of r){if(!Tl(i))continue;let o;try{o=Il(i)}catch{continue}let a=Ll(o);if(a===null)continue;let c=Nl(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Pl).join("/")}}return null}function Ll(e){try{let t=Al("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function $l(){return yo({repoRoot:z()})}var Ml,Xt=_(()=>{"use strict";bo();s(Dl,"probeNativeStore");s(Ol,"isNativeStoreUnavailable");Ml="codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";s(z,"resolveRepoRoot");s(Fl,"resolveRepoRootForPath");s(lr,"resolveRepoRootForDir");s(Ll,"gitToplevelOf");s($l,"defaultEngineFactory")});var Bl=_(()=>{"use strict"});var Vl=_(()=>{"use strict";W()});var my,DR,ql=_(()=>{"use strict";W();my=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],DR=new RegExp(my.join("|"),"g")});import{existsSync as _o,readdirSync as hy,readFileSync as gy}from"node:fs";import{spawnSync as yy}from"node:child_process";import{dirname as by,join as wo,posix as _y}from"node:path";function Jl(e){let t=[],n={host:"127.0.0.1",port:e.config.source==="missing"?null:e.config.port,configSource:e.config.source,reachable:null,ledgerCount:null};if(e.config.source==="missing")return t.push({id:`db.config_missing:${e.dir}`,status:"open",project:e.dir,title:"supabase/config.toml nirgends auffindbar \u2014 DB-Ziel unbekannt",detail:`Weder dieser Tree noch der Haupt-Worktree tragen eine config.toml f\xFCr ${e.dir}. Die Supabase-CLI w\xFCrde hier still auf ihren Default-Port ${ko} ausweichen \u2014 dorthin schreibt ein Werkzeug ohne Fehlermeldung, ggf. in die Datenbank eines FREMDEN Projekts (real passiert 2026-08-26: 'INSERT 0 1' in den falschen Ledger). Dieses Tool r\xE4t deshalb NIE einen Port und hat keine Verbindung versucht.`,hint:"config.toml aus dem Haupt-Checkout kopieren (sie ist bewusst gitignored \u2014 Ports/Keys sind lokal), dann erneut pr\xFCfen. `.maind/worktree-requirements` deklariert die Datei bereits f\xFCr check_divergence."}),{dir:e.dir,verdict:"blind",findings:t,db:n};e.config.source==="main_worktree"&&t.push({id:`db.config_missing_here:${e.dir}`,status:"open",project:e.dir,title:`config.toml fehlt in DIESEM Tree \u2014 Vergleich lief \xFCber den Haupt-Worktree (Port ${e.config.port})`,detail:`Der Ledger-Vergleich nutzt die config.toml des Haupt-Worktrees und ist damit aussagekr\xE4ftig. Aber jedes Supabase-CLI-Kommando, das HIER l\xE4uft, sieht keine config.toml und weicht still auf Port ${ko} aus \u2014 die Silent-Redirect-Falle vom 2026-08-26.`,hint:"config.toml aus dem Haupt-Checkout in diesen Worktree kopieren, bevor irgendein `supabase \u2026`-Kommando l\xE4uft."});let r=e.ledger;if(r===null||r.ok===!1){n.reachable=r===null?null:!1;let u=r===null?"unreachable":r.reason,f=r!==null&&r.ok===!1?r.detail:void 0,h={psql_missing:{title:"psql nicht im PATH \u2014 Ledger nicht lesbar",detailText:"Ohne psql kann der lokale Ledger nicht gelesen werden. Kein Urteil \xFCber Drift m\xF6glich.",hint:"psql installieren (z. B. `brew install libpq` + PATH) oder den lokalen Stack-Client nachr\xFCsten."},unreachable:{title:`lokale Datenbank auf 127.0.0.1:${e.config.port} nicht erreichbar`,detailText:"Der Port aus config.toml antwortet nicht \u2014 der Stack schl\xE4ft vermutlich. Scheitert wenigstens laut (anders als die Default-Port-Falle); ein Urteil \xFCber Drift ist trotzdem nicht m\xF6glich.",hint:"`npx supabase start` im Projekt, dann erneut pr\xFCfen."},no_ledger:{title:`Port ${e.config.port} antwortet, tr\xE4gt aber KEINEN Supabase-Ledger`,detailText:"supabase_migrations.schema_migrations existiert dort nicht. Mutma\xDFlich lauscht auf diesem Port eine FREMDE Datenbank \u2014 dieselbe Verwechslungsklasse wie die 54322-Panne, nur von der anderen Seite gesehen.",hint:"Pr\xFCfen, wer auf dem Port lauscht (`lsof -nP -iTCP:<port> -sTCP:LISTEN`), und die config.toml gegen das Projekt halten."},query_failed:{title:"Ledger-Abfrage fehlgeschlagen",detailText:`Die SELECT-Abfrage gegen supabase_migrations.schema_migrations scheiterte${f?`: ${f}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[u];return t.push({id:`db.${u}:${e.dir}`,status:"warn",project:e.dir,title:h.title,detail:h.detailText,hint:h.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),o=new Set(e.fileVersions),a=e.fileVersions.filter(u=>!i.has(u)).sort(ue);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:"`npx supabase migration up` im Projektverzeichnis (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen.",versions:a});let c=r.versions.filter(u=>!o.has(u)).sort(ue),l=new Map,p=[];for(let u of c){let f=e.siblingVersions.get(u);if(f){let m=l.get(f)??[];m.push(u),l.set(f,m)}else p.push(u)}for(let[u,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${u}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${u}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${u} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(p.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${p.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${p.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:p}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let u=new Set(e.remote.versions),f=e.fileVersions.filter(h=>!u.has(h)).sort(ue),m=e.remote.versions.filter(h=>!o.has(h)).sort(ue);f.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${f.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${f.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:f}),m.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${m.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${m.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:m})}let d=t.some(u=>u.status==="open"||u.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:d,findings:t,db:n}}function Yl(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Ql(e,t){if(t==="enoent")return{ok:!1,reason:"psql_missing"};let n=e.toLowerCase();return n.includes("does not exist")&&n.includes("schema_migrations")?{ok:!1,reason:"no_ledger"}:n.includes("connection refused")||n.includes("could not connect")||n.includes("timeout expired")||n.includes("server closed the connection")||n.includes("connection timed out")?{ok:!1,reason:"unreachable"}:{ok:!1,reason:"query_failed",detail:e.split(`
119
+ `).filter(Boolean).slice(-1)[0]}}function zl(e,t,n){let r=e(t,wy,n);return r.ok===!1?Ql(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
120
+ `).map(i=>i.trim()).filter(Boolean)}}function Zl(e){for(let t of e.split(/^\[/m)){if(!/^db\]/.test(t))continue;let n=/^\s*port\s*=\s*(\d+)/m.exec(t.slice(t.indexOf("]")+1));if(n)return Number(n[1])}return null}function ky(e){let t=S(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=by(t);return n===e?null:n}function vy(e,t,n){let r=_y.dirname(t),o=[{path:wo(e,r,"config.toml"),source:"worktree"}],a=ky(e);a&&o.push({path:wo(a,r,"config.toml"),source:"main_worktree"});for(let c of o)if(_o(c.path))try{let l=Zl(gy(c.path,"utf8"));if(l===null){n.push(`${c.path}: kein [db].port lesbar \u2014 Kandidat \xFCbersprungen`);continue}return{source:c.source,port:l}}catch{n.push(`${c.path}: nicht lesbar \u2014 Kandidat \xFCbersprungen`)}return{source:"missing"}}function Sy(e,t){let n=new Map,r=S(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=S(e,["rev-parse","--show-toplevel"])?.trim();for(let o of r.split(`
121
+ `)){if(!o.startsWith("worktree "))continue;let a=o.slice(9).trim();if(!a||a===i||!_o(a))continue;let c=wo(a,t);if(_o(c))try{for(let l of hy(c)){let p=et(l);p!==null&&!n.has(p)&&n.set(p,a)}}catch{}}return n}function vo(e,t={}){let n=t.runPsql??Xl,r=t.timeoutMs??15e3,i=[],o=Te(e,t.dirs);if(o.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let a=[],c=[],l=[];for(let u of o){let f=vy(e,u.dir,i),m=f.source==="missing"?null:zl(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),h=t.remoteDbUrl!==void 0?zl(n,t.remoteDbUrl,r):null,g=Jl({dir:u.dir,fileVersions:u.files.map(y=>y.version),config:f,ledger:m,siblingVersions:Sy(e,u.dir),remote:h});a.push(...g.findings),l.push(g.verdict),c.push({dir:u.dir,migrationCount:u.files.length,verdict:g.verdict,db:g.db})}let p=Yl(l),d={open:0,warn:1,info:2};return a.sort((u,f)=>d[u.status]-d[f.status]||u.id.localeCompare(f.id)),{ok:p==="in_sync",verdict:p,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var ko,Xl,wy,ed=_(()=>{"use strict";W();Lt();ko=54322;s(Jl,"evaluateLedgerProject");s(Yl,"deriveLedgerVerdict");Xl=s((e,t,n)=>{let r=yy("psql",[e,"-tAc",t],{encoding:"utf8",timeout:n,env:{...process.env,PGCONNECT_TIMEOUT:"5"}});return r.error&&r.error.code==="ENOENT"?{ok:!1,code:"enoent",stderr:""}:r.status!==0?{ok:!1,code:"error",stderr:(r.stderr??"").trim()}:{ok:!0,stdout:r.stdout??""}},"defaultRunPsql"),wy="select version from supabase_migrations.schema_migrations order by version";s(Ql,"classifyLedgerError");s(zl,"readLedger");s(Zl,"parseDbPort");s(ky,"mainWorktreeRoot");s(vy,"resolveConfig");s(Sy,"gatherSiblingVersions");s(vo,"checkMigrationLedgerDrift")});var td,Qt=_(()=>{"use strict";Bl();uo();gi();oo();Ri();Vl();ql();wi();Ht();er();Wt();Lt();Zn();ed();ji();io();Ht();Wt();er();Zn();Nn();pi();qt();td="0.1.0"});import{execFile as ld}from"node:child_process";import{randomUUID as Py}from"node:crypto";function $y(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return Eo.test(t)?t:Py()}function xo(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function jy(e,t){let n=(e.MAIND_AUTO_WORKING_PATHS??"").trim().toLowerCase();return n==="on"||n==="1"||n==="true"?!0:n==="off"||n==="0"||n==="false"?!1:t?.auto_working_paths===!0}async function Hy(e){return await new Promise(t=>{ld("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(Uy(r))})})}function Uy(e){let t=(e??"").trim().toLowerCase();return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t)?t:null}async function Gy(){return await new Promise(e=>{ld("git",["rev-parse","--abbrev-ref","HEAD"],{timeout:2e3,encoding:"utf8"},(t,n)=>{if(t)return e(null);let r=n.trim();e(r.length>0&&r!=="HEAD"?r:null)})})}function Wy(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function Ky(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=Eo.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(o=>{Eo.test(o)&&(n=o.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var cd,dd,Dy,Oy,My,Fy,Ly,Eo,mr,Ro=_(()=>{"use strict";Xe();cd=45e3,dd=3e4,Dy=5,Oy=120,My=3e4,Fy=15*6e4,Ly=1500,Eo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s($y,"resolveClientSessionId");s(xo,"autoAnnounceDisabled");s(jy,"autoWorkingPathsEnabled");mr=class{static{s(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;lastBranch=null;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??ne)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??Gy,this.gitBranchObject=t.gitBranchObject??Hy,this.log=t.log??(i=>process.stderr.write(i+`
122
+ `)),this.machineLabel=Wy(r?.machine_label),this.enabled=this.projectKey!==null&&!xo(n,r),this.workingPathsEnabled=jy(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??Ky(n,$y(n)),this.sessionMeta=t.sessionMeta??null}get sessionId(){return this.identity.current().id}get isEnabled(){return this.enabled}onSessionReady(){!this.enabled||this.ended||this.lastAnnounceAt>0||this.announce("active")}onActivity(){!this.enabled||this.ended||this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<cd||this.announce("active"))}pollActivity(){if(!this.enabled||this.ended)return;let t=this.identity.activityAtMs();if(t===null){this.noteMissingSideChannel();return}this.missingSideChannelPolls=0,!(t<=this.lastActivityAt)&&this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<cd||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<Dy||(this.warnedMissingSideChannel=!0,this.log("[maind-mcp-bridge] presence: no activity side channel for this session \u2014 presence now refreshes only on MAIND tool calls, so a session that is working can still appear stale. Re-run `maind-mcp-bridge install` to wire the hooks."))}async end(){if(!this.enabled||this.ended||(this.ended=!0,this.lastAnnounceAt===0))return;let t=new Promise(n=>setTimeout(n,Ly).unref());await Promise.race([this.send("ended"),t])}async announce(t){if(!this.inFlight&&!(this.now()<this.nextAttemptAt)){this.inFlight=!0;try{await this.send(t),this.consecutiveFailures>0&&this.log("[maind-mcp-bridge] presence announce recovered."),this.consecutiveFailures=0,this.nextAttemptAt=0,this.lastAnnounceAt=this.now()}catch(n){this.consecutiveFailures+=1;let r=Math.min(My*2**(this.consecutiveFailures-1),Fy);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{t==="active"&&this.identity.tryUpgrade()}catch{}let n=this.identity.current(),r={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:Oy,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let o=await this.gitBranch();if(o&&(r.branch=o),this.lastBranch=o,o)try{let a=await this.gitBranchObject(o);a!==null&&a!==this.lastSentObjectId&&(r.object_ids=[a],this.lastSentObjectId=a)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.sessionMeta!==null)try{let a=await this.sessionMeta();a?.model&&(r.model=a.model),a?.title&&(r.title=a.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let a=await this.deriveWorkingPaths();a&&a.length>0&&(r.working_paths=a)}catch{}}let i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let o=i;if(o.ok===!0&&typeof o.session_id=="string")try{this.identity.adopt(o.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let o={sessionId:this.sessionId,branch:this.lastBranch},a=typeof i=="object"?i:null;if(a!==null&&a.ok===!0)this.snapshot.write(i,o);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,o)}}}catch{}}};s(Hy,"defaultGitBranchObject");s(Uy,"normalizeObjectId");s(Gy,"defaultGitBranch");s(Wy,"normalizeMachineLabel");s(Ky,"staticIdentity")});import{mkdirSync as ud,readdirSync as hd,readFileSync as By,renameSync as pd,statSync as Vy,unlinkSync as gd,writeFileSync as fd}from"node:fs";import{homedir as qy}from"node:os";import{join as ft}from"node:path";function yd(){return ft(qy(),".maind","presence")}function bd(e,t){return ft(e,t)}function _d(e){let t=e.baseDir??yd(),n=bd(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,o=e.cwd??process.cwd(),a=e.now??Date.now,c=null;return{write(l,p){try{if(typeof l!="object"||l===null)return;let d=l;if(d.ok!==!0)return;let u={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:p.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:p.branch,peers:Array.isArray(d.peers)?d.peers:[],conflicts:Array.isArray(d.conflicts)?d.conflicts:[]};ud(n,{recursive:!0,mode:448}),c=ft(n,`${p.sessionId}.json`);let f=`${c}.tmp-${r}`;fd(f,JSON.stringify(u),{mode:384}),pd(f,c),md(n,a(),c)}catch{}},endSession(){try{c&&gd(c)}catch{}},markFailed(l,p){try{let d={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:p.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:p.branch,peers:[],conflicts:[],announce_error:l};ud(n,{recursive:!0,mode:448}),c=ft(n,`${p.sessionId}.json`);let u=`${c}.tmp-${r}`;fd(u,JSON.stringify(d),{mode:384}),pd(u,c),md(n,a(),c)}catch{}}}}function md(e,t,n){try{for(let r of hd(e)){if(!r.endsWith(".json"))continue;let i=ft(e,r);if(i!==n)try{t-Vy(i).mtimeMs>zy&&gd(i)}catch{}}}catch{}}function mt(e,t=yd()){try{let n=bd(t,e),r=[];for(let i of hd(n))if(i.endsWith(".json"))try{let o=JSON.parse(By(ft(n,i),"utf8")),a=Jy(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function Jy(e){if(typeof e!="object"||e===null)return null;let t=e;return t.v!==1||typeof t.written_at!="string"||typeof t.project_key!="string"||typeof t.own_session_id!="string"||typeof t.own_pid!="number"||typeof t.own_ppid!="number"||typeof t.cwd!="string"?null:{v:1,written_at:t.written_at,project_key:t.project_key,own_session_id:t.own_session_id,own_pid:t.own_pid,own_ppid:t.own_ppid,cwd:t.cwd,branch:typeof t.branch=="string"?t.branch:null,peers:Array.isArray(t.peers)?t.peers:[],conflicts:Array.isArray(t.conflicts)?t.conflicts:[],...typeof t.announce_error=="string"?{announce_error:t.announce_error}:{}}}var zy,hr=_(()=>{"use strict";zy=120*6e4;s(yd,"presenceSnapshotBaseDir");s(bd,"projectDir");s(_d,"createSnapshotStore");s(md,"pruneStale");s(mt,"readSnapshots");s(Jy,"parseSnapshot")});import{execFileSync as Yy}from"node:child_process";import{createHash as Xy,randomUUID as Qy}from"node:crypto";import{existsSync as Zy,mkdirSync as eb,readdirSync as tb,readFileSync as kd,renameSync as nb,statSync as Ao,unlinkSync as vd,writeFileSync as rb}from"node:fs";import{homedir as ib}from"node:os";import{basename as ob,join as ke}from"node:path";function ht(e){return ke(e??ke(ib(),".maind","presence"),"identity")}function Sd(e,t){if(e){let n=ob(e).replace(/\.jsonl$/i,"");if(Zt.test(n))return n.toLowerCase()}return t&&Zt.test(t)?t.toLowerCase():null}function Ed(e){let t=e.nowMs??Date.now();eb(e.dir,{recursive:!0,mode:448});let n=ke(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(kd(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let o=e.transcriptPath??i.transcript_path,a=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...o?{transcript_path:o}:{},...a?{model:a}:{}};rb(r,JSON.stringify(c,null,2)+`
123
+ `,{mode:384}),nb(r,n),db(e.dir,t)}function xd(e,t,n,r=Date.now()){try{let i=Ao(ke(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function Rd(e,t){try{vd(ke(e,`${t}.json`))}catch{}}function db(e,t){try{for(let n of tb(e))if(n.endsWith(".json"))try{let r=Ao(ke(e,n));t-r.mtimeMs>ab&&vd(ke(e,n))}catch{}}catch{}}function ub(e){return Ad(e)?.file??null}function Ad(e){let t=ke(e.dir,`${e.agentPid}.json`);try{if(!Zy(t))return null;let n=Ao(t);if(n.mtimeMs<e.bridgeStartMs-cb)return null;let r=JSON.parse(kd(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Zt.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!pb(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function wd(e){return e.replace(/\/+$/,"")}function pb(e,t){let n=wd(e),r=wd(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function fb(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=Xy("sha1").update(n).update(e,"utf8").digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let o=i.toString("hex");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function mb(e){if(process.platform==="win32")return null;try{let t=Yy("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function hb(){try{return U()}catch{return null}}var Zt,sb,ab,cb,lb,gr,yr=_(()=>{"use strict";B();Zt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sb=8,ab=48*60*6e4,cb=6e4,lb="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(ht,"identityDirPath");s(Sd,"transcriptStemOf");s(Ed,"writeAgentIdentityFile");s(xd,"identityFileStale");s(Rd,"deleteAgentIdentityFile");s(db,"pruneIdentityDir");s(ub,"readAgentIdentityFile");s(Ad,"readAgentIdentityEntry");s(wd,"normDir");s(pb,"sameSessionTree");s(fb,"uuidV5");s(mb,"processStartTime");gr=class{static{s(this,"SessionIdentityManager")}env;agentPid;cwd;dir;bridgeStartMs;nowMs;envId;id;source;aliases=[];constructor(t){this.env=t.env??process.env,this.agentPid=t.agentPid??process.ppid,this.cwd=t.cwd??process.cwd(),this.dir=t.identityDir??ht(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Zt.test(n)?n:null;let r=this.readStem();if(r!==null){this.id=r,this.source="client_native",this.envId&&this.envId!==r&&(this.aliases=[this.envId]);return}if(this.envId!==null){this.id=this.envId,this.source="env";return}let i=(t.deviceId??hb)(),o=(t.ppidStart??mb)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=fb(`${i}|${this.agentPid}|${o}|${t.projectKey}`,lb),this.source="derived";return}this.id=Qy(),this.source="random"}current(){return{id:this.id,source:this.source,aliases:[...this.aliases]}}tryUpgrade(){if(this.source==="client_native")return!1;let t=this.readStem();if(t===null||t===this.id)return!1;let n=this.id;return this.id=t,this.source="client_native",this.pushAlias(n),this.envId!==null&&this.pushAlias(this.envId),!0}adopt(t){let n=t.trim().toLowerCase();if(!Zt.test(n)||n===this.id)return;let r=this.id;this.id=n,this.pushAlias(r)}pushAlias(t){t===this.id||this.aliases.includes(t)||(this.aliases.push(t),this.aliases.length>sb&&this.aliases.shift())}activityAtMs(){return Ad({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let t=this.sideChannel();return t===null?null:t.transcript_stem.toLowerCase()}sideChannel(){return ub({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(hb,"defaultDeviceId")});function To(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Io=_(()=>{"use strict";s(To,"newModeState")});import{createReadStream as gb,existsSync as yb}from"node:fs";import{stat as bb}from"node:fs/promises";import{createInterface as _b}from"node:readline";async function Co(e){if(!e||!yb(e))return null;let t;try{t=await bb(e)}catch{return null}let n=new Set,r=0,i=0,o=0;return await new Promise(a=>{let c=gb(e,{encoding:"utf-8"}),l=_b({input:c});l.on("line",p=>{let d=p.trim();if(d){o++;try{let u=JSON.parse(d),f=u.message?.usage;if(!f)return;let m=typeof u.message?.id=="string"&&u.message.id?u.message.id:null,h=typeof u.requestId=="string"&&u.requestId?u.requestId:null,g=m??h;if(g!==null){if(n.has(g))return;n.add(g)}typeof f.input_tokens=="number"&&(r+=f.input_tokens),typeof f.output_tokens=="number"&&(i+=f.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:o,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var Td=_(()=>{"use strict";s(Co,"summariseTranscript")});var Id=_(()=>{"use strict"});function en(e){if(!e)return null;let t=null;for(let n of e.matchAll(kb)){let r=n[1].toLowerCase();wb.has(r)&&(t=r)}return t}var wb,kb,br=_(()=>{"use strict";wb=new Set(["low","medium","high","xhigh","max"]),kb=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(en,"detectEffortLevel")});import{createReadStream as vb,existsSync as Sb,readdirSync as Eb}from"node:fs";import{basename as Pd,dirname as xb,join as Cd}from"node:path";import{createInterface as Rb}from"node:readline";function gt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function Ib(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let i=Tb[r.name];if(!i||!r.input||typeof r.input!="object")continue;let o=r.input[i];typeof o=="string"&&o.length>0&&t.push(o)}return t}function _r(e){let t=Pd(e).replace(/\.jsonl$/,""),n=Cd(xb(e),t,"subagents"),r;try{r=Eb(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>Cd(n,i))}async function Nd(e,t,n,r,i){Sb(e)&&await new Promise(o=>{let a=vb(e,{encoding:"utf-8"}),c=Rb({input:a}),l=0;c.on("line",p=>{l++;let d=p.trim();if(!d)return;let u;try{u=JSON.parse(d)}catch{return}if(u.message?.role!=="assistant")return;let f=typeof u.message.id=="string"&&u.message.id?u.message.id:null,m=typeof u.requestId=="string"&&u.requestId?u.requestId:null,h=f??m??`${e}#${l}`,g=Ib(u.message.content),y=r.get(h);if(y){for(let E of g)y.edited_paths.includes(E)||y.edited_paths.push(E);return}if(n.has(h))return;n.add(h);let b=u.message.usage??{},w=typeof u.timestamp=="string"?Date.parse(u.timestamp):Number.NaN,v=typeof u.message.model=="string"&&u.message.model?u.message.model:"",k={ts:Number.isFinite(w)?w:0,model:v||"<unknown>",synthetic:v===Ab,input_tokens:gt(b.input_tokens),output_tokens:gt(b.output_tokens),cache_read_tokens:gt(b.cache_read_input_tokens),cache_creation_tokens:gt(b.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(gt(b.cache_creation?.ephemeral_1h_input_tokens),gt(b.cache_creation_input_tokens)),sidechain:u.isSidechain===!0,stream:t,edited_paths:g,cwd:typeof u.cwd=="string"&&u.cwd?u.cwd:null};r.set(h,k),i.push(k)}),c.on("close",()=>o()),c.on("error",()=>o()),a.on("error",()=>o())})}function No(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];i.ts>0?n=i.ts:n>0&&(i.ts=n)}}async function tn(e){let t=new Set,n=new Map,r=[],i=e?_r(e):[];if(!e)return{turns:r,subagent_files:i};let o=[];await Nd(e,Fe,t,n,o),No(o),r.push(...o);for(let a of i){let c=[],l=Pd(a).replace(/\.jsonl$/,"");await Nd(a,l,t,n,c),No(c);for(let p of c)p.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:i}}var Fe,Ab,Tb,wr=_(()=>{"use strict";Fe="main",Ab="<synthetic>",Tb={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(gt,"num");s(Ib,"editedPathsOf");s(_r,"subagentFilesOf");s(Nd,"readStream");s(No,"fillTimestamps");s(tn,"collectTurns")});import{createReadStream as Dd,existsSync as Cb}from"node:fs";import{createInterface as Od}from"node:readline";function Lb(e,t,n,r,i){let o=`${n?"s":"m"}:${t}`,a=e.get(o);if(!a){e.set(o,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}a.turns++,a.output_tokens+=r,i>0&&((a.first_ts===0||i<a.first_ts)&&(a.first_ts=i),i>a.last_ts&&(a.last_ts=i))}function kr(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function $b(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
124
+ `)}function jb(e,t){let n=s(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(p=>p.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[o,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of o)a.has(l)&&c++;return c/o.size>=.8}function Hb(e,t,n){return Nb.test(e)?{polarity:-1,magnitude:yt.rework,kind:"rework"}:n&&Pb.test(e)?{polarity:-1,magnitude:yt.correction,kind:"correction"}:Db.test(e)?{polarity:1,magnitude:yt.acceptance,kind:"acceptance"}:t!==null&&jb(t,e)?{polarity:-1,magnitude:yt.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function Ub(e){return{session_id:e,user_turns:0,assistant_turns:0,tool_calls:0,agent_questions:0,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,user_chars:0,user_token_estimate:0,human_share:0,reactions_pos:0,reactions_neg:0,net_sentiment:0,corrections:0,reworks:0,interrupts:0,tool_denials:0,repeated_instructions:0,acceptances:0,momentum_series:[],momentum_final:0,momentum_auc:0,ended_positive:!1,recovery_events:0,effort_at_end:null,model_mix:[],ai_title:null,session_slug:null,maind_tool_calls:{},maind_connected:"unknown",lines_seen:0,analyzer_version:Md,behaviour_measured:!0}}async function Gb(e,t){for(let n of _r(e))await new Promise(r=>{let i=Od({input:Dd(n,{encoding:"utf-8"})});i.on("line",o=>{let a=o.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of kr(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(vr))continue;let p=l.name.slice(vr.length);p&&(t.maind_tool_calls[p]=(t.maind_tool_calls[p]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function Po(e,t={}){let n=Ub("");if(!e||!Cb(e))return n;let r=t.turns??(await tn(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let i=[],o=new Map,a=null,c=!1,l=null;await new Promise(m=>{let h=Dd(e,{encoding:"utf-8"}),g=Od({input:h}),y=s(b=>{let w=b.trim();if(!w)return;let v;try{v=JSON.parse(w)}catch{return}if(n.lines_seen++,!n.session_id){let N=v.sessionId??v.session_id;typeof N=="string"&&N&&(n.session_id=N)}v.type==="ai-title"&&typeof v.aiTitle=="string"&&v.aiTitle&&(n.ai_title=v.aiTitle),typeof v.slug=="string"&&v.slug&&(n.session_slug=v.slug);let k=v.message?.role,E=v.isSidechain===!0;if(k==="assistant")for(let N of kr(v.message?.content)){if(N.type!=="tool_use"||typeof N.name!="string"||!N.name.startsWith(vr))continue;let Ke=N.name.slice(vr.length);Ke&&(n.maind_tool_calls[Ke]=(n.maind_tool_calls[Ke]??0)+1)}if(E)return;if(k==="assistant"){let N=kr(v.message?.content),Ke=!1;for(let Ss of N)Ss.type==="tool_use"&&(n.tool_calls++,Ke=!0,Ss.name==="AskUserQuestion"&&n.agent_questions++);c=Ke;return}if(k!=="user")return;let R=kr(v.message?.content),I=$b(R);if(I.includes(Ob)){n.interrupts++,i.push({polarity:-1,magnitude:yt.interrupt,kind:"interrupt"});return}if(R.some(N=>N.type==="tool_result"&&N.is_error===!0&&typeof N.content=="string"&&N.content.includes(Mb))){n.tool_denials++,i.push({polarity:-1,magnitude:yt.denial,kind:"denial"});return}if(R.some(N=>N.type==="tool_result")||!I.trim())return;n.user_turns++,n.user_chars+=I.length;let D=en(I);D&&(a=D);let A=Hb(I,l,c);l=I,A.kind==="correction"?n.corrections++:A.kind==="rework"?n.reworks++:A.kind==="repeat"?n.repeated_instructions++:A.kind==="acceptance"&&n.acceptances++,A.polarity!==0&&i.push(A),c=!1},"processLine");g.on("line",b=>{try{y(b)}catch{}}),g.on("close",()=>m()),g.on("error",()=>m()),h.on("error",()=>m())}),await Gb(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||Lb(o,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...o.values()].sort((m,h)=>m.first_ts-h.first_ts||m.model.localeCompare(h.model)),n.user_token_estimate=Math.round(n.user_chars/4);let p=n.user_token_estimate+n.output_tokens;n.human_share=p>0?Number((n.user_token_estimate/p).toFixed(4)):0;let d=0,u=0,f=[];return i.forEach((m,h)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,d=d*Fb+m.polarity*m.magnitude;let g=Number(d.toFixed(3));f.push({t:h,value:g,...m.kind!=="neutral"?{kind:m.kind}:{}}),u+=g,h>0&&i[h-1].polarity<0&&m.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(u.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls).length>0&&(n.maind_connected="connected"),n}var vr,Md,Nb,Pb,Db,Ob,Mb,Fb,yt,Fd=_(()=>{"use strict";br();wr();vr="mcp__maind__",Md="2026-09-09",Nb=/(\brückgängig\b|zurücknehmen|\bnochmal(s)?\b|noch mal|\brevert\b|\bundo\b|\bredo\b|stattdessen|\binstead\b|mach(e)? das (nochmal|neu)|try again)/i,Pb=/(\bnein\b|\bfalsch\b|stimmt nicht|das ist nicht|so nicht|\bnicht so\b|warum hast du|wieso hast du|\bno\b|\bnope\b|\bwrong\b|\bincorrect\b|that'?s not|that is not|\bdon'?t\b|\bdoesn'?t\b|shouldn'?t)/i,Db=/(\bdanke\b|\bperfekt\b|\bsuper\b|\bpasst\b|\bgenau\b|sieht gut|\bcommit\b|\bship\b|\bmerge\b|\bpush\b|looks good|\blgtm\b|\bthanks\b|thank you|\bperfect\b|\bgreat\b|\bexactly\b|\bnice\b|well done|👍|✅|🎉)/i,Ob="[Request interrupted by user",Mb="The user doesn't want to proceed with this tool use",Fb=.7,yt={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(Lb,"bumpModel");s(kr,"asBlocks");s($b,"textOf");s(jb,"isRepeat");s(Hb,"classifyGenuine");s(Ub,"emptyAnalysis");s(Gb,"tallySubagentMaindCalls");s(Po,"analyzeSession")});function Do(e){let t=e!==null&&typeof e=="object"?e:{},n=typeof t.slices_stored=="boolean"?t.slices_stored:null;return{analyticsStored:t.analytics_stored===!0,spanStored:t.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof t.slices_reason=="string"?t.slices_reason:null,slicesCount:typeof t.slices_count=="number"&&Number.isFinite(t.slices_count)?t.slices_count:0}}function Oo(e,t){return!t||e.slicesStored===!0?null:e.slicesStored===null?"cost slices sent, verdict unknown \u2014 the ingest endpoint predates slice verdicts (redeploy mcp-client-metrics-ingest)":`cost slices not stored: ${e.slicesReason??"no reason given"} (${e.slicesCount} sent)`}function Mo(e,t,n,r="unknown",i){let o={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};return t&&t.started_at&&(o.session_span=n?{...t,...n}:t),o}var Ld=_(()=>{"use strict";s(Do,"parseIngestResponse");s(Oo,"describeSliceVerdict");s(Mo,"ingestBody")});import{homedir as Wb}from"node:os";import{join as Kb}from"node:path";var Bb,$d=_(()=>{"use strict";Bb=Kb(Wb(),".codex","sessions")});import{isAbsolute as $o,relative as Vb,resolve as jd,sep as jo}from"node:path";function Hd(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function Sr(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Ho(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=s(a=>{if(!Array.isArray(a))return[];let c=[];for(let l of a){if(!l||typeof l!="object")continue;let p=l,d=Sr(p.from);typeof p.object_id!="string"||!Fo.test(p.object_id)||d===null||c.push({object_id:p.object_id.toLowerCase(),from:d,to:Sr(p.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=Sr(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:Sr(c.to)})}let o=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let c=a;typeof c.object_id!="string"||!Fo.test(c.object_id)||typeof c.path_prefix=="string"&&o.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Fo.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:o}}function Gd(e,t){if(!$o(e))return null;let n=Vb(jd(t),jd(e));return!n||n==="."||n.startsWith("..")||$o(n)?null:jo==="/"?n:n.split(jo).join("/")}function qb(e,t){return t===""||e===t||e.startsWith(t+"/")}function Uo(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Wd(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function Go(e,t){for(let n of Wd(t))if(qb(e,n.path_prefix))return n.object_id;return null}function zb(e,t){for(let n of Wd(t))if(Uo(e,n.path_prefix))return n.object_id;return null}function Lo(e,t){return e>=t.from&&(t.to===null||e<t.to)}function Kd(e,t,n,r){let i=e.ts,o=r?.anchors??[],a=t.map(c=>Go(c,o)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(d=>Lo(i,d));if(c.length)return c.sort((d,u)=>u.from-d.from||d.object_id.localeCompare(u.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(d=>Lo(i,d));if(l.length)return{object_id:(l.find(u=>a.includes(u.object_id))??l.find(u=>n!==null&&u.object_id===n.object_id)??[...l].sort((u,f)=>u.object_id.localeCompare(f.object_id))[0]).object_id,source:"binding"};let p=r.claims.filter(d=>Lo(i,d));if(p.length){let d=t[0]??n?.rel??null,u=(d===null?p:p.filter(f=>Uo(f.path_prefix,d))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of u){let m=zb(f.path_prefix,o);if(m)return{object_id:m,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function Wo(e,t,n){let r=t?.anchors??[],i=s(h=>{if(!n.repoRoot)return[];let g=[];for(let y of h.edited_paths){let b=Gd(y,n.repoRoot);b!==null&&!g.includes(b)&&g.push(b)}return g},"relOf"),o=s(h=>{for(let g of h){let y=Go(g,r);if(y)return{object_id:y,rel:g}}return null},"firstAnchoredEdit"),a=new Map;for(let h of e){let g=a.get(h.stream)??[];g.push(h),a.set(h.stream,g)}let c=[...a.entries()].sort(([h],[g])=>h===Fe?-1:g===Fe?1:0),l=[],p=s(h=>{let g=null;for(let y of l){if(y.ts>h&&h>0)break;g=y.seg}return g},"mainSegmentAt"),d=new Map;for(let[h,g]of c){let y=g.map((w,v)=>({t:w,i:v,rels:i(w)})).sort((w,v)=>w.t.ts-v.t.ts||w.i-v.i),b=null;for(let w of y){let v=o(w.rels);if(v){b=v;break}}!b&&h!==Fe&&y.length&&(b=p(y[0].t.ts));for(let w of y){let v=o(w.rels);v&&(b=v),h===Fe&&l.push({ts:w.t.ts,seg:b});let k=w.t;if(k.input_tokens+k.output_tokens+k.cache_read_tokens+k.cache_creation_tokens===0)continue;let R=Kd(k,w.rels,b,t),I=k.input_tokens+k.cache_read_tokens+k.cache_creation_tokens>Ud?"above_200k":"standard",T=Hd(k.model),D=`${R.object_id??""}|${R.source}|${T}|${I}`,A=d.get(D);A||(A={object_id:R.object_id,attribution_source:R.source,model:T,context_tier:I,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},d.set(D,A)),A.input_tokens+=k.input_tokens,A.output_tokens+=k.output_tokens,A.cache_read_tokens+=k.cache_read_tokens,A.cache_creation_tokens+=k.cache_creation_tokens,A.cache_creation_1h_tokens+=k.cache_creation_1h_tokens,A.turns+=1,k.ts>0&&((A.firstMs===0||k.ts<A.firstMs)&&(A.firstMs=k.ts),k.ts>A.lastMs&&(A.lastMs=k.ts))}}let u=n.nowMs??Date.now(),f=[];for(let h of d.values()){let{firstMs:g,lastMs:y,...b}=h;b.first_ts=new Date(g>0?g:u).toISOString(),b.last_ts=new Date(y>0?y:u).toISOString(),f.push(b)}let m={lease:0,binding:1,claim:2,path:3,none:4};return f.sort((h,g)=>m[h.attribution_source]-m[g.attribution_source]||(h.object_id??"").localeCompare(g.object_id??"")||h.model.localeCompare(g.model)||h.context_tier.localeCompare(g.context_tier)),f}function Ko(e,t){let n=new Map;for(let o of e){let a=new Set;for(let c of o.edited_paths){if(!$o(c))continue;let l=t(Jb(c));l&&a.add(l)}for(let c of a)n.set(c,(n.get(c)??0)+1)}let r=null,i=0;for(let[o,a]of n)(a>i||a===i&&r!==null&&o.length>r.length)&&(r=o,i=a);return r}function Jb(e){let t=e.split(jo).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var Ud,Fo,Bd=_(()=>{"use strict";wr();s(Hd,"normalizeModelId");Ud=2e5,Fo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Sr,"msOf");s(Ho,"parseCostContext");s(Gd,"toRepoRelative");s(qb,"underPrefix");s(Uo,"prefixesOverlap");s(Wd,"sortedAnchors");s(Go,"anchorFor");s(zb,"bestAnchorOverlapping");s(Lo,"inWindow");s(Kd,"assignTurn");s(Wo,"sliceSession");s(Ko,"dominantCheckoutRoot");s(Jb,"dirOf")});import{createReadStream as Yb,existsSync as Xb}from"node:fs";import{createInterface as Qb}from"node:readline";function Vd(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function t_(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
125
+ `)}function Jd(e){return{session_id:e,started_at:null,ended_at:null,wall_seconds:0,agent_seconds:0,wait_seconds:0,pauses:[],pause_count:0,pause_seconds:0,pauses_truncated:!1,turn_count:0,event_count:0}}function n_(e){let t=e.message?.role;if(t==="assistant")return{holder:Vd(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Vd(e.message?.content),r=t_(n);return r.includes(Zb)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(e_))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Bo(e){let t=Jd("");if(!e||!Xb(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(l=>{let p=Yb(e,{encoding:"utf-8"}),d=Qb({input:p}),u=s(f=>{let m=f.trim();if(!m)return;let h;try{h=JSON.parse(m)}catch{return}if(!t.session_id){let b=h.sessionId??h.session_id;typeof b=="string"&&b&&(t.session_id=b)}if(h.isSidechain===!0)return;let g=typeof h.timestamp=="string"?Date.parse(h.timestamp):NaN;if(!Number.isFinite(g)||o!==null&&g<o)return;let y=n_(h);if(y!==null){if(t.event_count++,y.genuine&&t.turn_count++,n===null&&(n=g),r=g,o!==null){let b=g-o;a==="agent"?i+=b:b>=qd*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<zd&&c.push({offset_seconds:Math.round((o-n)/1e3),duration_seconds:Math.round(b/1e3)}))}o=g,a=y.holder}},"processLine");d.on("line",f=>{try{u(f)}catch{}}),d.on("close",()=>l()),d.on("error",()=>l()),p.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var Zb,e_,qd,zd,Yd=_(()=>{"use strict";Zb="[Request interrupted by user",e_="The user doesn't want to proceed with this tool use",qd=60,zd=200;s(Vd,"asBlocks");s(t_,"textOf");s(Jd,"emptySpan");s(n_,"classify");s(Bo,"analyzeSpan")});import{createReadStream as r_,existsSync as i_}from"node:fs";import{createInterface as o_}from"node:readline";function a_(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function Er(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function c_(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=[];for(let n of e)if(n&&typeof n=="object"&&"text"in n){let r=n.text;typeof r=="string"&&t.push(r)}return t.join(`
126
+ `)}return""}async function Vo(e,t={}){if(!e||!i_(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:To(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,o=t.initialModes?{...t.initialModes}:To(),a=t.start??0;return await new Promise(c=>{let l=r_(e,{encoding:"utf-8",start:t.start??0}),p=o_({input:l});p.on("line",u=>{a+=Buffer.byteLength(u,"utf-8")+1;let f=u.trim();if(!f)return;let m;try{m=JSON.parse(f)}catch{return}let h=m.sessionId??m.session_id??"",g=m.timestamp?Date.parse(m.timestamp):Date.now(),y=m.message?.role;if(m.type==="ai-title"&&typeof m.aiTitle=="string"){n.push({kind:"title",session_id:h,ts:g,title:m.aiTitle});return}if(m.type==="attachment"&&m.attachment?.type){let b=s_[m.attachment.type];b&&(o[a_(b.mode)]=b.active,n.push({kind:"mode",session_id:h,ts:g,mode:b.mode,active:b.active}));return}if(y==="user"){let b=c_(m.message?.content),w=en(b);w&&(i=w);let v={session_id:h,ts:g,text:b,effort_directive:w};n.push({kind:"user",...v});return}if(y==="assistant"){let b=m.message?.usage,w=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,v=typeof m.requestId=="string"&&m.requestId?m.requestId:null,k=w??v,E=k!==null&&r.has(k);k!==null&&!E&&r.add(k);let R={session_id:h,ts:g,model:m.message?.model??null,input_tokens:E?0:Er(b?.input_tokens),output_tokens:E?0:Er(b?.output_tokens),cache_read_input_tokens:E?0:Er(b?.cache_read_input_tokens),cache_creation_input_tokens:E?0:Er(b?.cache_creation_input_tokens),effort:i,isSidechain:m.isSidechain===!0,...o.ultracode?{ultracode:!0}:{},...o.planMode?{planMode:!0}:{},...o.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...R})}});let d=s(()=>({events:n,bytesRead:a,effortAtEnd:i,modesAtEnd:{...o},seenMessagesAtEnd:new Set(r)}),"finalResult");p.on("close",()=>c(d())),p.on("error",()=>c(d())),l.on("error",()=>c(d()))})}var s_,Xd=_(()=>{"use strict";br();Io();s_={ultra_effort_enter:{mode:"ultracode",active:!0},ultra_effort_exit:{mode:"ultracode",active:!1},plan_mode:{mode:"plan",active:!0},plan_mode_reentry:{mode:"plan",active:!0},plan_mode_exit:{mode:"plan",active:!1},auto_mode:{mode:"auto",active:!0},auto_mode_exit:{mode:"auto",active:!1}};s(a_,"modeFlagKey");s(Er,"num");s(c_,"extractUserText");s(Vo,"streamTranscript")});var Qd=_(()=>{"use strict"});import{homedir as l_}from"node:os";import{join as d_}from"node:path";function zo(e){return e.replace(/[/.]/g,"-")}var u_,qo,Zd=_(()=>{"use strict";u_=l_(),qo=d_(u_,".claude","projects");s(zo,"projectPathFromCwd")});var bt=_(()=>{"use strict";Io();Td();Id();Fd();Ld();wr();$d();Bd();Yd();Xd();br();Qd();Zd()});async function nu(e){return Le("get_session_briefing",{tools:["claude-code"]},e)}async function Le(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??Jo,i=new AbortController,o=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let a={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n.apiKey}`,"x-maind-client-family":n.clientFamily??"claude-code","x-maind-client-version":n.bridgeVersion,"x-maind-bridge-version":n.bridgeVersion};n.deviceId&&(a["x-maind-device-id"]=n.deviceId),n.projectKey&&(a["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:a,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:w_,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),l=c.headers.get("mcp-session-id");if(await c.text().catch(()=>""),!c.ok||!l)return null;let p={...a,"mcp-session-id":l};await fetch(r,{method:"POST",headers:p,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(g=>g.text().catch(()=>"")).catch(()=>"");let d=await fetch(r,{method:"POST",headers:p,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!d.ok)return null;let f=(d.headers.get("content-type")??"").startsWith("text/event-stream")?await k_(d):await d.text();if(f.trim().length===0)return null;let m=JSON.parse(f);if(m.error||m.result?.isError)return null;let h=m.result?.content?.find(g=>g.type==="text"&&typeof g.text=="string")?.text;return typeof h=="string"&&h.trim().length>0?h:null}catch{return null}finally{clearTimeout(o)}}async function k_(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o="",a=s(()=>{if(i.length===0)return;let c=i.join(`
127
+ `).trim();i=[],c.length>0&&(o=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let p;for(;(p=r.indexOf(`
128
+ `))!==-1;){let d=r.slice(0,p);r=r.slice(p+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){a();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}return a(),o}var Jo,w_,nn=_(()=>{"use strict";Jo="https://mcp.maind.dev/mcp",w_="2025-06-18";s(nu,"fetchSessionBriefing");s(Le,"fetchToolText");s(k_,"readSseMessage")});function v_(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":U()}}async function ru(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:v_(t),body:JSON.stringify({metrics:n})});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:o.slice(0,500)}}return{ok:!0,inserted:(await r.json().catch(()=>null))?.inserted_metrics??n.length,status:r.status}}catch(r){return{ok:!1,inserted:0,error:r instanceof Error?r.message:String(r)}}}var Rr,Yo=_(()=>{"use strict";B();Rr=process.env.MAIND_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";s(v_,"ingestHeaders");s(ru,"postMetrics")});function iu(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function su(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,o=Array.isArray(i.active_claims)?i.active_claims:[],a=[];for(let c of o){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let d=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;d<=0||a.push({path_prefix:l.path_prefix,note:typeof l.note=="string"?l.note:null,remaining_seconds:Math.round(d)})}n.push({session_id_short:typeof i.session_id_short=="string"?i.session_id_short:"?",is_own_user:i.is_own_user===!0,branch:typeof i.branch=="string"?i.branch:null,focus:typeof i.focus=="string"?i.focus:null,machine_label:typeof i.machine_label=="string"?i.machine_label:null,last_seen_seconds:typeof i.last_seen_seconds=="number"?i.last_seen_seconds:0,claims:a,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function _t(e,t){if(t.hostPids.length>0){let r=e.find(i=>t.hostPids.includes(i.own_ppid));if(r)return{snap:r,via:"ppid"}}let n=e.find(r=>r.cwd===t.cwd);return n?{snap:n,via:"cwd"}:null}function rn(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function au(e,t,n){let r=n.maxAgeMs??ou,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,a=su(e,o),c=[];for(let l of a)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let p of l.claims)iu(t,p.path_prefix)&&c.push(`'${p.path_prefix}' is CLAIMED by peer session ${l.session_id_short}${l.branch?` (branch ${l.branch}`:" ("}${l.machine_label?`, ${l.machine_label}`:""}${l.focus?`, focus: "${l.focus}"`:""}, last seen ${rn(l.last_seen_seconds+o)} ago)${p.note?` \u2014 note: "${p.note}"`:""}, claim expires in ${rn(p.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let p of l.working_paths)if(iu(t,p)){c.push(`'${p}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${rn(l.last_seen_seconds+o)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${rn(o)} ago, advisory \u2014 never a lock):
129
129
  `+c.map(l=>` \u2022 ${l}`).join(`
130
130
  `)+`
131
- Verify live before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: ["${t}"]}) \u2014 then claim_paths for your own edit area.`}function ru(e,t,n,r=eu,i=null){if(!e)return null;let o=n-Date.parse(e.written_at);if(!Number.isFinite(o)||o<0||o>r)return null;let a=o/1e3,c=tu(e,a),l=i!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${i}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let u=c.reduce((h,g)=>h+g.claims.length,0),d=c.filter(h=>h.focus===null&&h.working_paths.length===0&&h.claims.length===0).length,p=u>0?`${u} active claim${u===1?"":"s"}`:"no active claims",m=d>0?`, ${d} presence-only`:"",f=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${m}) as of ${rn(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
132
- ${f}`:f}var eu,qo=_(()=>{"use strict";s(Zd,"prefixConflict");eu=10*6e4;s(tu,"parsePeers");s(_t,"selectOwnSnapshot");s(rn,"ageDisplay");s(nu,"adviseOnPath");s(ru,"sessionStartSummary")});async function C(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=s(o=>{n||(n=!0,clearTimeout(i),t(o))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",o=>e.push(o)),process.stdin.on("end",()=>{try{let o=Buffer.concat(e).toString("utf-8").trim();r(o?JSON.parse(o):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function on(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function ie(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var oe=_(()=>{"use strict";s(C,"readHookInput");s(on,"transcriptPathOf");s(ie,"toolFilePathOf")});function wt(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function ve(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function iu(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}var kt=_(()=>{"use strict";s(wt,"denyPayload");s(ve,"advisoryPayload");s(iu,"postAdvisoryPayload")});import{realpathSync as f_}from"node:fs";import{basename as ou,dirname as su,join as m_}from"node:path";function $e(e){let t=su(e),n=[ou(e)];for(;;)try{let r=f_(t);return m_(r,...n.reverse())}catch{let r=su(t);if(r===t)return e;n.push(ou(t)),t=r}}var Ar=_(()=>{"use strict";s($e,"realpathOfUnwritten")});import{mkdir as h_,readFile as g_,writeFile as y_,rename as b_}from"node:fs/promises";import{existsSync as cu}from"node:fs";import{homedir as __}from"node:os";import{join as lu}from"node:path";function au(){return{config:null,sessions:{},pending_metrics:[]}}async function $(){if(!cu(Tr))return au();try{let e=await g_(Tr,"utf-8"),t=JSON.parse(e);return{config:t.config??null,sessions:t.sessions??{},pending_metrics:Array.isArray(t.pending_metrics)?t.pending_metrics:[],thresholds:t.thresholds,thresholds_synced_at:t.thresholds_synced_at,guard_signals:t.guard_signals,repo_health_seen:t.repo_health_seen,write_health_seen:t.write_health_seen}}catch(e){return process.stderr.write(`[maind-mcp-bridge] state.json corrupt, resetting: ${e instanceof Error?e.message:String(e)}
133
- `),au()}}async function se(e){cu(je)||await h_(je,{recursive:!0,mode:448});let t=`${Tr}.tmp`;await y_(t,JSON.stringify(e,null,2),{mode:384}),await b_(t,Tr)}function zo(e){return e.thresholds??e.config?.thresholds??w_}var je,Tr,w_,He=_(()=>{"use strict";je=lu(__(),".maind"),Tr=lu(je,"state.json"),w_={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(au,"emptyState");s($,"loadState");s(se,"saveState");s(zo,"resolveThresholds")});import{existsSync as k_,realpathSync as v_,statSync as S_}from"node:fs";import{dirname as du,isAbsolute as E_,join as x_}from"node:path";function T_(e,t){let n=e.filter(i=>uu.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let o=i.hint?`
131
+ Verify live before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: ["${t}"]}) \u2014 then claim_paths for your own edit area.`}function cu(e,t,n,r=ou,i=null){if(!e)return null;let o=n-Date.parse(e.written_at);if(!Number.isFinite(o)||o<0||o>r)return null;let a=o/1e3,c=su(e,a),l=i!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${i}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let p=c.reduce((h,g)=>h+g.claims.length,0),d=c.filter(h=>h.focus===null&&h.working_paths.length===0&&h.claims.length===0).length,u=p>0?`${p} active claim${p===1?"":"s"}`:"no active claims",f=d>0?`, ${d} presence-only`:"",m=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${u}${f}) as of ${rn(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
132
+ ${m}`:m}var ou,Xo=_(()=>{"use strict";s(iu,"prefixConflict");ou=10*6e4;s(su,"parsePeers");s(_t,"selectOwnSnapshot");s(rn,"ageDisplay");s(au,"adviseOnPath");s(cu,"sessionStartSummary")});async function C(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=s(o=>{n||(n=!0,clearTimeout(i),t(o))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",o=>e.push(o)),process.stdin.on("end",()=>{try{let o=Buffer.concat(e).toString("utf-8").trim();r(o?JSON.parse(o):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function on(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function ie(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var oe=_(()=>{"use strict";s(C,"readHookInput");s(on,"transcriptPathOf");s(ie,"toolFilePathOf")});function wt(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function ve(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function lu(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}var kt=_(()=>{"use strict";s(wt,"denyPayload");s(ve,"advisoryPayload");s(lu,"postAdvisoryPayload")});import{realpathSync as S_}from"node:fs";import{basename as du,dirname as uu,join as E_}from"node:path";function $e(e){let t=uu(e),n=[du(e)];for(;;)try{let r=S_(t);return E_(r,...n.reverse())}catch{let r=uu(t);if(r===t)return e;n.push(du(t)),t=r}}var Ar=_(()=>{"use strict";s($e,"realpathOfUnwritten")});import{mkdir as x_,readFile as R_,writeFile as A_,rename as T_}from"node:fs/promises";import{existsSync as fu}from"node:fs";import{homedir as I_}from"node:os";import{join as mu}from"node:path";function pu(){return{config:null,sessions:{},pending_metrics:[]}}async function j(){if(!fu(Tr))return pu();try{let e=await R_(Tr,"utf-8"),t=JSON.parse(e);return{config:t.config??null,sessions:t.sessions??{},pending_metrics:Array.isArray(t.pending_metrics)?t.pending_metrics:[],thresholds:t.thresholds,thresholds_synced_at:t.thresholds_synced_at,guard_signals:t.guard_signals,repo_health_seen:t.repo_health_seen,write_health_seen:t.write_health_seen}}catch(e){return process.stderr.write(`[maind-mcp-bridge] state.json corrupt, resetting: ${e instanceof Error?e.message:String(e)}
133
+ `),pu()}}async function se(e){fu(je)||await x_(je,{recursive:!0,mode:448});let t=`${Tr}.tmp`;await A_(t,JSON.stringify(e,null,2),{mode:384}),await T_(t,Tr)}function Qo(e){return e.thresholds??e.config?.thresholds??C_}var je,Tr,C_,He=_(()=>{"use strict";je=mu(I_(),".maind"),Tr=mu(je,"state.json"),C_={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(pu,"emptyState");s(j,"loadState");s(se,"saveState");s(Qo,"resolveThresholds")});import{existsSync as N_,realpathSync as P_,statSync as D_}from"node:fs";import{dirname as hu,isAbsolute as O_,join as M_}from"node:path";function $_(e,t){let n=e.filter(i=>gu.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let o=i.hint?`
134
134
  \u2192 ${i.hint}`:"";return` \u2022 ${i.title}
135
135
  ${i.detail}${o}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
136
136
 
@@ -138,40 +138,40 @@ ${f}`:f}var eu,qo=_(()=>{"use strict";s(Zd,"prefixConflict");eu=10*6e4;s(tu,"par
138
138
 
139
139
  `)+`
140
140
 
141
- This is advisory; nothing is blocked. Resolve it before running build/test commands in this tree \u2014 otherwise the failure arrives later, disguised as your own change.`}function I_(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function C_(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},o=i[t]??{};o[n]=new Date(r).toISOString(),i[t]=o,e.repo_health_seen=i}function Jo(e){let t=du(e);for(;;){try{if(S_(t).isDirectory())return t}catch{}let n=du(t);if(n===t)return t;t=n}}async function N_(e,t,n){let r=await n.load();if(I_(r,e,t))return null;C_(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let o=i.filter(c=>uu.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:R_,metric_value:1},{session_id:e,metric_key:A_,metric_value:o}),await n.save(a),T_(i,t)}async function pu(){try{let e=await C(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"";if(!n)return 0;let r=ie(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=E_(r)?r:x_(i,r),a=k_(o)?v_(o):$e(o),c=ae(Jo(a)),l=await N_(n,c,{load:$,save:se,check:s(async u=>(await $t(u,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(ve(l)),0}catch{return 0}}var uu,R_,A_,Yo=_(()=>{"use strict";Qt();qe();kt();oe();Ar();He();uu=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],R_="repo_health_hook_runs",A_="repo_health_hook_findings";s(T_,"formatRepoHealth");s(I_,"alreadySeen");s(C_,"markSeen");s(Jo,"nearestExistingDir");s(N_,"repoHealthForEdit");s(pu,"runOnRepoHealth")});import{existsSync as P_,readFileSync as D_,realpathSync as O_}from"node:fs";import{isAbsolute as mu,join as hu,posix as M_,relative as F_,sep as L_}from"node:path";function fu(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function G_(e,t){return{contracts:t.filter(r=>fu(r.spec)===e||fu(r.impl)===e).map(r=>r.id),theme:H_.test(e),acl:U_.test(e)}}function W_(e){return e.contracts.length===0&&!e.theme&&!e.acl}function K_(e,t,n,r,i=Date.now()){let o=e.write_health_seen??{},a=o[t]??{},c=new Set(a[n]?.keys??[]),l=r.filter(u=>!c.has(u.key));if(l.length>0){for(let u of l)c.add(u.key);a[n]={at:new Date(i).toISOString(),keys:[...c]},o[t]=a,e.write_health_seen=o}return l}function B_(e,t){return e.length===0?null:`maind write-health \u2014 your edit to ${t} makes these checks relevant, and each finding below is reported once per session:
141
+ This is advisory; nothing is blocked. Resolve it before running build/test commands in this tree \u2014 otherwise the failure arrives later, disguised as your own change.`}function j_(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function H_(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},o=i[t]??{};o[n]=new Date(r).toISOString(),i[t]=o,e.repo_health_seen=i}function Zo(e){let t=hu(e);for(;;){try{if(D_(t).isDirectory())return t}catch{}let n=hu(t);if(n===t)return t;t=n}}async function U_(e,t,n){let r=await n.load();if(j_(r,e,t))return null;H_(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let o=i.filter(c=>gu.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:F_,metric_value:1},{session_id:e,metric_key:L_,metric_value:o}),await n.save(a),$_(i,t)}async function yu(){try{let e=await C(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"";if(!n)return 0;let r=ie(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=O_(r)?r:M_(i,r),a=N_(o)?P_(o):$e(o),c=ae(Zo(a)),l=await U_(n,c,{load:j,save:se,check:s(async p=>(await $t(p,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(ve(l)),0}catch{return 0}}var gu,F_,L_,es=_(()=>{"use strict";Qt();qe();kt();oe();Ar();He();gu=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],F_="repo_health_hook_runs",L_="repo_health_hook_findings";s($_,"formatRepoHealth");s(j_,"alreadySeen");s(H_,"markSeen");s(Zo,"nearestExistingDir");s(U_,"repoHealthForEdit");s(yu,"runOnRepoHealth")});import{existsSync as G_,readFileSync as W_,realpathSync as K_}from"node:fs";import{isAbsolute as _u,join as wu,posix as B_,relative as V_,sep as q_}from"node:path";function bu(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function Q_(e,t){return{contracts:t.filter(r=>bu(r.spec)===e||bu(r.impl)===e).map(r=>r.id),theme:Y_.test(e),acl:X_.test(e)}}function Z_(e){return e.contracts.length===0&&!e.theme&&!e.acl}function ew(e,t,n,r,i=Date.now()){let o=e.write_health_seen??{},a=o[t]??{},c=new Set(a[n]?.keys??[]),l=r.filter(p=>!c.has(p.key));if(l.length>0){for(let p of l)c.add(p.key);a[n]={at:new Date(i).toISOString(),keys:[...c]},o[t]=a,e.write_health_seen=o}return l}function tw(e,t){return e.length===0?null:`maind write-health \u2014 your edit to ${t} makes these checks relevant, and each finding below is reported once per session:
142
142
 
143
143
  `+e.map(n=>` \u2022 ${n.line}`).join(`
144
144
  `)+`
145
145
 
146
- Advisory; nothing is blocked. These are findings THIS branch introduces (pre-existing ones are graded out) \u2014 fix them now, or they surface at the gate.`}function V_(e,t){let n=F_(e,t);return!n||n.startsWith("..")||mu(n)?null:n.split(L_).join(M_.sep)}function q_(e){try{let t=D_(hu(e,qn),"utf8"),{manifest:n}=Xn(t);return n?.contracts??[]}catch{return[]}}async function gu(){try{let e=await C(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=ie(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=mu(r)?r:hu(i,r),a=P_(o)?O_(o):$e(o),c=ae(Jo(a)),l=V_(c,a);if(l===null)return 0;let u=G_(l,q_(c));if(W_(u))return 0;let d=[];if(u.contracts.length>0)try{let h=await Ne(c,{contracts:u.contracts});for(let g of h.findings)g.status==="open"&&d.push({key:`spec:${g.id}`,line:`spec-drift (${g.contract}): ${g.detail}`})}catch{}if(u.theme)try{let h=De(c);for(let g of h.findings)g.status==="open"&&d.push({key:`theme:${g.file}:${g.klass}`,line:`theme-class-drift: \`${g.klass}\` in ${g.file} \u2014 no token \`--color-${g.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(u.acl)try{let h=Pe(c);for(let g of h.findings)g.status==="open"&&d.push({key:`acl:${g.id}`,line:`table-acl-lint: \`${g.table}\` (created in ${g.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let p=await $(),m=K_(p,n,c,d);p.pending_metrics.push({session_id:n,metric_key:$_,metric_value:1},{session_id:n,metric_key:j_,metric_value:m.length}),await se(p);let f=B_(m,l);return f!==null&&process.stdout.write(iu(f)),0}catch{return 0}}var $_,j_,H_,U_,yu=_(()=>{"use strict";Qt();qe();kt();oe();Yo();Ar();He();$_="write_health_hook_runs",j_="write_health_hook_findings",H_=/\.(tsx?|jsx?|css)$/,U_=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(fu,"declPath");s(G_,"routesForPath");s(W_,"routesAreEmpty");s(K_,"takeUnreported");s(B_,"formatWriteHealth");s(V_,"repoRelative");s(q_,"readContracts");s(gu,"runOnWriteHealth")});var Iu={};q(Iu,{agentHostPidCandidates:()=>me,closeTrackedSession:()=>Eu,effectiveConfig:()=>Ue,grandparentPid:()=>Ru,recordGuardSignals:()=>Su,runFlush:()=>lw,runHookStatus:()=>dw,runOnFileEdit:()=>sw,runOnFileWrite:()=>ow,runOnRepoHealth:()=>pu,runOnSessionStart:()=>ew,runOnToolUse:()=>rw,runOnWriteHealth:()=>gu,runSessionEndMetrics:()=>Qo,runSyncConfig:()=>pw,writeIdentitySideChannel:()=>Xo});import{execFileSync as _u}from"node:child_process";import{existsSync as Nr,readFileSync as wu,realpathSync as z_}from"node:fs";import{writeFile as J_}from"node:fs/promises";import{homedir as ku}from"node:os";import{isAbsolute as Cr,join as sn,relative as vu}from"node:path";function Su(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=n.includes("search_lessons")||n.includes("get_session_briefing")||n.includes("get_lesson")||n.includes("get_conventions")||n.includes("activate_skill")||n.includes("suggest_skills")||n.includes("codebase_change_briefing"),o=n.includes("review_changes");if(!i&&!o)return;let a=e.guard_signals??{},c=a[t]??{},l=new Date(r).toISOString();i&&(c.consulted_at=l),o&&(c.reviewed_at=l),a[t]=c,e.guard_signals=a}function Eu(e,t,n=Date.now()){Z_(e,n);let r=e.sessions[t];if(!r)return!1;let i=n-new Date(r.started_at).getTime();return e.pending_metrics.push({session_id:t,metric_key:"session_duration_ms",metric_value:Math.max(0,i)},{session_id:t,metric_key:"tool_call_count",metric_value:r.tool_call_count},{session_id:t,metric_key:"lessons_consulted",metric_value:r.lessons_consulted}),delete e.sessions[t],!0}function Z_(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let i=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0);t-i>Ir&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(o=>Date.parse(o)||0));t-i>Ir&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let i=Math.max(0,...Object.values(r).map(o=>Date.parse(o.at)||0));t-i>Ir&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let i=Date.parse(r.started_at);!Number.isNaN(i)&&t-i>Ir&&delete e.sessions[n]}}function Ue(e){if(e.config)return e.config;let t=D();return t===null?null:{api_key:t,endpoint:Rr}}function xu(e,t){let n=e.sessions[t];return n||(n={session_id:t,started_at:new Date().toISOString(),tool_call_count:0,lessons_consulted:0},e.sessions[t]=n),n}async function ew(){let e=await $();if(Ue(e)===null)return 0;let t=await C(),n=Tu(t);if(n===null)return 0;xu(e,n),await se(e);try{Xo(t,n)}catch{}try{let r=O();if(r!==null){let i=mt(r),o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=_t(i,{hostPids:me(),cwd:o}),c=ru(a?.snap??i[0]??null,a?.snap.own_session_id??null,Date.now(),void 0,a?.snap.announce_error??null);c!==null&&process.stdout.write(c+`
147
- `)}}catch{}try{let r=Dt(tw());if(Zr(r)&&An(r)){let i=r.filter(o=>o.remedy==="run-install").map(o=>o.subcommand).join(", ");process.stderr.write(`[maind] New bridge capability not yet wired (${i}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
148
- `)}}catch{}return 0}function tw(){try{let e=sn(ku(),".claude","settings.json");return Nr(e)?wu(e,"utf8"):null}catch{return null}}function Xo(e,t,n,r=ht()){let i=n??me();if(i.length===0)return;let o=bd(on(e)||null,t);if(o===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=on(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let u of i)_d({dir:r,agentPid:u,sessionId:t,transcriptStem:o,cwd:a,transcriptPath:c,model:l})}function Ru(){try{if(process.platform==="win32")return null;let e=_u("ps",["-o","ppid=","-p",String(process.ppid)],{timeout:1e3,encoding:"utf8"}),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function me(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=Ru();return n!==null&&n>1&&n!==t&&e.push(n),e}async function rw(){let e=await $();if(Ue(e)===null)return 0;let t=await C(),n=Tu(t)??"unknown",r=xu(e,n);r.tool_call_count+=1;try{let a=me().filter(c=>wd(ht(),c,nw));n!=="unknown"&&a.length>0&&Xo(t,n,a)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),Su(e,n,i);let o=t.transcript_path;if(typeof o=="string"&&o&&!r.transcript_path&&(r.transcript_path=o),r.transcript_path){let a=await Io(r.transcript_path);a&&(r.token_count=a.total_tokens,await cw(e,r))}return await se(e),0}function iw(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
146
+ Advisory; nothing is blocked. These are findings THIS branch introduces (pre-existing ones are graded out) \u2014 fix them now, or they surface at the gate.`}function nw(e,t){let n=V_(e,t);return!n||n.startsWith("..")||_u(n)?null:n.split(q_).join(B_.sep)}function rw(e){try{let t=W_(wu(e,qn),"utf8"),{manifest:n}=Xn(t);return n?.contracts??[]}catch{return[]}}async function ku(){try{let e=await C(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=ie(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=_u(r)?r:wu(i,r),a=G_(o)?K_(o):$e(o),c=ae(Zo(a)),l=nw(c,a);if(l===null)return 0;let p=Q_(l,rw(c));if(Z_(p))return 0;let d=[];if(p.contracts.length>0)try{let h=await Ne(c,{contracts:p.contracts});for(let g of h.findings)g.status==="open"&&d.push({key:`spec:${g.id}`,line:`spec-drift (${g.contract}): ${g.detail}`})}catch{}if(p.theme)try{let h=De(c);for(let g of h.findings)g.status==="open"&&d.push({key:`theme:${g.file}:${g.klass}`,line:`theme-class-drift: \`${g.klass}\` in ${g.file} \u2014 no token \`--color-${g.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(p.acl)try{let h=Pe(c);for(let g of h.findings)g.status==="open"&&d.push({key:`acl:${g.id}`,line:`table-acl-lint: \`${g.table}\` (created in ${g.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let u=await j(),f=ew(u,n,c,d);u.pending_metrics.push({session_id:n,metric_key:z_,metric_value:1},{session_id:n,metric_key:J_,metric_value:f.length}),await se(u);let m=tw(f,l);return m!==null&&process.stdout.write(lu(m)),0}catch{return 0}}var z_,J_,Y_,X_,vu=_(()=>{"use strict";Qt();qe();kt();oe();es();Ar();He();z_="write_health_hook_runs",J_="write_health_hook_findings",Y_=/\.(tsx?|jsx?|css)$/,X_=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(bu,"declPath");s(Q_,"routesForPath");s(Z_,"routesAreEmpty");s(ew,"takeUnreported");s(tw,"formatWriteHealth");s(nw,"repoRelative");s(rw,"readContracts");s(ku,"runOnWriteHealth")});var Ou={};q(Ou,{agentHostPidCandidates:()=>me,closeTrackedSession:()=>Iu,effectiveConfig:()=>Ue,grandparentPid:()=>Nu,recordGuardSignals:()=>Tu,runFlush:()=>_w,runHookStatus:()=>ww,runOnFileEdit:()=>gw,runOnFileWrite:()=>hw,runOnRepoHealth:()=>yu,runOnSessionStart:()=>dw,runOnToolUse:()=>fw,runOnWriteHealth:()=>ku,runSessionEndMetrics:()=>ns,runSyncConfig:()=>vw,writeIdentitySideChannel:()=>ts});import{execFileSync as Eu}from"node:child_process";import{existsSync as Nr,readFileSync as xu,realpathSync as iw}from"node:fs";import{writeFile as ow}from"node:fs/promises";import{homedir as Ru}from"node:os";import{isAbsolute as Cr,join as sn,relative as Au}from"node:path";function Tu(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=n.includes("search_lessons")||n.includes("get_session_briefing")||n.includes("get_lesson")||n.includes("get_conventions")||n.includes("activate_skill")||n.includes("suggest_skills")||n.includes("codebase_change_briefing"),o=n.includes("review_changes");if(!i&&!o)return;let a=e.guard_signals??{},c=a[t]??{},l=new Date(r).toISOString();i&&(c.consulted_at=l),o&&(c.reviewed_at=l),a[t]=c,e.guard_signals=a}function Iu(e,t,n=Date.now()){lw(e,n);let r=e.sessions[t];if(!r)return!1;let i=n-new Date(r.started_at).getTime();return e.pending_metrics.push({session_id:t,metric_key:"session_duration_ms",metric_value:Math.max(0,i)},{session_id:t,metric_key:"tool_call_count",metric_value:r.tool_call_count},{session_id:t,metric_key:"lessons_consulted",metric_value:r.lessons_consulted}),delete e.sessions[t],!0}function lw(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let i=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0);t-i>Ir&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(o=>Date.parse(o)||0));t-i>Ir&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let i=Math.max(0,...Object.values(r).map(o=>Date.parse(o.at)||0));t-i>Ir&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let i=Date.parse(r.started_at);!Number.isNaN(i)&&t-i>Ir&&delete e.sessions[n]}}function Ue(e){if(e.config)return e.config;let t=O();return t===null?null:{api_key:t,endpoint:Rr}}function Cu(e,t){let n=e.sessions[t];return n||(n={session_id:t,started_at:new Date().toISOString(),tool_call_count:0,lessons_consulted:0},e.sessions[t]=n),n}async function dw(){let e=await j();if(Ue(e)===null)return 0;let t=await C(),n=Du(t);if(n===null)return 0;Cu(e,n),await se(e);try{ts(t,n)}catch{}try{let r=M();if(r!==null){let i=mt(r),o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=_t(i,{hostPids:me(),cwd:o}),c=cu(a?.snap??i[0]??null,a?.snap.own_session_id??null,Date.now(),void 0,a?.snap.announce_error??null);c!==null&&process.stdout.write(c+`
147
+ `)}}catch{}try{let r=Dt(uw());if(ei(r)&&An(r)){let i=r.filter(o=>o.remedy==="run-install").map(o=>o.subcommand).join(", ");process.stderr.write(`[maind] New bridge capability not yet wired (${i}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
148
+ `)}}catch{}return 0}function uw(){try{let e=sn(Ru(),".claude","settings.json");return Nr(e)?xu(e,"utf8"):null}catch{return null}}function ts(e,t,n,r=ht()){let i=n??me();if(i.length===0)return;let o=Sd(on(e)||null,t);if(o===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=on(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let p of i)Ed({dir:r,agentPid:p,sessionId:t,transcriptStem:o,cwd:a,transcriptPath:c,model:l})}function Nu(){try{if(process.platform==="win32")return null;let e=Eu("ps",["-o","ppid=","-p",String(process.ppid)],{timeout:1e3,encoding:"utf8"}),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function me(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=Nu();return n!==null&&n>1&&n!==t&&e.push(n),e}async function fw(){let e=await j();if(Ue(e)===null)return 0;let t=await C(),n=Du(t)??"unknown",r=Cu(e,n);r.tool_call_count+=1;try{let a=me().filter(c=>xd(ht(),c,pw));n!=="unknown"&&a.length>0&&ts(t,n,a)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),Tu(e,n,i);let o=t.transcript_path;if(typeof o=="string"&&o&&!r.transcript_path&&(r.transcript_path=o),r.transcript_path){let a=await Co(r.transcript_path);a&&(r.token_count=a.total_tokens,await bw(e,r))}return await se(e),0}function mw(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
149
149
  `);return`${t.prefix}${e.number} is already taken:
150
150
  ${n}
151
151
 
152
152
  Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
153
153
 
154
- Renumbering later is not the same cost: once the index entry, the links and the commit message name the number, every one of them has to be rewritten.`}async function ow(){try{let e=await C();if((e.tool_name??"")!=="Write")return 0;let t=ie(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=Cr(t)?t:sn(n,t);if(Nr(r))return 0;let i=ae(n),o=vu(i,$e(r));if(o.length===0||o.startsWith("..")||Cr(o))return 0;let a=await Ce(i,o);return!a.taken||a.namespace===null||process.stdout.write(wt(iw(a,a.namespace))),0}catch{return 0}}async function sw(){try{let e=await C(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=ie(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=Cr(n)?n:sn(r,n),o=O();if(o===null)return 0;let a=mt(o);if(a.length===0)return 0;let c=_t(a,{hostPids:me(),cwd:r});if(c===null)return 0;let l=ae(r),u=Nr(i)?z_(i):$e(i),d=vu(l,u).replace(/\\/g,"/");if(d.length===0||d.startsWith("..")||Cr(d))return 0;let p=nu(c.snap,d,{via:c.via,currentBranch:c.via==="cwd"?aw(r):null,nowMs:Date.now()});return p===null||process.stdout.write(ve(p)),0}catch{return 0}}function aw(e){try{let n=_u("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,timeout:1e3,encoding:"utf8"}).trim();return n.length>0&&n!=="HEAD"?n:null}catch{return null}}async function cw(e,t){let n=zo(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,o="ok";if(i>=n.handoff_at_pct/100?o="handoff_recommended":i>=n.warn_at_pct/100&&(o="warn"),t.last_advisory_status===o||(t.last_advisory_status=o,o==="ok"))return;let a=Math.round(i*100),c={session_id:t.session_id,status:o,tokens:r,ratio:Number(i.toFixed(3)),pct:a,thresholds:n,suggested_next:o==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await J_(sn(je,`handoff_advisory_${t.session_id}.json`),JSON.stringify(c,null,2))}catch(l){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${l instanceof Error?l.message:String(l)}
154
+ Renumbering later is not the same cost: once the index entry, the links and the commit message name the number, every one of them has to be rewritten.`}async function hw(){try{let e=await C();if((e.tool_name??"")!=="Write")return 0;let t=ie(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=Cr(t)?t:sn(n,t);if(Nr(r))return 0;let i=ae(n),o=Au(i,$e(r));if(o.length===0||o.startsWith("..")||Cr(o))return 0;let a=await Ce(i,o);return!a.taken||a.namespace===null||process.stdout.write(wt(mw(a,a.namespace))),0}catch{return 0}}async function gw(){try{let e=await C(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=ie(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=Cr(n)?n:sn(r,n),o=M();if(o===null)return 0;let a=mt(o);if(a.length===0)return 0;let c=_t(a,{hostPids:me(),cwd:r});if(c===null)return 0;let l=ae(r),p=Nr(i)?iw(i):$e(i),d=Au(l,p).replace(/\\/g,"/");if(d.length===0||d.startsWith("..")||Cr(d))return 0;let u=au(c.snap,d,{via:c.via,currentBranch:c.via==="cwd"?yw(r):null,nowMs:Date.now()});return u===null||process.stdout.write(ve(u)),0}catch{return 0}}function yw(e){try{let n=Eu("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,timeout:1e3,encoding:"utf8"}).trim();return n.length>0&&n!=="HEAD"?n:null}catch{return null}}async function bw(e,t){let n=Qo(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,o="ok";if(i>=n.handoff_at_pct/100?o="handoff_recommended":i>=n.warn_at_pct/100&&(o="warn"),t.last_advisory_status===o||(t.last_advisory_status=o,o==="ok"))return;let a=Math.round(i*100),c={session_id:t.session_id,status:o,tokens:r,ratio:Number(i.toFixed(3)),pct:a,thresholds:n,suggested_next:o==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await ow(sn(je,`handoff_advisory_${t.session_id}.json`),JSON.stringify(c,null,2))}catch(l){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${l instanceof Error?l.message:String(l)}
155
155
  `)}o==="warn"?process.stderr.write(`[maind] \u26A0 Token usage at ~${a}% (warn threshold ${n.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
156
156
  `):process.stderr.write(`[maind] \u26D4 Token usage at ~${a}% (handoff threshold ${n.handoff_at_pct}%). Strongly consider compiling a HANDOFF brief and starting a fresh session \u2014 call recommend_handoff or generate_handoff_brief.
157
- `)}async function Qo(e){try{let t=await $(),n=Ue(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Eu(t,r),await se(t)),await Au(n,X_)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
158
- `)}}async function lw(){let e=await $(),t=Ue(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=await Au(t,Q_);return process.stdout.write(JSON.stringify(n,null,2)+`
159
- `),n.ok?0:1}async function Au(e,t){let n=await $();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=Qd(e.endpoint,e.api_key,r),o=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([i,o]);if(a.ok){let c=await $();return c.pending_metrics=c.pending_metrics.slice(r.length),await se(c),{ok:!0,flushed:r.length,remaining:c.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:a.error}}async function dw(){let e=await $(),t=Ue(e),n=uw(),r=Zr(n.findings);if(process.stdout.write(JSON.stringify({paired:t!==null,source:e.config?"maind-hook init (legacy)":"bridge credential",endpoint:t?.endpoint??null,api_key_prefix:t?t.api_key.slice(0,12)+"\u2026":null,open_sessions:Object.keys(e.sessions).length,pending_metrics:e.pending_metrics.length,thresholds:zo(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!r,hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...An(n.findings)?{remedy:bu}:{}}},null,2)+`
157
+ `)}async function ns(e){try{let t=await j(),n=Ue(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Iu(t,r),await se(t)),await Pu(n,aw)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
158
+ `)}}async function _w(){let e=await j(),t=Ue(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=await Pu(t,cw);return process.stdout.write(JSON.stringify(n,null,2)+`
159
+ `),n.ok?0:1}async function Pu(e,t){let n=await j();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=ru(e.endpoint,e.api_key,r),o=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([i,o]);if(a.ok){let c=await j();return c.pending_metrics=c.pending_metrics.slice(r.length),await se(c),{ok:!0,flushed:r.length,remaining:c.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:a.error}}async function ww(){let e=await j(),t=Ue(e),n=kw(),r=ei(n.findings);if(process.stdout.write(JSON.stringify({paired:t!==null,source:e.config?"maind-hook init (legacy)":"bridge credential",endpoint:t?.endpoint??null,api_key_prefix:t?t.api_key.slice(0,12)+"\u2026":null,open_sessions:Object.keys(e.sessions).length,pending_metrics:e.pending_metrics.length,thresholds:Qo(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!r,hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...An(n.findings)?{remedy:Su}:{}}},null,2)+`
160
160
  `),r){process.stderr.write(`
161
161
  [maind] Claude Code hook wiring is incomplete:
162
162
  `);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
163
- `);An(n.findings)&&process.stderr.write(` ${bu}
164
- `)}return 0}function uw(){let e=sn(ku(),".claude","settings.json"),t=null;try{Nr(e)&&(t=wu(e,"utf8"))}catch{}return{settingsPath:e,findings:Dt(t)}}async function pw(){let e=await $(),t=Ue(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=t.thresholds_endpoint??Y_,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(a){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${a instanceof Error?a.message:String(a)}
163
+ `);An(n.findings)&&process.stderr.write(` ${Su}
164
+ `)}return 0}function kw(){let e=sn(Ru(),".claude","settings.json"),t=null;try{Nr(e)&&(t=xu(e,"utf8"))}catch{}return{settingsPath:e,findings:Dt(t)}}async function vw(){let e=await j(),t=Ue(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=t.thresholds_endpoint??sw,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(a){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${a instanceof Error?a.message:String(a)}
165
165
  `),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
166
166
  `);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
167
167
  `),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
168
168
  `),1}let o=i;return typeof o.warn_at_pct!="number"||typeof o.handoff_at_pct!="number"||typeof o.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
169
169
  `),1):(e.thresholds={warn_at_pct:o.warn_at_pct,handoff_at_pct:o.handoff_at_pct,model_token_limit:o.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await se(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
170
- `),0)}function Tu(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var Y_,X_,Q_,Ir,nw,bu,Zo=_(()=>{"use strict";bt();Qt();qe();B();Ot();hr();ge();Vo();qo();yr();oe();kt();Ar();He();Yo();yu();Y_=process.env.MAIND_THRESHOLDS_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds",X_=1500,Q_=1e4,Ir=7*24*60*60*1e3;s(Su,"recordGuardSignals");s(Eu,"closeTrackedSession");s(Z_,"gcState");s(Ue,"effectiveConfig");s(xu,"getOrCreateSession");s(ew,"runOnSessionStart");s(tw,"readSettingsRaw");s(Xo,"writeIdentitySideChannel");nw=6e4;s(Ru,"grandparentPid");s(me,"agentHostPidCandidates");s(rw,"runOnToolUse");s(iw,"denyReason");s(ow,"runOnFileWrite");s(sw,"runOnFileEdit");s(aw,"currentGitBranch");s(cw,"maybeEmitAdvisory");s(Qo,"runSessionEndMetrics");s(lw,"runFlush");s(Au,"flushPending");s(dw,"runHookStatus");bu="Re-run `maind-mcp-bridge install` to add the missing hooks \u2014 it is append-only and idempotent: it adds only what is absent, asks consent per hook, and never rewrites an entry you already have.";s(uw,"readHookWiring");s(pw,"runSyncConfig");s(Tu,"sessionIdOf")});function Cu(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Nu=_(()=>{"use strict";s(Cu,"resolveConnection")});function Du(e,t,n,r=Date.now()){let i=t===null?null:Lo(t),o=Ho(e,i,{repoRoot:n,nowMs:r});return o.length===0?null:{slices:o,context_ok:i!==null}}var Pu,es=_(()=>{"use strict";bt();Pu=2e3;s(Du,"buildCostPayload")});function Ou(e){if(!e||e.announce_error!=null)return null;let t=e.own_session_id;return typeof t=="string"&&fw.test(t)?t.toLowerCase():null}var fw,Mu=_(()=>{"use strict";fw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Ou,"snapshotSessionId")});async function Fu(e){let t=e.now??Date.now,n=e.fetchContext(),{turns:r}=await tn(e.transcriptPath),[i,o,a]=await Promise.all([No(e.transcriptPath,{turns:r}),Uo(e.transcriptPath),n]);if(e.sessionId&&(i.session_id=e.sessionId,o.session_id=e.sessionId),i.maind_connected=e.connection(i.maind_connected==="connected",t()),!i.session_id)return{posted:!1,contextOk:a!==null,sentSlices:!1};let c=Du(r,a,e.repoRoot,t()),l=Oo(i,o,{client_session_id:e.coordSessionId,client:"claude-code"},"live_bridge",c);return await e.post(l,c!==null),{posted:!0,contextOk:c?.context_ok??a!==null,sentSlices:c!==null}}var Lu=_(()=>{"use strict";bt();es();s(Fu,"ingestSessionEnd")});var $u={};q($u,{runOnSessionEnd:()=>kw});import{execFileSync as mw}from"node:child_process";function gw(e,t){try{let n=O(),r=n!==null&&!Eo(process.env,ne()),i=null;if(n!==null){let o=_t(mt(n),{hostPids:me(),cwd:process.cwd()});if(o){let a=Date.parse(o.snap.written_at);i=Number.isFinite(a)?Math.max(0,t-a):null}}return Cu({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function yw(){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;try{let n=O();if(n!==null){let r=_t(mt(n),{hostPids:me(),cwd:process.cwd()}),i=Ou(r?.snap);if(i!==null)return i}}catch{}let t=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return e.test(t)?t:null}function bw(){try{let e=mw("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}async function _w(e,t,n,r){if(n===null)return null;try{return await Le("get_session_cost_context",{project_key:n,...r?{session_id:r}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:P,timeoutMs:Pu})}catch{return null}}async function ww(e,t,n,r,i){let o=fetch(hw,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":P},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=Do(Po(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
171
- `)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([o,a])}async function kw(){try{for(let i of me())kd(ht(),i)}catch{}let e=D();if(!e)return 0;let t=await C(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=on(t);if(r)try{let i=U(),o=yw(),a=O();await Fu({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:o,repoRoot:bw(),fetchContext:s(()=>_w(e,i,a,o),"fetchContext"),post:s((c,l)=>ww(e,i,c,1500,l),"post"),connection:gw})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
172
- `)}return await Qo(n),0}var hw,ju=_(()=>{"use strict";bt();Xe();B();nn();Vo();qo();oe();Zo();xo();hr();ge();yr();xe();Nu();es();Mu();Lu();hw=Rr;s(gw,"connectionVerdict");s(yw,"presenceSessionId");s(bw,"sessionRepoRoot");s(_w,"fetchCostContext");s(ww,"postWithTimeout");s(kw,"runOnSessionEnd")});function Q(e=process.env,t=ne()){let n=e.MAIND_GUARD;return{mode:n==="off"||n==="warn"||n==="block"?n:t?.guard_mode??"off",stopGate:t?.guard_stop_gate===!0}}async function vt(e,t=de()){let n={};try{let i=await G(t);if(i!==null&&i.trim().length>0){let o=JSON.parse(i);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}let r={...n,...e};await F(t,JSON.stringify(r,null,2)+`
173
- `,384)}var Ge=_(()=>{"use strict";Xe();ce();s(Q,"resolveGuardConfig");s(vt,"writeGuardConfig")});function vw(e){let t={mode:"warn",stopGate:!1,full:!1,dryRun:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--mode":{let i=e[++n];if(i!=="warn"&&i!=="block")return null;t.mode=i;break}case"--stop-gate":t.stopGate=!0;break;case"--full":case"--yes":t.full=!0;break;case"--dry-run":t.dryRun=!0;break;default:return null}return t}async function Hu(e,t,n=process.stdout){let r=vw(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
174
- `),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},o=[];for(let l of Rn)o.push(await ri(i,l));for(let l of o)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
170
+ `),0)}function Du(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var sw,aw,cw,Ir,pw,Su,rs=_(()=>{"use strict";bt();Qt();qe();B();Ot();hr();ge();Yo();Xo();yr();oe();kt();Ar();He();es();vu();sw=process.env.MAIND_THRESHOLDS_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds",aw=1500,cw=1e4,Ir=7*24*60*60*1e3;s(Tu,"recordGuardSignals");s(Iu,"closeTrackedSession");s(lw,"gcState");s(Ue,"effectiveConfig");s(Cu,"getOrCreateSession");s(dw,"runOnSessionStart");s(uw,"readSettingsRaw");s(ts,"writeIdentitySideChannel");pw=6e4;s(Nu,"grandparentPid");s(me,"agentHostPidCandidates");s(fw,"runOnToolUse");s(mw,"denyReason");s(hw,"runOnFileWrite");s(gw,"runOnFileEdit");s(yw,"currentGitBranch");s(bw,"maybeEmitAdvisory");s(ns,"runSessionEndMetrics");s(_w,"runFlush");s(Pu,"flushPending");s(ww,"runHookStatus");Su="Re-run `maind-mcp-bridge install` to add the missing hooks \u2014 it is append-only and idempotent: it adds only what is absent, asks consent per hook, and never rewrites an entry you already have.";s(kw,"readHookWiring");s(vw,"runSyncConfig");s(Du,"sessionIdOf")});function Mu(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Fu=_(()=>{"use strict";s(Mu,"resolveConnection")});function $u(e,t,n,r=Date.now()){let i=t===null?null:Ho(t),o=Wo(e,i,{repoRoot:n,nowMs:r});return o.length===0?null:{slices:o,context_ok:i!==null}}var Lu,is=_(()=>{"use strict";bt();Lu=2e3;s($u,"buildCostPayload")});function ju(e){if(!e||e.announce_error!=null)return null;let t=e.own_session_id;return typeof t=="string"&&Sw.test(t)?t.toLowerCase():null}var Sw,Hu=_(()=>{"use strict";Sw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(ju,"snapshotSessionId")});async function Uu(e){let t=e.now??Date.now,n=e.fetchContext(e.projectKey),{turns:r}=await tn(e.transcriptPath),i=e.resolveRoot?Ko(r,e.resolveRoot):null,o=i&&e.projectKeyOf?e.projectKeyOf(i):null,a=i!==null&&o!==null&&o!==e.projectKey;a&&n.catch(()=>{});let[c,l,p]=await Promise.all([Po(e.transcriptPath,{turns:r}),Bo(e.transcriptPath),a?e.fetchContext(o):n]),d=i??e.repoRoot;if(e.sessionId&&(c.session_id=e.sessionId,l.session_id=e.sessionId),c.maind_connected=e.connection(c.maind_connected==="connected",t()),!c.session_id)return{posted:!1,contextOk:p!==null,sentSlices:!1};let u=$u(r,p,d,t()),f=Mo(c,l,{client_session_id:e.coordSessionId,client:"claude-code"},"live_bridge",u);return await e.post(f,u!==null),{posted:!0,contextOk:u?.context_ok??p!==null,sentSlices:u!==null}}var Gu=_(()=>{"use strict";bt();is();s(Uu,"ingestSessionEnd")});var Bu={};q(Bu,{runOnSessionEnd:()=>Pw});import{execFileSync as os}from"node:child_process";function xw(e,t){try{let n=M(),r=n!==null&&!xo(process.env,ne()),i=null;if(n!==null){let o=_t(mt(n),{hostPids:me(),cwd:process.cwd()});if(o){let a=Date.parse(o.snap.written_at);i=Number.isFinite(a)?Math.max(0,t-a):null}}return Mu({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function Rw(){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;try{let n=M();if(n!==null){let r=_t(mt(n),{hostPids:me(),cwd:process.cwd()}),i=ju(r?.snap);if(i!==null)return i}}catch{}let t=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return e.test(t)?t:null}function Aw(){try{let e=os("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function Tw(e){let t=Wu.get(e);if(t!==void 0)return t;let n=null;try{let r=os("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();n=r.length>0?r:null}catch{n=null}return Wu.set(e,n),n}function Iw(e){let t=Ku.get(e);if(t!==void 0)return t;let n=null;try{let r=os("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=zr(r))}catch{n=null}return Ku.set(e,n),n}async function Cw(e,t,n,r){if(n===null)return null;try{return await Le("get_session_cost_context",{project_key:n,...r?{session_id:r}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:P,timeoutMs:Lu})}catch{return null}}async function Nw(e,t,n,r,i){let o=fetch(Ew,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":P},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=Oo(Do(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
171
+ `)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([o,a])}async function Pw(){try{for(let i of me())Rd(ht(),i)}catch{}let e=O();if(!e)return 0;let t=await C(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=on(t);if(r)try{let i=U(),o=Rw(),a=M();await Uu({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:o,repoRoot:Aw(),resolveRoot:Tw,projectKeyOf:Iw,fetchContext:s(c=>Cw(e,i,c,o),"fetchContext"),post:s((c,l)=>Nw(e,i,c,1500,l),"post"),connection:xw})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
172
+ `)}return await ns(n),0}var Ew,Wu,Ku,Vu=_(()=>{"use strict";bt();Xe();B();nn();Yo();Xo();oe();rs();Ro();hr();ge();yr();xe();Fu();is();Hu();Gu();Ew=Rr;s(xw,"connectionVerdict");s(Rw,"presenceSessionId");s(Aw,"sessionRepoRoot");Wu=new Map;s(Tw,"gitRootOf");Ku=new Map;s(Iw,"projectKeyOfRoot");s(Cw,"fetchCostContext");s(Nw,"postWithTimeout");s(Pw,"runOnSessionEnd")});function Q(e=process.env,t=ne()){let n=e.MAIND_GUARD;return{mode:n==="off"||n==="warn"||n==="block"?n:t?.guard_mode??"off",stopGate:t?.guard_stop_gate===!0}}async function vt(e,t=de()){let n={};try{let i=await G(t);if(i!==null&&i.trim().length>0){let o=JSON.parse(i);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}let r={...n,...e};await L(t,JSON.stringify(r,null,2)+`
173
+ `,384)}var Ge=_(()=>{"use strict";Xe();ce();s(Q,"resolveGuardConfig");s(vt,"writeGuardConfig")});function Dw(e){let t={mode:"warn",stopGate:!1,full:!1,dryRun:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--mode":{let i=e[++n];if(i!=="warn"&&i!=="block")return null;t.mode=i;break}case"--stop-gate":t.stopGate=!0;break;case"--full":case"--yes":t.full=!0;break;case"--dry-run":t.dryRun=!0;break;default:return null}return t}async function qu(e,t,n=process.stdout){let r=Dw(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
174
+ `),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},o=[];for(let l of Rn)o.push(await ii(i,l));for(let l of o)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
175
175
  `);let a=o.some(l=>l.detail==="user declined"),c=o.some(l=>l.status==="failed");return r.dryRun?(n.write(`
176
176
  [dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
177
177
  `),0):(await vt({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
@@ -181,77 +181,77 @@ Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
181
181
  check: maind-mcp-bridge guard status
182
182
  Takes effect for NEW Claude Code sessions (hooks are read at session start).
183
183
  `),a&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
184
- `),c?1:0)}var Uu=_(()=>{"use strict";Ot();ii();Ge();s(vw,"parseGuardInstallFlags");s(Hu,"runGuardInstall")});import{existsSync as Gu}from"node:fs";import{mkdir as Sw,readFile as Ew,readdir as xw,rename as Rw,stat as Aw,unlink as Tw,writeFile as Iw}from"node:fs/promises";import{join as Pr}from"node:path";function Wu(e){return Pr(an,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function he(e){try{let t=Wu(e);if(!Gu(t))return{};let n=JSON.parse(await Ew(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function J(e,t){await Sw(an,{recursive:!0,mode:448});let n=Wu(e),r=`${n}.tmp`;await Iw(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await Rw(r,n)}async function Ku(e=7*24*60*60*1e3,t=Date.now()){try{if(!Gu(an))return;for(let n of await xw(an)){if(!n.endsWith(".json"))continue;let r=Pr(an,n);try{let i=await Aw(r);t-i.mtimeMs>e&&await Tw(r)}catch{}}}catch{}}var St,an,Et=_(()=>{"use strict";He();St=Pr(je,"guard"),an=Pr(St,"sessions");s(Wu,"sessionFile");s(he,"loadGuardSession");s(J,"saveGuardSession");s(Ku,"sweepOldGuardSessions")});import{existsSync as Cw}from"node:fs";import{appendFile as Nw,mkdir as Pw,open as Dw}from"node:fs/promises";import{join as Ow}from"node:path";async function V(e){try{await Pw(St,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
185
- `;await Nw(xt,t,{mode:384})}catch{}}async function Bu(e=256*1024){let t={inject_ok:0,inject_fail:0,warn:0,deny:0,override:0,stop_block:0,gate_override:0,cross_session_warn:0,cross_session_deny:0};try{if(!Cw(xt))return t;let n=await Dw(xt,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),o=Buffer.alloc(r-i);await n.read(o,0,o.length,i);let c=o.toString("utf8").split(`
186
- `);for(let l of i>0?c.slice(1):c)if(l.trim())try{let u=JSON.parse(l);typeof u.event=="string"&&u.event in t&&(t[u.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var xt,Rt=_(()=>{"use strict";Et();xt=Ow(St,"events.jsonl");s(V,"appendGuardEvent");s(Bu,"readGuardEventCounts")});var qu={};q(qu,{runGuard:()=>jw});import{existsSync as Mw,readFileSync as Fw}from"node:fs";import{homedir as Vu}from"node:os";import{join as Lw}from"node:path";async function jw(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Hu(n,Vu());case"status":return Uw();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
184
+ `),c?1:0)}var zu=_(()=>{"use strict";Ot();oi();Ge();s(Dw,"parseGuardInstallFlags");s(qu,"runGuardInstall")});import{existsSync as Ju}from"node:fs";import{mkdir as Ow,readFile as Mw,readdir as Fw,rename as Lw,stat as $w,unlink as jw,writeFile as Hw}from"node:fs/promises";import{join as Pr}from"node:path";function Yu(e){return Pr(an,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function he(e){try{let t=Yu(e);if(!Ju(t))return{};let n=JSON.parse(await Mw(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function J(e,t){await Ow(an,{recursive:!0,mode:448});let n=Yu(e),r=`${n}.tmp`;await Hw(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await Lw(r,n)}async function Xu(e=7*24*60*60*1e3,t=Date.now()){try{if(!Ju(an))return;for(let n of await Fw(an)){if(!n.endsWith(".json"))continue;let r=Pr(an,n);try{let i=await $w(r);t-i.mtimeMs>e&&await jw(r)}catch{}}}catch{}}var St,an,Et=_(()=>{"use strict";He();St=Pr(je,"guard"),an=Pr(St,"sessions");s(Yu,"sessionFile");s(he,"loadGuardSession");s(J,"saveGuardSession");s(Xu,"sweepOldGuardSessions")});import{existsSync as Uw}from"node:fs";import{appendFile as Gw,mkdir as Ww,open as Kw}from"node:fs/promises";import{join as Bw}from"node:path";async function V(e){try{await Ww(St,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
185
+ `;await Gw(xt,t,{mode:384})}catch{}}async function Qu(e=256*1024){let t={inject_ok:0,inject_fail:0,warn:0,deny:0,override:0,stop_block:0,gate_override:0,cross_session_warn:0,cross_session_deny:0};try{if(!Uw(xt))return t;let n=await Kw(xt,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),o=Buffer.alloc(r-i);await n.read(o,0,o.length,i);let c=o.toString("utf8").split(`
186
+ `);for(let l of i>0?c.slice(1):c)if(l.trim())try{let p=JSON.parse(l);typeof p.event=="string"&&p.event in t&&(t[p.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var xt,Rt=_(()=>{"use strict";Et();xt=Bw(St,"events.jsonl");s(V,"appendGuardEvent");s(Qu,"readGuardEventCounts")});var ep={};q(ep,{runGuard:()=>Yw});import{existsSync as Vw,readFileSync as qw}from"node:fs";import{homedir as Zu}from"node:os";import{join as zw}from"node:path";async function Yw(e){let t=e[0],n=e.slice(1);switch(t){case"install":return qu(n,Zu());case"status":return Qw();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
187
187
  `),1):(await vt({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
188
188
  `),0)}case"off":return await vt({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
189
189
  `),0;case"stop-gate":{let r=n[0];return r!=="on"&&r!=="off"?(process.stdout.write(`usage: maind-mcp-bridge guard stop-gate <on|off>
190
190
  `),1):(await vt({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
191
- `),0)}case"skip":return Hw(n);default:return process.stdout.write($w),t===void 0||t==="--help"||t==="-h"?0:1}}async function Hw(e){let t=null,n=null;for(let o=0;o<e.length;o++)e[o]==="--session"?t=e[++o]??null:e[o]==="--reason"&&(n=e[++o]??null);if(!t||!n||n.trim().length===0)return process.stdout.write(`usage: maind-mcp-bridge guard skip --session <id> --reason "<why consultation is unnecessary here>"
191
+ `),0)}case"skip":return Xw(n);default:return process.stdout.write(Jw),t===void 0||t==="--help"||t==="-h"?0:1}}async function Xw(e){let t=null,n=null;for(let o=0;o<e.length;o++)e[o]==="--session"?t=e[++o]??null:e[o]==="--reason"&&(n=e[++o]??null);if(!t||!n||n.trim().length===0)return process.stdout.write(`usage: maind-mcp-bridge guard skip --session <id> --reason "<why consultation is unnecessary here>"
192
192
  `),1;let r=n.trim().slice(0,500),i=await he(t);return await J(t,{...i,override_reason:r}),await V({event:"override",session_id:t,reason:r,cwd:process.cwd()}),process.stdout.write(`override recorded for session ${t} \u2014 the gate opens on the next attempt.
193
193
  logged (auditable) in ${xt}
194
- `),0}async function Uw(){let e=Q(),t=Lw(Vu(),".claude","settings.json"),n=null;try{Mw(t)&&(n=Fw(t,"utf8"))}catch{}let r=Dt(n,{},Rn),i=await Bu();process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",hook_wiring:r.map(a=>({event:a.event,subcommand:a.subcommand,status:a.status,detail:a.detail})),events:i,events_file:xt},null,2)+`
194
+ `),0}async function Qw(){let e=Q(),t=zw(Zu(),".claude","settings.json"),n=null;try{Vw(t)&&(n=qw(t,"utf8"))}catch{}let r=Dt(n,{},Rn),i=await Qu();process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",hook_wiring:r.map(a=>({event:a.event,subcommand:a.subcommand,status:a.status,detail:a.detail})),events:i,events_file:xt},null,2)+`
195
195
  `);let o=r.filter(a=>a.status!=="ok");if(e.mode==="off"&&process.stderr.write("\n[maind] guard is OFF \u2014 enable with `guard install` (first time) or `guard mode warn|block`.\n"),o.length>0&&e.mode!=="off"){process.stderr.write(`
196
196
  [maind] guard hook wiring is incomplete:
197
197
  `);for(let a of o)process.stderr.write(` \u2022 ${a.detail}
198
- `);o.some(a=>a.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var $w,zu=_(()=>{"use strict";Ot();Ge();Uu();Rt();Et();$w=["usage: maind-mcp-bridge guard <verb>",""," install [--mode warn|block] [--stop-gate] [--full] [--dry-run]"," wire the guard hooks (consent per hook, append-only) + set the mode"," status mode, hook wiring, and local event counts"," mode <warn|block>"," flip enforcement hardness (config-only; settings.json untouched)"," off disable the guard (hooks stay wired, become no-ops)"," stop-gate <on|off>"," toggle the strict completion gate (review before finish)",' skip --session <id> --reason "<why>"'," record a logged override for one session (block-gate exit valve)",""].join(`
199
- `);s(jw,"runGuard");s(Hw,"runGuardSkip");s(Uw,"runGuardStatus")});var Zu={};q(Zu,{BRIEFING_CACHE_FILE:()=>Yu,formatInjection:()=>Qu,resolveBriefingInjection:()=>Xu,runGuardInject:()=>Xw});import{existsSync as Gw}from"node:fs";import{mkdir as Ww,readFile as Kw,rename as Bw,writeFile as Vw}from"node:fs/promises";import{dirname as qw,join as zw}from"node:path";async function Xu(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??Yu,o=n.fetcher??Xd,a=await Qw(i);if(a!==null&&r-Date.parse(a.fetched_at)<Jw&&a.project_key===e)return{text:a.text,via:"cache"};let l=await o({apiKey:t,deviceId:ek(),projectKey:e,bridgeVersion:P,timeoutMs:Yw});return l!==null?(await Zw(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:l}),{text:l,via:"fetch"}):a!==null?{text:a.text,via:"stale-cache"}:{text:null,via:"none"}}async function Xw(){try{if(Q().mode==="off")return 0;let t=await C(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;await Ku();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let u=await he(n);return await J(n,{...u,carryover:!0}),0}let i=D();if(i===null)return 0;let o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=O(),c=await Xu(a,i),l=await he(n);return c.text===null?(await J(n,{...l,inject_failed:!0}),await V({event:"inject_fail",session_id:n,cwd:o,project_key:a??void 0}),process.stderr.write(`[maind] guard: briefing fetch failed and no cache \u2014 session starts unbriefed; the model should call get_session_briefing itself.
200
- `),0):(process.stdout.write(Qu(c.text,c.via)),await J(n,{...l,injected:!0}),await V({event:"inject_ok",session_id:n,cwd:o,project_key:a??void 0,detail:c.via}),0)}catch{return 0}}function Qu(e,t){let n=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=e;return Buffer.byteLength(r,"utf8")>Ju&&(r=r.slice(0,Ju)+`
198
+ `);o.some(a=>a.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var Jw,tp=_(()=>{"use strict";Ot();Ge();zu();Rt();Et();Jw=["usage: maind-mcp-bridge guard <verb>",""," install [--mode warn|block] [--stop-gate] [--full] [--dry-run]"," wire the guard hooks (consent per hook, append-only) + set the mode"," status mode, hook wiring, and local event counts"," mode <warn|block>"," flip enforcement hardness (config-only; settings.json untouched)"," off disable the guard (hooks stay wired, become no-ops)"," stop-gate <on|off>"," toggle the strict completion gate (review before finish)",' skip --session <id> --reason "<why>"'," record a logged override for one session (block-gate exit valve)",""].join(`
199
+ `);s(Yw,"runGuard");s(Xw,"runGuardSkip");s(Qw,"runGuardStatus")});var sp={};q(sp,{BRIEFING_CACHE_FILE:()=>rp,formatInjection:()=>op,resolveBriefingInjection:()=>ip,runGuardInject:()=>ck});import{existsSync as Zw}from"node:fs";import{mkdir as ek,readFile as tk,rename as nk,writeFile as rk}from"node:fs/promises";import{dirname as ik,join as ok}from"node:path";async function ip(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??rp,o=n.fetcher??nu,a=await lk(i);if(a!==null&&r-Date.parse(a.fetched_at)<sk&&a.project_key===e)return{text:a.text,via:"cache"};let l=await o({apiKey:t,deviceId:uk(),projectKey:e,bridgeVersion:P,timeoutMs:ak});return l!==null?(await dk(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:l}),{text:l,via:"fetch"}):a!==null?{text:a.text,via:"stale-cache"}:{text:null,via:"none"}}async function ck(){try{if(Q().mode==="off")return 0;let t=await C(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;await Xu();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let p=await he(n);return await J(n,{...p,carryover:!0}),0}let i=O();if(i===null)return 0;let o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=M(),c=await ip(a,i),l=await he(n);return c.text===null?(await J(n,{...l,inject_failed:!0}),await V({event:"inject_fail",session_id:n,cwd:o,project_key:a??void 0}),process.stderr.write(`[maind] guard: briefing fetch failed and no cache \u2014 session starts unbriefed; the model should call get_session_briefing itself.
200
+ `),0):(process.stdout.write(op(c.text,c.via)),await J(n,{...l,injected:!0}),await V({event:"inject_ok",session_id:n,cwd:o,project_key:a??void 0,detail:c.via}),0)}catch{return 0}}function op(e,t){let n=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=e;return Buffer.byteLength(r,"utf8")>np&&(r=r.slice(0,np)+`
201
201
  \u2026 [maind guard: briefing truncated at 10KB]`),`[maind guard] Session briefing, injected deterministically (ADR-284)${n} \u2014 the session-start get_session_briefing consultation is satisfied by this block:
202
202
 
203
203
  `+r+`
204
- `}async function Qw(e){try{if(!Gw(e))return null;let t=JSON.parse(await Kw(e,"utf8"));return typeof t.fetched_at!="string"||typeof t.text!="string"||Number.isNaN(Date.parse(t.fetched_at))?null:{fetched_at:t.fetched_at,project_key:typeof t.project_key=="string"?t.project_key:null,text:t.text}}catch{return null}}async function Zw(e,t){try{await Ww(qw(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await Vw(n,JSON.stringify(t,null,2),{mode:384}),await Bw(n,e)}catch{}}function ek(){try{return U()}catch{return null}}var Yu,Jw,Yw,Ju,ep=_(()=>{"use strict";B();oe();ge();xe();Ge();Rt();Et();nn();Yu=zw(St,"briefing-cache.json"),Jw=12*60*60*1e3,Yw=3e3,Ju=10*1024;s(Xu,"resolveBriefingInjection");s(Xw,"runGuardInject");s(Qu,"formatInjection");s(Qw,"readCache");s(Zw,"writeCache");s(ek,"safeDeviceId")});var ip={};q(ip,{decideGate:()=>rp,runGuardGate:()=>nk});function rp(e){let{mode:t,session:n}=e;return t==="off"?{kind:"allow"}:n.injected===!0||n.carryover===!0||typeof n.override_reason=="string"||e.consulted?{kind:"allow"}:t==="warn"?n.warned===!0?{kind:"allow"}:{kind:"warn",context:tp(n)}:(n.deny_count??0)>=np?n.warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Block-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+tp(n)}:{kind:"deny",reason:tk(e.sessionId,n)}}function tp(e){return`[maind guard | warn] ${e.inject_failed===!0?"The automatic briefing injection FAILED for this session (server unreachable or not paired) \u2014 call get_session_briefing yourself to close the gap.":"No maind consultation has happened in this session yet."} The project mandates session-start consultation (proc/maind-consultation-triggers): call get_session_briefing, or search_lessons with the task's key terms, before substantive edits. This reminder appears once per session.`}function tk(e,t){return`[maind guard | block] Edit denied \u2014 ${t.inject_failed===!0?"the automatic briefing injection failed for this session, so the consultation is still open":"no maind consultation has happened in this session"} (mandated by proc/maind-consultation-triggers). Two exits:
204
+ `}async function lk(e){try{if(!Zw(e))return null;let t=JSON.parse(await tk(e,"utf8"));return typeof t.fetched_at!="string"||typeof t.text!="string"||Number.isNaN(Date.parse(t.fetched_at))?null:{fetched_at:t.fetched_at,project_key:typeof t.project_key=="string"?t.project_key:null,text:t.text}}catch{return null}}async function dk(e,t){try{await ek(ik(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await rk(n,JSON.stringify(t,null,2),{mode:384}),await nk(n,e)}catch{}}function uk(){try{return U()}catch{return null}}var rp,sk,ak,np,ap=_(()=>{"use strict";B();oe();ge();xe();Ge();Rt();Et();nn();rp=ok(St,"briefing-cache.json"),sk=12*60*60*1e3,ak=3e3,np=10*1024;s(ip,"resolveBriefingInjection");s(ck,"runGuardInject");s(op,"formatInjection");s(lk,"readCache");s(dk,"writeCache");s(uk,"safeDeviceId")});var up={};q(up,{decideGate:()=>dp,runGuardGate:()=>fk});function dp(e){let{mode:t,session:n}=e;return t==="off"?{kind:"allow"}:n.injected===!0||n.carryover===!0||typeof n.override_reason=="string"||e.consulted?{kind:"allow"}:t==="warn"?n.warned===!0?{kind:"allow"}:{kind:"warn",context:cp(n)}:(n.deny_count??0)>=lp?n.warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Block-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+cp(n)}:{kind:"deny",reason:pk(e.sessionId,n)}}function cp(e){return`[maind guard | warn] ${e.inject_failed===!0?"The automatic briefing injection FAILED for this session (server unreachable or not paired) \u2014 call get_session_briefing yourself to close the gap.":"No maind consultation has happened in this session yet."} The project mandates session-start consultation (proc/maind-consultation-triggers): call get_session_briefing, or search_lessons with the task's key terms, before substantive edits. This reminder appears once per session.`}function pk(e,t){return`[maind guard | block] Edit denied \u2014 ${t.inject_failed===!0?"the automatic briefing injection failed for this session, so the consultation is still open":"no maind consultation has happened in this session"} (mandated by proc/maind-consultation-triggers). Two exits:
205
205
  1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
206
206
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
207
- After ${np} denies this gate downgrades itself to warn.`}async function nk(){try{let e=Q();if(e.mode==="off")return 0;let t=await C(),n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let i=await he(r),o=(await $()).guard_signals?.[r]?.consulted_at!==void 0,a=rp({mode:e.mode,session:i,consulted:o,sessionId:r}),c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),l=O()??void 0;return a.kind==="deny"?(process.stdout.write(wt(a.reason)),await J(r,{...i,deny_count:(i.deny_count??0)+1}),await V({event:"deny",session_id:r,cwd:c,project_key:l}),0):a.kind==="warn"?(process.stdout.write(ve(a.context)),await J(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await V({event:"warn",session_id:r,cwd:c,project_key:l}),0):(await J(r,{...i,edits_seen:(i.edits_seen??0)+1}),0)}catch{return 0}}var np,op=_(()=>{"use strict";oe();kt();He();ge();Ge();Rt();Et();np=3;s(rp,"decideGate");s(tp,"warnText");s(tk,"denyText");s(nk,"runGuardGate")});var ap={};q(ap,{decideStopGate:()=>sp,runGuardStop:()=>ik});function sp(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function ik(){try{let e=Q();if(e.mode==="off"||!e.stopGate)return 0;let t=await C(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=await he(n),i=(await $()).guard_signals?.[n]?.reviewed_at!==void 0;return sp({enabled:!0,editsSeen:r.edits_seen??0,reviewed:i,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:rk})),await J(n,{...r,stop_blocked:!0}),await V({event:"stop_block",session_id:n})),0}catch{return 0}}var rk,cp=_(()=>{"use strict";oe();He();Ge();Rt();Et();s(sp,"decideStopGate");rk="[maind guard] Stop gate (strict, opt-in): this session edited files but review_changes never ran. Run the review over the edit batches \u2014 codebase_review_changes, then review_changes with its review_args (or `maind review` from the CLI) \u2014 report the findings, then finish. This gate blocks only once.";s(ik,"runGuardStop")});import{appendFile as ok,mkdir as sk,readFile as dp,rename as up,writeFile as pp}from"node:fs/promises";import{homedir as fp}from"node:os";import{join as mp}from"node:path";function hp(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},o=new Map,a=1/0,c=-1/0;for(let u of e){u.at<a&&(a=u.at),u.at>c&&(c=u.at);let d=i[u.tool]??={calls:0,warns:0,denies:0};if(u.event==="tool_call"?d.calls+=1:u.event==="policy_warn"||u.event==="sha_warn"?d.warns+=1:d.denies+=1,(u.event==="policy_warn"||u.event==="policy_deny")&&u.convention_id!==void 0&&u.convention_version!==void 0){let p=o.get(u.convention_id);(p===void 0||u.convention_version>p)&&o.set(u.convention_id,u.convention_version)}}let l=Object.entries(i).sort((u,d)=>d[1].calls+d[1].warns+d[1].denies-(u[1].calls+u[1].warns+u[1].denies)).slice(0,64);return{window_start:new Date(a).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...o.entries()].slice(0,32).map(([u,d])=>({convention_id:u,convention_version:d})),...r?{project_key:r}:{}}}function We(){return mp(fp(),".maind","gateway","attest-spool.jsonl")}async function ts(e){let t=D();if(t===null)return!1;let n=await Le("gateway_attest",{...e},{apiKey:t,deviceId:U(),projectKey:e.project_key??null,bridgeVersion:P,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function gp(e){try{await sk(mp(fp(),".maind","gateway"),{recursive:!0}),await ok(We(),JSON.stringify(e)+`
208
- `,{mode:384}),await ak()}catch{}}async function ak(){try{let t=(await dp(We(),"utf8")).split(`
209
- `).filter(r=>r.trim());if(t.length<=lp)return;let n=`${We()}.${process.pid}.tmp`;await pp(n,t.slice(-lp).join(`
207
+ After ${lp} denies this gate downgrades itself to warn.`}async function fk(){try{let e=Q();if(e.mode==="off")return 0;let t=await C(),n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let i=await he(r),o=(await j()).guard_signals?.[r]?.consulted_at!==void 0,a=dp({mode:e.mode,session:i,consulted:o,sessionId:r}),c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),l=M()??void 0;return a.kind==="deny"?(process.stdout.write(wt(a.reason)),await J(r,{...i,deny_count:(i.deny_count??0)+1}),await V({event:"deny",session_id:r,cwd:c,project_key:l}),0):a.kind==="warn"?(process.stdout.write(ve(a.context)),await J(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await V({event:"warn",session_id:r,cwd:c,project_key:l}),0):(await J(r,{...i,edits_seen:(i.edits_seen??0)+1}),0)}catch{return 0}}var lp,pp=_(()=>{"use strict";oe();kt();He();ge();Ge();Rt();Et();lp=3;s(dp,"decideGate");s(cp,"warnText");s(pk,"denyText");s(fk,"runGuardGate")});var mp={};q(mp,{decideStopGate:()=>fp,runGuardStop:()=>hk});function fp(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function hk(){try{let e=Q();if(e.mode==="off"||!e.stopGate)return 0;let t=await C(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=await he(n),i=(await j()).guard_signals?.[n]?.reviewed_at!==void 0;return fp({enabled:!0,editsSeen:r.edits_seen??0,reviewed:i,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:mk})),await J(n,{...r,stop_blocked:!0}),await V({event:"stop_block",session_id:n})),0}catch{return 0}}var mk,hp=_(()=>{"use strict";oe();He();Ge();Rt();Et();s(fp,"decideStopGate");mk="[maind guard] Stop gate (strict, opt-in): this session edited files but review_changes never ran. Run the review over the edit batches \u2014 codebase_review_changes, then review_changes with its review_args (or `maind review` from the CLI) \u2014 report the findings, then finish. This gate blocks only once.";s(hk,"runGuardStop")});import{appendFile as gk,mkdir as yk,readFile as yp,rename as bp,writeFile as _p}from"node:fs/promises";import{homedir as wp}from"node:os";import{join as kp}from"node:path";function vp(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},o=new Map,a=1/0,c=-1/0;for(let p of e){p.at<a&&(a=p.at),p.at>c&&(c=p.at);let d=i[p.tool]??={calls:0,warns:0,denies:0};if(p.event==="tool_call"?d.calls+=1:p.event==="policy_warn"||p.event==="sha_warn"?d.warns+=1:d.denies+=1,(p.event==="policy_warn"||p.event==="policy_deny")&&p.convention_id!==void 0&&p.convention_version!==void 0){let u=o.get(p.convention_id);(u===void 0||p.convention_version>u)&&o.set(p.convention_id,p.convention_version)}}let l=Object.entries(i).sort((p,d)=>d[1].calls+d[1].warns+d[1].denies-(p[1].calls+p[1].warns+p[1].denies)).slice(0,64);return{window_start:new Date(a).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...o.entries()].slice(0,32).map(([p,d])=>({convention_id:p,convention_version:d})),...r?{project_key:r}:{}}}function We(){return kp(wp(),".maind","gateway","attest-spool.jsonl")}async function ss(e){let t=O();if(t===null)return!1;let n=await Le("gateway_attest",{...e},{apiKey:t,deviceId:U(),projectKey:e.project_key??null,bridgeVersion:P,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function Sp(e){try{await yk(kp(wp(),".maind","gateway"),{recursive:!0}),await gk(We(),JSON.stringify(e)+`
208
+ `,{mode:384}),await bk()}catch{}}async function bk(){try{let t=(await yp(We(),"utf8")).split(`
209
+ `).filter(r=>r.trim());if(t.length<=gp)return;let n=`${We()}.${process.pid}.tmp`;await _p(n,t.slice(-gp).join(`
210
210
  `)+`
211
- `,{mode:384}),await up(n,We())}catch{}}async function yp(){let e;try{e=(await dp(We(),"utf8")).split(`
212
- `).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await ts(i)||(n=!0,t.push(r))}try{let r=`${We()}.${process.pid}.tmp`;await pp(r,t.length>0?t.join(`
211
+ `,{mode:384}),await bp(n,We())}catch{}}async function Ep(){let e;try{e=(await yp(We(),"utf8")).split(`
212
+ `).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await ss(i)||(n=!0,t.push(r))}try{let r=`${We()}.${process.pid}.tmp`;await _p(r,t.length>0?t.join(`
213
213
  `)+`
214
- `:"",{mode:384}),await up(r,We())}catch{}}var lp,bp=_(()=>{"use strict";B();nn();xe();lp=256;s(hp,"aggregateWindow");s(We,"attestSpoolPath");s(ts,"postAttestation");s(gp,"spoolAttestation");s(ak,"capSpool");s(yp,"flushAttestSpool")});function cn(e=process.env,t=ne()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Dr(e=process.env,t=ne()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function _p(e,t=de()){let n={};try{let i=await G(t);if(i!==null&&i.trim().length>0){let o=JSON.parse(i);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}let r={...n,...e};await F(t,JSON.stringify(r,null,2)+`
215
- `,384)}async function wp(e,t=de()){await _p({gateway_mode:e},t)}async function kp(e,t=de()){await _p({gateway_attest:e},t)}function vp(e=process.env,t=ne()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var ns=_(()=>{"use strict";Xe();ce();s(cn,"resolveGatewayMode");s(Dr,"resolveGatewayAttest");s(_p,"writeGatewayConfigPatch");s(wp,"writeGatewayMode");s(kp,"writeGatewayAttest");s(vp,"resolveShaProofMode")});function Ep(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,o=i.gateway_gate;if(typeof o!="object"||o===null)continue;let a=o;if(a.enabled!==!0)continue;let c=typeof i.id=="string"&&i.id.length>0&&i.id.length<=64?i.id:null,l=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||l===null)continue;let u=typeof i.severity=="string"&&ck.has(i.severity)?i.severity:"recommended",d=typeof i.summary=="string"?i.summary:"",p=Array.isArray(a.servers)?a.servers.filter(f=>typeof f=="string"&&f.length>0):null;if(p!==null&&p.length===0)continue;let m=Array.isArray(a.deny_tools)?a.deny_tools.filter(f=>typeof f=="string"&&f.length>0):[];for(let f of m){if(n.length>=256)return n;n.push({tool:f,servers:p,conventionId:c,conventionVersion:l,severity:u,summary:d})}}return n}function lk(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function xp(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let o of n)lk(o,e,t)&&(i===null||Sp[o.severity]>Sp[i.severity])&&(i=o);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function Rp(e,t){let n=`${t.conventionId} v${t.conventionVersion}`,r=t.summary?` ("${t.summary}")`:"";return`maind gateway: tool '${e}' is denied by convention ${n}${r}. The call was not forwarded to the server. Exits: ask the user to run 'maind-mcp-bridge gateway mode warn' (observe instead of enforce), or to disable the convention for themselves (set_convention_pref) if it is not mandatory.`}var ck,Sp,rs=_(()=>{"use strict";ck=new Set(["required","recommended","info"]);s(Ep,"extractGatewayRules");Sp={required:2,recommended:1,info:0};s(lk,"ruleMatches");s(xp,"decideToolCall");s(Rp,"policyDenyText")});import{mkdirSync as dk,readFileSync as uk,renameSync as pk,writeFileSync as fk}from"node:fs";import{homedir as mk}from"node:os";import{dirname as hk,join as gk}from"node:path";function Ap(){return gk(mk(),".maind","gateway","policy-cache.json")}function Or(e,t,n=new Date().toISOString()){try{let r={version:is,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=Ap();dk(hk(i),{recursive:!0});let o=`${i}.${process.pid}.tmp`;fk(o,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),pk(o,i)}catch{}}function Mr(e){try{let t=uk(Ap(),"utf8"),n=JSON.parse(t);return n.version!==is||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:is,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var is,os=_(()=>{"use strict";is=1;s(Ap,"policyCachePath");s(Or,"writePolicyCache");s(Mr,"readPolicyCache")});function ln(e=process.env){let t=e.MAIND_MCP_URL??Bo,n=D();return{mcpUrl:t,keyFp:n?fn(n):"anon"}}async function Fr(e=6e3){let t=D();if(t===null)return null;let n=null;try{n=O()}catch{n=null}let r=await Le("get_conventions",{},{apiKey:t,deviceId:U(),projectKey:n,bridgeVersion:P,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return Ep(i)}var ss=_(()=>{"use strict";qe();B();nn();ge();xe();rs();s(ln,"policyIdentity");s(Fr,"fetchGatewayRules")});function dn(e){let t=Array.isArray(e.args)?e.args.map(String):[],n=t.indexOf("gateway");if(n===-1||t.indexOf("--",n+1)===-1)return!1;if(n===0)return!0;let r=[String(e.command??""),...t.slice(0,n)].join(" ");return/maind-mcp-bridge|@maind-dev\/mcp-bridge|\.js\s*$/.test(r)}function yk(e){if(dn(e))return!1;let t=typeof e.command=="string"?e.command:"",n=Array.isArray(e.args)?e.args:[],r=[t,...n.map(String)].join(" ");return r.includes("maind-mcp-bridge")||/@maind-dev\/mcp-bridge/.test(r)}function bk(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:dn(e)?{action:"skip",reason:"already-wrapped"}:yk(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Tp(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],o=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=o||t.env?{...o??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return a&&(c.env=a),c}function Ip(e){if(!dn(e))return null;let t=e.args.map(String),n=t.indexOf("--",t.indexOf("gateway")+1);return n===-1||n+1>=t.length?null:{...e,command:t[n+1],args:t.slice(n+2)}}function Cp(e){return Object.entries(e).map(([t,n])=>{let r=bk(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var Np=_(()=>{"use strict";s(dn,"isGatewayWrapped");s(yk,"isMaindProxyEntry");s(bk,"classifyServer");s(Tp,"wrapServerEntry");s(Ip,"unwrapServerEntry");s(Cp,"planRewrites")});var Lp={};q(Lp,{runGatewayInstall:()=>Ek,runGatewayUninstall:()=>xk});import{existsSync as _k,readFileSync as wk}from"node:fs";import{homedir as kk}from"node:os";import{join as Pp}from"node:path";import{createInterface as vk}from"node:readline";function Dp(e){let t={yes:!1,dryRun:!1};for(let n of e)if(n==="--yes")t.yes=!0;else if(n==="--dry-run")t.dryRun=!0;else return null;return t}function Op(){return[{label:"Claude Code (project .mcp.json)",path:Pp(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:Pp(kk(),".claude.json")}]}async function Mp(e){let t=vk({input:process.stdin,output:process.stderr});try{let n=await new Promise(r=>t.question(`${e} [y/N] `,r));return n.trim().toLowerCase()==="y"||n.trim().toLowerCase()==="yes"}finally{t.close()}}function Fp(e){let t=Sk(e);if(t===null)return null;try{let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=n,i=r.mcpServers;return typeof i!="object"||i===null||Array.isArray(i)?null:{raw:r,servers:i}}catch{return null}}function Sk(e){try{return _k(e)?wk(e,"utf8"):null}catch{return null}}async function Ek(e){let t=Dp(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
216
- `),2;let n=ee({entryPath:te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of Op()){let o=Fp(i.path);if(o===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
217
- `);continue}let a=Cp(o.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
218
- `);continue}if(!(t.yes||await Mp(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
214
+ `:"",{mode:384}),await bp(r,We())}catch{}}var gp,xp=_(()=>{"use strict";B();nn();xe();gp=256;s(vp,"aggregateWindow");s(We,"attestSpoolPath");s(ss,"postAttestation");s(Sp,"spoolAttestation");s(bk,"capSpool");s(Ep,"flushAttestSpool")});function cn(e=process.env,t=ne()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Dr(e=process.env,t=ne()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function Rp(e,t=de()){let n={};try{let i=await G(t);if(i!==null&&i.trim().length>0){let o=JSON.parse(i);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}let r={...n,...e};await L(t,JSON.stringify(r,null,2)+`
215
+ `,384)}async function Ap(e,t=de()){await Rp({gateway_mode:e},t)}async function Tp(e,t=de()){await Rp({gateway_attest:e},t)}function Ip(e=process.env,t=ne()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var as=_(()=>{"use strict";Xe();ce();s(cn,"resolveGatewayMode");s(Dr,"resolveGatewayAttest");s(Rp,"writeGatewayConfigPatch");s(Ap,"writeGatewayMode");s(Tp,"writeGatewayAttest");s(Ip,"resolveShaProofMode")});function Np(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,o=i.gateway_gate;if(typeof o!="object"||o===null)continue;let a=o;if(a.enabled!==!0)continue;let c=typeof i.id=="string"&&i.id.length>0&&i.id.length<=64?i.id:null,l=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||l===null)continue;let p=typeof i.severity=="string"&&_k.has(i.severity)?i.severity:"recommended",d=typeof i.summary=="string"?i.summary:"",u=Array.isArray(a.servers)?a.servers.filter(m=>typeof m=="string"&&m.length>0):null;if(u!==null&&u.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(m=>typeof m=="string"&&m.length>0):[];for(let m of f){if(n.length>=256)return n;n.push({tool:m,servers:u,conventionId:c,conventionVersion:l,severity:p,summary:d})}}return n}function wk(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Pp(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let o of n)wk(o,e,t)&&(i===null||Cp[o.severity]>Cp[i.severity])&&(i=o);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function Dp(e,t){let n=`${t.conventionId} v${t.conventionVersion}`,r=t.summary?` ("${t.summary}")`:"";return`maind gateway: tool '${e}' is denied by convention ${n}${r}. The call was not forwarded to the server. Exits: ask the user to run 'maind-mcp-bridge gateway mode warn' (observe instead of enforce), or to disable the convention for themselves (set_convention_pref) if it is not mandatory.`}var _k,Cp,cs=_(()=>{"use strict";_k=new Set(["required","recommended","info"]);s(Np,"extractGatewayRules");Cp={required:2,recommended:1,info:0};s(wk,"ruleMatches");s(Pp,"decideToolCall");s(Dp,"policyDenyText")});import{mkdirSync as kk,readFileSync as vk,renameSync as Sk,writeFileSync as Ek}from"node:fs";import{homedir as xk}from"node:os";import{dirname as Rk,join as Ak}from"node:path";function Op(){return Ak(xk(),".maind","gateway","policy-cache.json")}function Or(e,t,n=new Date().toISOString()){try{let r={version:ls,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=Op();kk(Rk(i),{recursive:!0});let o=`${i}.${process.pid}.tmp`;Ek(o,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),Sk(o,i)}catch{}}function Mr(e){try{let t=vk(Op(),"utf8"),n=JSON.parse(t);return n.version!==ls||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:ls,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var ls,ds=_(()=>{"use strict";ls=1;s(Op,"policyCachePath");s(Or,"writePolicyCache");s(Mr,"readPolicyCache")});function ln(e=process.env){let t=e.MAIND_MCP_URL??Jo,n=O();return{mcpUrl:t,keyFp:n?fn(n):"anon"}}async function Fr(e=6e3){let t=O();if(t===null)return null;let n=null;try{n=M()}catch{n=null}let r=await Le("get_conventions",{},{apiKey:t,deviceId:U(),projectKey:n,bridgeVersion:P,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return Np(i)}var us=_(()=>{"use strict";qe();B();nn();ge();xe();cs();s(ln,"policyIdentity");s(Fr,"fetchGatewayRules")});function dn(e){let t=Array.isArray(e.args)?e.args.map(String):[],n=t.indexOf("gateway");if(n===-1||t.indexOf("--",n+1)===-1)return!1;if(n===0)return!0;let r=[String(e.command??""),...t.slice(0,n)].join(" ");return/maind-mcp-bridge|@maind-dev\/mcp-bridge|\.js\s*$/.test(r)}function Tk(e){if(dn(e))return!1;let t=typeof e.command=="string"?e.command:"",n=Array.isArray(e.args)?e.args:[],r=[t,...n.map(String)].join(" ");return r.includes("maind-mcp-bridge")||/@maind-dev\/mcp-bridge/.test(r)}function Ik(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:dn(e)?{action:"skip",reason:"already-wrapped"}:Tk(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Mp(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],o=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=o||t.env?{...o??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return a&&(c.env=a),c}function Fp(e){if(!dn(e))return null;let t=e.args.map(String),n=t.indexOf("--",t.indexOf("gateway")+1);return n===-1||n+1>=t.length?null:{...e,command:t[n+1],args:t.slice(n+2)}}function Lp(e){return Object.entries(e).map(([t,n])=>{let r=Ik(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var $p=_(()=>{"use strict";s(dn,"isGatewayWrapped");s(Tk,"isMaindProxyEntry");s(Ik,"classifyServer");s(Mp,"wrapServerEntry");s(Fp,"unwrapServerEntry");s(Lp,"planRewrites")});var Kp={};q(Kp,{runGatewayInstall:()=>Mk,runGatewayUninstall:()=>Fk});import{existsSync as Ck,readFileSync as Nk}from"node:fs";import{homedir as Pk}from"node:os";import{join as jp}from"node:path";import{createInterface as Dk}from"node:readline";function Hp(e){let t={yes:!1,dryRun:!1};for(let n of e)if(n==="--yes")t.yes=!0;else if(n==="--dry-run")t.dryRun=!0;else return null;return t}function Up(){return[{label:"Claude Code (project .mcp.json)",path:jp(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:jp(Pk(),".claude.json")}]}async function Gp(e){let t=Dk({input:process.stdin,output:process.stderr});try{let n=await new Promise(r=>t.question(`${e} [y/N] `,r));return n.trim().toLowerCase()==="y"||n.trim().toLowerCase()==="yes"}finally{t.close()}}function Wp(e){let t=Ok(e);if(t===null)return null;try{let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=n,i=r.mcpServers;return typeof i!="object"||i===null||Array.isArray(i)?null:{raw:r,servers:i}}catch{return null}}function Ok(e){try{return Ck(e)?Nk(e,"utf8"):null}catch{return null}}async function Mk(e){let t=Hp(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
216
+ `),2;let n=ee({entryPath:te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of Up()){let o=Wp(i.path);if(o===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
217
+ `);continue}let a=Lp(o.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
218
+ `);continue}if(!(t.yes||await Gp(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
219
219
  Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
220
220
  The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
221
- `);continue}o.servers[c.key]=Tp(o.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
222
- `)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await F(i.path,JSON.stringify(o.raw,null,2)+`
221
+ `);continue}o.servers[c.key]=Mp(o.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
222
+ `)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await L(i.path,JSON.stringify(o.raw,null,2)+`
223
223
  `,384)}return process.stderr.write(r>0?`
224
224
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
225
225
  `:`
226
226
  Nothing to wrap.
227
- `),0}async function xk(e){let t=Dp(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
228
- `),2;let n=0;for(let r of Op()){let i=Fp(r.path);if(i===null)continue;let o=!1;for(let[a,c]of Object.entries(i.servers)){if(!dn(c)||!(t.yes||await Mp(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let u=Ip(c);if(u===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
229
- `);continue}i.servers[a]=u,o=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
230
- `)}!t.dryRun&&o&&await F(r.path,JSON.stringify(i.raw,null,2)+`
227
+ `),0}async function Fk(e){let t=Hp(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
228
+ `),2;let n=0;for(let r of Up()){let i=Wp(r.path);if(i===null)continue;let o=!1;for(let[a,c]of Object.entries(i.servers)){if(!dn(c)||!(t.yes||await Gp(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let p=Fp(c);if(p===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
229
+ `);continue}i.servers[a]=p,o=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
230
+ `)}!t.dryRun&&o&&await L(r.path,JSON.stringify(i.raw,null,2)+`
231
231
  `,384)}return process.stderr.write(n>0?`
232
232
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
233
233
  `:`
234
234
  Nothing wrapped \u2014 nothing to restore.
235
- `),0}var $p=_(()=>{"use strict";ce();Ye();Np();s(Dp,"parseFlags");s(Op,"targets");s(Mp,"confirm");s(Fp,"loadConfig");s(Sk,"readFileSafeSync");s(Ek,"runGatewayInstall");s(xk,"runGatewayUninstall")});var jp={};q(jp,{runGatewayAttest:()=>Ak,runGatewayMode:()=>Rk,runGatewayPolicy:()=>Ck});async function Rk(e){let t=e[0];if(t===void 0){let n=cn(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
235
+ `),0}var Bp=_(()=>{"use strict";ce();Ye();$p();s(Hp,"parseFlags");s(Up,"targets");s(Gp,"confirm");s(Wp,"loadConfig");s(Ok,"readFileSafeSync");s(Mk,"runGatewayInstall");s(Fk,"runGatewayUninstall")});var Vp={};q(Vp,{runGatewayAttest:()=>$k,runGatewayMode:()=>Lk,runGatewayPolicy:()=>Uk});async function Lk(e){let t=e[0];if(t===void 0){let n=cn(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
236
236
  `),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
237
- `),2):(await wp(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
237
+ `),2):(await Ap(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
238
238
  `:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
239
239
  `:`Convention policy is off; only explicit --deny-tool flags apply.
240
- `)),0)}async function Ak(e){let t=e[0];if(t===void 0){let n=Dr(),r=process.env.MAIND_GATEWAY_ATTEST!==void 0;return process.stdout.write(`maind: gateway attestation reports are ${n?"ON":"OFF"}${r?" (from MAIND_GATEWAY_ATTEST env)":""}.
240
+ `)),0)}async function $k(e){let t=e[0];if(t===void 0){let n=Dr(),r=process.env.MAIND_GATEWAY_ATTEST!==void 0;return process.stdout.write(`maind: gateway attestation reports are ${n?"ON":"OFF"}${r?" (from MAIND_GATEWAY_ATTEST env)":""}.
241
241
  `+(n?"":`maind: enable with 'gateway attest on' \u2014 reports observation windows (per-tool call/warn/deny COUNTERS, tool NAMES, convention citations, server label) to your maind account. Never tool arguments, results, paths, or prompts.
242
242
  `)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
243
- `),2):(await kp(t==="on"),process.stdout.write(t==="on"?`maind: attestation reports ON. Each gateway now reports observation windows (tool-name counters + convention citations \u2014 never arguments) to your maind account, at gateway end and every 30 min.
243
+ `),2):(await Tp(t==="on"),process.stdout.write(t==="on"?`maind: attestation reports ON. Each gateway now reports observation windows (tool-name counters + convention citations \u2014 never arguments) to your maind account, at gateway end and every 30 min.
244
244
  `:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
245
- `),0)}function Tk(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
245
+ `),0)}function jk(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
246
246
  `;let t="";for(let n of e){let r=n.servers===null?"*":n.servers.join(","),i=n.severity==="required"?"deny-capable":"warn-only";t+=` ${n.tool} [servers: ${r}] ${n.conventionId} v${n.conventionVersion} (${n.severity} \u2192 ${i})
247
- `}return t}function Ik(e,t=Date.now()){let n=Date.parse(e.cached_at);if(Number.isNaN(n))return"unknown age";let r=Math.floor((t-n)/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;let i=Math.floor(r/60);return i<24?`${i} h ago`:`${Math.floor(i/24)} d ago`}async function Ck(e){let t=e.includes("--refresh"),n=cn(),r=ln();if(t){let o=await Fr();o===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
247
+ `}return t}function Hk(e,t=Date.now()){let n=Date.parse(e.cached_at);if(Number.isNaN(n))return"unknown age";let r=Math.floor((t-n)/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;let i=Math.floor(r/60);return i<24?`${i} h ago`:`${Math.floor(i/24)} d ago`}async function Uk(e){let t=e.includes("--refresh"),n=cn(),r=ln();if(t){let o=await Fr();o===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
248
248
  `):(Or(r,o),process.stdout.write(`maind: policy refreshed (${o.length} rule(s)).
249
249
  `))}let i=Mr(r);return process.stdout.write(`maind: gateway mode '${n}'
250
250
  `),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
251
- `),0):(process.stdout.write(`maind: policy from cache (${Ik(i)}, ${r.mcpUrl}):
252
- `),process.stdout.write(Tk(i.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
253
- `),0)}var Hp=_(()=>{"use strict";ns();os();ss();s(Rk,"runGatewayMode");s(Ak,"runGatewayAttest");s(Tk,"renderRules");s(Ik,"cacheAge");s(Ck,"runGatewayPolicy")});var Bp={};q(Bp,{gatewayEventsFile:()=>Wp,parseGatewayArgs:()=>Kp,runGateway:()=>Lk});import{spawn as Nk}from"node:child_process";import{appendFile as Pk,mkdir as Dk}from"node:fs/promises";import{homedir as Up}from"node:os";import{basename as Ok,join as Gp}from"node:path";import{createInterface as Mk}from"node:readline";function Wp(){return Gp(Up(),".maind","gateway","events.jsonl")}async function Fk(e){try{let t=Wp();await Dk(Gp(Up(),".maind","gateway"),{recursive:!0}),await Pk(t,JSON.stringify(e)+`
254
- `,{mode:384})}catch{}}function Kp(e){let t=new Set,n=null,r=0;for(;r<e.length;){let i=e[r];if(i==="--deny-tool"){let o=e[r+1];if(!o)return null;t.add(o),r+=2;continue}if(i==="--label"){let o=e[r+1];if(!o)return null;n=o,r+=2;continue}if(i==="--"){let o=e[r+1];return o?{denyTools:t,label:n,command:o,args:e.slice(r+2)}:null}return null}return null}async function Lk(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:k,runGatewayUninstall:E}=await Promise.resolve().then(()=>($p(),Lp));return e[0]==="install"?k(e.slice(1)):E(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:k,runGatewayMode:E,runGatewayPolicy:R}=await Promise.resolve().then(()=>(Hp(),jp));return e[0]==="mode"?E(e.slice(1)):e[0]==="attest"?k(e.slice(1)):R(e.slice(1))}let t=Kp(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
251
+ `),0):(process.stdout.write(`maind: policy from cache (${Hk(i)}, ${r.mcpUrl}):
252
+ `),process.stdout.write(jk(i.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
253
+ `),0)}var qp=_(()=>{"use strict";as();ds();us();s(Lk,"runGatewayMode");s($k,"runGatewayAttest");s(jk,"renderRules");s(Hk,"cacheAge");s(Uk,"runGatewayPolicy")});var Qp={};q(Qp,{gatewayEventsFile:()=>Yp,parseGatewayArgs:()=>Xp,runGateway:()=>zk});import{spawn as Gk}from"node:child_process";import{appendFile as Wk,mkdir as Kk}from"node:fs/promises";import{homedir as zp}from"node:os";import{basename as Bk,join as Jp}from"node:path";import{createInterface as Vk}from"node:readline";function Yp(){return Jp(zp(),".maind","gateway","events.jsonl")}async function qk(e){try{let t=Yp();await Kk(Jp(zp(),".maind","gateway"),{recursive:!0}),await Wk(t,JSON.stringify(e)+`
254
+ `,{mode:384})}catch{}}function Xp(e){let t=new Set,n=null,r=0;for(;r<e.length;){let i=e[r];if(i==="--deny-tool"){let o=e[r+1];if(!o)return null;t.add(o),r+=2;continue}if(i==="--label"){let o=e[r+1];if(!o)return null;n=o,r+=2;continue}if(i==="--"){let o=e[r+1];return o?{denyTools:t,label:n,command:o,args:e.slice(r+2)}:null}return null}return null}async function zk(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:k,runGatewayUninstall:E}=await Promise.resolve().then(()=>(Bp(),Kp));return e[0]==="install"?k(e.slice(1)):E(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:k,runGatewayMode:E,runGatewayPolicy:R}=await Promise.resolve().then(()=>(qp(),Vp));return e[0]==="mode"?E(e.slice(1)):e[0]==="attest"?k(e.slice(1)):R(e.slice(1))}let t=Xp(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
255
255
  maind-mcp-bridge gateway install [--yes] [--dry-run]
256
256
  maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
257
257
  maind-mcp-bridge gateway mode [off|warn|enforce]
@@ -261,54 +261,54 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
261
261
  NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
262
262
  install/uninstall rewrite Claude Code MCP configs (consent per server).
263
263
  mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
264
- `),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r??Ok(i),c=cn(),l=vp(),u=l==="off"?null:un(),d=c==="off"?[]:Mr(ln())?.rules??[];c!=="off"&&Fr().then(k=>{k!==null&&(d=k,Or(ln(),k))}).catch(()=>{});let p=[],m=Dr()&&D()!==null&&c!=="off",f=null;try{f=O()}catch{f=null}let h=s(k=>{Fk(k),m&&p.push(k)},"record"),g=s(async()=>{if(!m)return;let k=hp(p.splice(0),c,a,f);k!==null&&(await ts(k)||await gp(k))},"attestAndReset");m&&yp().catch(()=>{});let y=setInterval(()=>{g()},30*6e4);y.unref();let b=Nk(i,o,{stdio:["pipe","pipe","inherit"]});b.stdout.pipe(process.stdout),b.on("error",k=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(k)}
265
- `),process.exitCode=1});let w=Mk({input:process.stdin,terminal:!1});w.on("line",k=>{let E=ks(k);if(E.kind==="request"&&E.method==="tools/call"&&E.toolName){if(n.has(E.toolName)&&E.id!==void 0){process.stdout.write(Be(E.id,E.toolName)+`
266
- `),h($r("deny",a,E.toolName,Date.now()));return}let R=xp(E.toolName,a,d,c);if(R.kind==="deny"&&E.id!==void 0){process.stdout.write(Be(E.id,E.toolName,Rp(E.toolName,R.rule))+`
267
- `),h(jr("policy_deny",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));return}(R.kind==="warn"||R.kind==="deny")&&h(jr("policy_warn",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));let I=pn(k,u);if(I.length>0){let T=I.find(N=>N.verdict==="fabricated");if(T!==void 0&&l==="enforce"&&c==="enforce"&&E.id!==void 0&&T!==void 0&&E.id!==void 0){process.stdout.write(Be(E.id,E.toolName,Ve(T,!0))+`
268
- `),h(Hr("sha_deny",a,E.toolName,Date.now()));return}let j=T??I[0];process.stderr.write(`[maind gateway] ${Ve(j,!1)}
264
+ `),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r??Bk(i),c=cn(),l=Ip(),p=l==="off"?null:un(),d=c==="off"?[]:Mr(ln())?.rules??[];c!=="off"&&Fr().then(k=>{k!==null&&(d=k,Or(ln(),k))}).catch(()=>{});let u=[],f=Dr()&&O()!==null&&c!=="off",m=null;try{m=M()}catch{m=null}let h=s(k=>{qk(k),f&&u.push(k)},"record"),g=s(async()=>{if(!f)return;let k=vp(u.splice(0),c,a,m);k!==null&&(await ss(k)||await Sp(k))},"attestAndReset");f&&Ep().catch(()=>{});let y=setInterval(()=>{g()},30*6e4);y.unref();let b=Gk(i,o,{stdio:["pipe","pipe","inherit"]});b.stdout.pipe(process.stdout),b.on("error",k=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(k)}
265
+ `),process.exitCode=1});let w=Vk({input:process.stdin,terminal:!1});w.on("line",k=>{let E=Rs(k);if(E.kind==="request"&&E.method==="tools/call"&&E.toolName){if(n.has(E.toolName)&&E.id!==void 0){process.stdout.write(Be(E.id,E.toolName)+`
266
+ `),h($r("deny",a,E.toolName,Date.now()));return}let R=Pp(E.toolName,a,d,c);if(R.kind==="deny"&&E.id!==void 0){process.stdout.write(Be(E.id,E.toolName,Dp(E.toolName,R.rule))+`
267
+ `),h(jr("policy_deny",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));return}(R.kind==="warn"||R.kind==="deny")&&h(jr("policy_warn",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));let I=pn(k,p);if(I.length>0){let T=I.find(N=>N.verdict==="fabricated");if(T!==void 0&&l==="enforce"&&c==="enforce"&&E.id!==void 0&&T!==void 0&&E.id!==void 0){process.stdout.write(Be(E.id,E.toolName,Ve(T,!0))+`
268
+ `),h(Hr("sha_deny",a,E.toolName,Date.now()));return}let A=T??I[0];process.stderr.write(`[maind gateway] ${Ve(A,!1)}
269
269
  `),h(Hr("sha_warn",a,E.toolName,Date.now()))}h($r("tool_call",a,E.toolName,Date.now()))}b.stdin.write(k+`
270
- `)}),w.on("close",()=>{b.stdin.end()});let v=await new Promise(k=>{b.on("exit",(E,R)=>{k(E??(R?1:0))})});return clearInterval(y),await g(),v}var Vp=_(()=>{"use strict";Ur();bp();ns();rs();Gr();os();ss();B();ge();s(Wp,"gatewayEventsFile");s(Fk,"logEvent");s(Kp,"parseGatewayArgs");s(Lk,"runGateway")});var fs={};q(fs,{MAX_ENTRIES:()=>as,TTL_MS:()=>ds,crossSessionDir:()=>us,decideCrossSession:()=>Jp,parseSessionDb:()=>zp,pruneDb:()=>ps,runGuardCrossCheck:()=>Vk,runGuardCrossObserve:()=>Bk,staleReason:()=>cs});import{mkdir as $k,readFile as jk,readdir as Hk,stat as qp,unlink as Uk,writeFile as Gk}from"node:fs/promises";import{homedir as Wk}from"node:os";import{join as ls}from"node:path";function us(){return ls(Wk(),".maind","cross-session")}function zp(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[o,a]of Object.entries(n.files)){if(typeof a!="object"||a===null)continue;let c=a;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[o]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[o,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(i[o]=a);return{files:r,warned:i}}function ps(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=ds);return n.length>as&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-as)),{files:Object.fromEntries(n),warned:e.warned}}function Jp(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function cs(e,t){return`Cross-session guard: '${e}' changed on disk after this session last read it (mtime ${Math.floor(t.current/1e3)} > recorded ${Math.floor(t.baseline/1e3)}). Likely a parallel session, an editor, or git (checkout/pull). Re-read the file, reconcile with the external change, then retry.`}async function Yp(e){let t=us();return await $k(t,{recursive:!0}),ls(t,`${e}.json`)}async function Xp(e,t){try{let n=await jk(await Yp(e),"utf8");return ps(zp(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function Qp(e,t){try{await Gk(await Yp(e),JSON.stringify(t),{mode:384})}catch{}}async function Kk(e){try{let t=us();for(let n of await Hk(t)){if(!n.endsWith(".json"))continue;let r=ls(t,n),i=await qp(r).catch(()=>null);i&&e-i.mtimeMs>ds&&await Uk(r).catch(()=>{})}}catch{}}async function Zp(e){try{return(await qp(e)).mtimeMs}catch{return}}async function Bk(e,t=Date.now()){try{if(Q().mode==="off")return 0;let r=e??await C(),i=typeof r.session_id=="string"?r.session_id:"",o=ie(r);if(!i||!o)return 0;let a=await Zp(o);if(a===void 0)return 0;let c=await Xp(i,t);return c.files[o]={m:a,t},delete c.warned[o],await Qp(i,ps(c,t)),await Kk(t),0}catch{return 0}}async function Vk(e,t=Date.now()){try{let n=Q();if(n.mode==="off")return 0;let r=e??await C(),i=typeof r.session_id=="string"?r.session_id:"",o=ie(r);if(!i||!o)return 0;let a=await Xp(i,t),c=Jp(a.files[o]?.m,await Zp(o));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(wt(cs(o,c))+`
271
- `),await V({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o}),0):(a.warned[o]===c.current||(process.stdout.write(ve(cs(o,c))+`
272
- `),a.warned[o]=c.current,await Qp(i,a),await V({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o})),0)}catch{return 0}}var ds,as,ms=_(()=>{"use strict";oe();kt();Ge();Rt();ds=48*3600*1e3,as=500;s(us,"crossSessionDir");s(zp,"parseSessionDb");s(ps,"pruneDb");s(Jp,"decideCrossSession");s(cs,"staleReason");s(Yp,"dbPath");s(Xp,"loadDb");s(Qp,"saveDb");s(Kk,"sweepStaleSessionFiles");s(Zp,"fileMtime");s(Bk,"runGuardCrossObserve");s(Vk,"runGuardCrossCheck")});var gs={};q(gs,{INDEX_REFRESH_WORKER:()=>nf,acquireLock:()=>of,releaseLock:()=>hs,runIndexRefreshWorker:()=>ev,runOnIndexRefresh:()=>Zk});import{spawn as qk}from"node:child_process";import{existsSync as zk,mkdirSync as Jk,rmdirSync as ef,statSync as Yk}from"node:fs";import{join as tf}from"node:path";function rf(e){return tf(e,".maind","index-refresh.lock")}function Qk(e){return tf(e,".maind","code-index.sqlite")}function of(e,t=Date.now()){let n=rf(e);try{if(t-Yk(n).mtimeMs<Xk)return!1;ef(n)}catch{}try{return Jk(n,{recursive:!1}),!0}catch{return!1}}function hs(e){try{ef(rf(e))}catch{}}async function Zk(){try{let e=await C(),t=z(typeof e.cwd=="string"?e.cwd:process.cwd());if(!zk(Qk(t))||!of(t))return 0;let n=process.argv[1];if(n===void 0)return hs(t),0;qk(process.execPath,[n,nf,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function ev(){let e=process.argv[3]??z();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(yo(),kl)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{hs(e)}return 0}var Xk,nf,ys=_(()=>{"use strict";oe();Xt();Xk=30*6e4,nf="index-refresh-run";s(rf,"lockPath");s(Qk,"indexDbPath");s(of,"acquireLock");s(hs,"releaseLock");s(Zk,"runOnIndexRefresh");s(ev,"runIndexRefreshWorker")});import{randomUUID as tv}from"node:crypto";import{createInterface as xf}from"node:readline";var sf=[["claude-code","claude-code"],["claude-cli","claude-code"],["claude-desktop","claude-desktop"],["claude.app","claude-desktop"],["openai-codex","codex"],["codex-cli","codex"],["codex","codex"],["github-copilot","copilot"],["vscode-copilot","copilot"],["copilot","copilot"],["cursor","cursor"],["windsurf","windsurf"],["codeium","windsurf"],["vscode-extension","vscode-extension"],["maind-vscode","vscode-extension"],["mcp-inspector","mcp-inspector"],["maind-cli","maind-cli"],["maind-mcp-bridge","mcp-bridge"]];function af(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of sf)if(t.includes(n))return r;return null}s(af,"mapClientInfoNameToFamily");function ws(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Lr(t)||t.method!=="initialize")return null;let n=t.params;if(!Lr(n))return null;let r=n.clientInfo;if(!Lr(r))return null;let i=r.name,o=af(typeof i=="string"?i:null);if(o===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:o,version:c}}s(ws,"tryExtractInitializeClient");function Lr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Lr,"isRecord");Ur();Gr();qe();var Rf="https://mcp.maind.dev/mcp",At=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},bn=class{static{s(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;presenceFrameId=0;sessionId=null;shaRepoRoot;initFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=fn(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=Af(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=Tf(r),this.clientVersionLocked=this.clientVersion!==null;let i=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=i&&/^[a-f0-9]{64}$/.test(i)?i:null,this.localRouter=t.localRouter??null,this.presence=t.presence??null,this.shaRepoRoot=un(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??Rf}async run(){let t=xf({input:process.stdin,crlfDelay:1/0});for await(let n of t){if(this.terminated)return;let r=n.trim();r.length!==0&&await this.forwardFrame(r)}}async forwardFrame(t,n=!1){if(!this.clientFamilyLocked&&this.clientFamily===null){let d=ws(t);d!==null&&(this.clientFamily=d.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=d.version))}this.initFrame===null&&gn(t)&&(this.initFrame=t);let r=Nf(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let d=pn(t,this.shaRepoRoot);if(d.length>0){let p=d.find(f=>f.verdict==="fabricated"),m=p??d[0];if(p!==void 0&&xs(p)&&r.id!==null){let f=Ve(p,!0);process.stderr.write(`[maind] ${f}
273
- `);let h=r.params?.name;process.stdout.write(Be(r.id,typeof h=="string"?h:"unknown",f)+`
274
- `);return}i=Ve(m,!1),process.stderr.write(`[maind] ${i}
270
+ `)}),w.on("close",()=>{b.stdin.end()});let v=await new Promise(k=>{b.on("exit",(E,R)=>{k(E??(R?1:0))})});return clearInterval(y),await g(),v}var Zp=_(()=>{"use strict";Ur();xp();as();cs();Gr();ds();us();B();ge();s(Yp,"gatewayEventsFile");s(qk,"logEvent");s(Xp,"parseGatewayArgs");s(zk,"runGateway")});var bs={};q(bs,{MAX_ENTRIES:()=>ps,TTL_MS:()=>hs,crossSessionDir:()=>gs,decideCrossSession:()=>nf,parseSessionDb:()=>tf,pruneDb:()=>ys,runGuardCrossCheck:()=>rv,runGuardCrossObserve:()=>nv,staleReason:()=>fs});import{mkdir as Jk,readFile as Yk,readdir as Xk,stat as ef,unlink as Qk,writeFile as Zk}from"node:fs/promises";import{homedir as ev}from"node:os";import{join as ms}from"node:path";function gs(){return ms(ev(),".maind","cross-session")}function tf(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[o,a]of Object.entries(n.files)){if(typeof a!="object"||a===null)continue;let c=a;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[o]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[o,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(i[o]=a);return{files:r,warned:i}}function ys(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=hs);return n.length>ps&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-ps)),{files:Object.fromEntries(n),warned:e.warned}}function nf(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function fs(e,t){return`Cross-session guard: '${e}' changed on disk after this session last read it (mtime ${Math.floor(t.current/1e3)} > recorded ${Math.floor(t.baseline/1e3)}). Likely a parallel session, an editor, or git (checkout/pull). Re-read the file, reconcile with the external change, then retry.`}async function rf(e){let t=gs();return await Jk(t,{recursive:!0}),ms(t,`${e}.json`)}async function of(e,t){try{let n=await Yk(await rf(e),"utf8");return ys(tf(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function sf(e,t){try{await Zk(await rf(e),JSON.stringify(t),{mode:384})}catch{}}async function tv(e){try{let t=gs();for(let n of await Xk(t)){if(!n.endsWith(".json"))continue;let r=ms(t,n),i=await ef(r).catch(()=>null);i&&e-i.mtimeMs>hs&&await Qk(r).catch(()=>{})}}catch{}}async function af(e){try{return(await ef(e)).mtimeMs}catch{return}}async function nv(e,t=Date.now()){try{if(Q().mode==="off")return 0;let r=e??await C(),i=typeof r.session_id=="string"?r.session_id:"",o=ie(r);if(!i||!o)return 0;let a=await af(o);if(a===void 0)return 0;let c=await of(i,t);return c.files[o]={m:a,t},delete c.warned[o],await sf(i,ys(c,t)),await tv(t),0}catch{return 0}}async function rv(e,t=Date.now()){try{let n=Q();if(n.mode==="off")return 0;let r=e??await C(),i=typeof r.session_id=="string"?r.session_id:"",o=ie(r);if(!i||!o)return 0;let a=await of(i,t),c=nf(a.files[o]?.m,await af(o));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(wt(fs(o,c))+`
271
+ `),await V({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o}),0):(a.warned[o]===c.current||(process.stdout.write(ve(fs(o,c))+`
272
+ `),a.warned[o]=c.current,await sf(i,a),await V({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o})),0)}catch{return 0}}var hs,ps,_s=_(()=>{"use strict";oe();kt();Ge();Rt();hs=48*3600*1e3,ps=500;s(gs,"crossSessionDir");s(tf,"parseSessionDb");s(ys,"pruneDb");s(nf,"decideCrossSession");s(fs,"staleReason");s(rf,"dbPath");s(of,"loadDb");s(sf,"saveDb");s(tv,"sweepStaleSessionFiles");s(af,"fileMtime");s(nv,"runGuardCrossObserve");s(rv,"runGuardCrossCheck")});var ks={};q(ks,{INDEX_REFRESH_WORKER:()=>df,acquireLock:()=>pf,releaseLock:()=>ws,runIndexRefreshWorker:()=>uv,runOnIndexRefresh:()=>dv});import{spawn as iv}from"node:child_process";import{existsSync as ov,mkdirSync as sv,rmdirSync as cf,statSync as av}from"node:fs";import{join as lf}from"node:path";function uf(e){return lf(e,".maind","index-refresh.lock")}function lv(e){return lf(e,".maind","code-index.sqlite")}function pf(e,t=Date.now()){let n=uf(e);try{if(t-av(n).mtimeMs<cv)return!1;cf(n)}catch{}try{return sv(n,{recursive:!1}),!0}catch{return!1}}function ws(e){try{cf(uf(e))}catch{}}async function dv(){try{let e=await C(),t=z(typeof e.cwd=="string"?e.cwd:process.cwd());if(!ov(lv(t))||!pf(t))return 0;let n=process.argv[1];if(n===void 0)return ws(t),0;iv(process.execPath,[n,df,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function uv(){let e=process.argv[3]??z();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(bo(),Rl)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{ws(e)}return 0}var cv,df,vs=_(()=>{"use strict";oe();Xt();cv=30*6e4,df="index-refresh-run";s(uf,"lockPath");s(lv,"indexDbPath");s(pf,"acquireLock");s(ws,"releaseLock");s(dv,"runOnIndexRefresh");s(uv,"runIndexRefreshWorker")});import{randomUUID as pv}from"node:crypto";import{createInterface as Pf}from"node:readline";var ff=[["claude-code","claude-code"],["claude-cli","claude-code"],["claude-desktop","claude-desktop"],["claude.app","claude-desktop"],["openai-codex","codex"],["codex-cli","codex"],["codex","codex"],["github-copilot","copilot"],["vscode-copilot","copilot"],["copilot","copilot"],["cursor","cursor"],["windsurf","windsurf"],["codeium","windsurf"],["vscode-extension","vscode-extension"],["maind-vscode","vscode-extension"],["mcp-inspector","mcp-inspector"],["maind-cli","maind-cli"],["maind-mcp-bridge","mcp-bridge"]];function mf(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of ff)if(t.includes(n))return r;return null}s(mf,"mapClientInfoNameToFamily");function xs(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Lr(t)||t.method!=="initialize")return null;let n=t.params;if(!Lr(n))return null;let r=n.clientInfo;if(!Lr(r))return null;let i=r.name,o=mf(typeof i=="string"?i:null);if(o===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:o,version:c}}s(xs,"tryExtractInitializeClient");function Lr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Lr,"isRecord");Ur();Gr();qe();var Df="https://mcp.maind.dev/mcp",At=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},bn=class{static{s(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;presenceFrameId=0;sessionId=null;shaRepoRoot;initFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=fn(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=Of(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=Mf(r),this.clientVersionLocked=this.clientVersion!==null;let i=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=i&&/^[a-f0-9]{64}$/.test(i)?i:null,this.localRouter=t.localRouter??null,this.presence=t.presence??null,this.shaRepoRoot=un(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??Df}async run(){let t=Pf({input:process.stdin,crlfDelay:1/0});for await(let n of t){if(this.terminated)return;let r=n.trim();r.length!==0&&await this.forwardFrame(r)}}async forwardFrame(t,n=!1){if(!this.clientFamilyLocked&&this.clientFamily===null){let d=xs(t);d!==null&&(this.clientFamily=d.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=d.version))}this.initFrame===null&&gn(t)&&(this.initFrame=t);let r=$f(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let d=pn(t,this.shaRepoRoot);if(d.length>0){let u=d.find(m=>m.verdict==="fabricated"),f=u??d[0];if(u!==void 0&&Cs(u)&&r.id!==null){let m=Ve(u,!0);process.stderr.write(`[maind] ${m}
273
+ `);let h=r.params?.name;process.stdout.write(Be(r.id,typeof h=="string"?h:"unknown",m)+`
274
+ `);return}i=Ve(f,!1),process.stderr.write(`[maind] ${i}
275
275
  `)}}if(this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let d=await this.localRouter.handleToolCall(r?.id??null,r?.params);process.stdout.write(d+`
276
- `);return}let o=this.localRouter!==null&&r?.method==="tools/list",a=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:a,body:t})}catch(d){let p=hn(t);if(this.serveInitializeFromCache(t,p))return;yn(p,-32603,`bridge network error: ${Df(d)}`);return}let l=c.headers.get("mcp-session-id");if(l&&l!==this.sessionId&&(this.sessionId=l),c.status===401){await this.handle401(c,t);return}if(c.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!gn(t)){let d=await c.text().catch(()=>"");if(Pf(d)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=hn(t);yn(p,-32603,`bridge upstream error (HTTP 404): ${d.slice(0,500)}`);return}if(!c.ok){let d=hn(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,d))return;yn(d,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let u=c.headers.get("content-type")??"";if(o&&this.localRouter){let d=u.startsWith("text/event-stream")?await Kr(c):await c.text(),p=this.localRouter.augmentToolsList(d);p.trim().length>0&&process.stdout.write(p+`
277
- `);return}if(gn(t)){let d=u.startsWith("text/event-stream")?await Kr(c):await c.text();this.cacheInitializeResult(d),this.presence?.onSessionReady(),d.trim().length>0&&process.stdout.write(d+`
278
- `);return}if(i!==null){let d=u.startsWith("text/event-stream")?await Kr(c):await c.text(),p=Cf(d,i);p.trim().length>0&&process.stdout.write(p+`
279
- `);return}if(u.startsWith("text/event-stream"))await If(c);else{if(c.status===202)return;{let d=await c.text();d.trim().length>0&&process.stdout.write(d+`
280
- `)}}}async handle401(t,n){let r=await t.text().catch(()=>""),i=r.toLowerCase();if(i.includes("device_mismatch")||i.includes("device_revoked")||i.includes("device_required")||i.includes("invalid or revoked"))throw this.terminated=!0,new At(Of(i));let a=hn(n);yn(a,-32001,`bridge auth error: ${r.slice(0,200)}`)}async postPresenceToolCall(t,n){if(this.sessionId===null)throw new Error("presence: no MCP session established yet");this.presenceFrameId+=1;let r=JSON.stringify({jsonrpc:"2.0",id:`maind-presence-${this.presenceFrameId}`,method:"tools/call",params:{name:t,arguments:n}}),i=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),o=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return Mf(o)}buildHeaders(t){let n={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${this.apiKey}`,"x-maind-device-id":this.deviceId,"x-maind-bridge-version":this.bridgeVersion};return this.clientFamily!==null&&(n["x-maind-client-family"]=this.clientFamily),this.clientVersion!==null&&(n["x-maind-client-version"]=this.clientVersion),this.projectKey!==null&&(n["x-maind-project-key"]=this.projectKey),t&&this.sessionId!==null&&(n["mcp-session-id"]=this.sessionId),n}async recoverSession(){if(this.initFrame===null)return!1;this.sessionId=null;let t;try{t=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!1),body:this.initFrame})}catch{return!1}let n=t.headers.get("mcp-session-id");if(await t.text().catch(()=>""),!t.ok||!n)return!1;this.sessionId=n;try{await(await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})})).text().catch(()=>"")}catch{}return!0}getRepoRoot(){return this.repoRoot===null&&(this.repoRoot=ae()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&Is(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!gn(t))return!1;let r=Cs(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(Ns(n,r)+`
281
- `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${mn(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Af(e){if(e===null)return null;let t=e.trim().toLowerCase();return t.length===0?null:new Set(["claude-code","codex","copilot","cursor","windsurf","mcp-bridge","vscode-extension","claude-desktop","mcp-inspector"]).has(t)?t:null}s(Af,"normalizeClientFamily");function Tf(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(Tf,"normalizeClientVersion");async function If(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=s(()=>{if(i.length===0)return;let a=i.join(`
276
+ `);return}let o=this.localRouter!==null&&r?.method==="tools/list",a=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:a,body:t})}catch(d){let u=hn(t);if(this.serveInitializeFromCache(t,u))return;yn(u,-32603,`bridge network error: ${Hf(d)}`);return}let l=c.headers.get("mcp-session-id");if(l&&l!==this.sessionId&&(this.sessionId=l),c.status===401){await this.handle401(c,t);return}if(c.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!gn(t)){let d=await c.text().catch(()=>"");if(jf(d)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let u=hn(t);yn(u,-32603,`bridge upstream error (HTTP 404): ${d.slice(0,500)}`);return}if(!c.ok){let d=hn(t),u=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,d))return;yn(d,-32603,`bridge upstream error (HTTP ${c.status}): ${u.slice(0,500)}`);return}let p=c.headers.get("content-type")??"";if(o&&this.localRouter){let d=p.startsWith("text/event-stream")?await Kr(c):await c.text(),u=this.localRouter.augmentToolsList(d);u.trim().length>0&&process.stdout.write(u+`
277
+ `);return}if(gn(t)){let d=p.startsWith("text/event-stream")?await Kr(c):await c.text();this.cacheInitializeResult(d),this.presence?.onSessionReady(),d.trim().length>0&&process.stdout.write(d+`
278
+ `);return}if(i!==null){let d=p.startsWith("text/event-stream")?await Kr(c):await c.text(),u=Lf(d,i);u.trim().length>0&&process.stdout.write(u+`
279
+ `);return}if(p.startsWith("text/event-stream"))await Ff(c);else{if(c.status===202)return;{let d=await c.text();d.trim().length>0&&process.stdout.write(d+`
280
+ `)}}}async handle401(t,n){let r=await t.text().catch(()=>""),i=r.toLowerCase();if(i.includes("device_mismatch")||i.includes("device_revoked")||i.includes("device_required")||i.includes("invalid or revoked"))throw this.terminated=!0,new At(Uf(i));let a=hn(n);yn(a,-32001,`bridge auth error: ${r.slice(0,200)}`)}async postPresenceToolCall(t,n){if(this.sessionId===null)throw new Error("presence: no MCP session established yet");this.presenceFrameId+=1;let r=JSON.stringify({jsonrpc:"2.0",id:`maind-presence-${this.presenceFrameId}`,method:"tools/call",params:{name:t,arguments:n}}),i=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),o=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return Gf(o)}buildHeaders(t){let n={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${this.apiKey}`,"x-maind-device-id":this.deviceId,"x-maind-bridge-version":this.bridgeVersion};return this.clientFamily!==null&&(n["x-maind-client-family"]=this.clientFamily),this.clientVersion!==null&&(n["x-maind-client-version"]=this.clientVersion),this.projectKey!==null&&(n["x-maind-project-key"]=this.projectKey),t&&this.sessionId!==null&&(n["mcp-session-id"]=this.sessionId),n}async recoverSession(){if(this.initFrame===null)return!1;this.sessionId=null;let t;try{t=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!1),body:this.initFrame})}catch{return!1}let n=t.headers.get("mcp-session-id");if(await t.text().catch(()=>""),!t.ok||!n)return!1;this.sessionId=n;try{await(await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})})).text().catch(()=>"")}catch{}return!0}getRepoRoot(){return this.repoRoot===null&&(this.repoRoot=ae()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&Os(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!gn(t))return!1;let r=Ms(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(Fs(n,r)+`
281
+ `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${mn(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Of(e){if(e===null)return null;let t=e.trim().toLowerCase();return t.length===0?null:new Set(["claude-code","codex","copilot","cursor","windsurf","mcp-bridge","vscode-extension","claude-desktop","mcp-inspector"]).has(t)?t:null}s(Of,"normalizeClientFamily");function Mf(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(Mf,"normalizeClientVersion");async function Ff(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=s(()=>{if(i.length===0)return;let a=i.join(`
282
282
  `).trim();i=[],a.length>0&&process.stdout.write(a+`
283
283
  `)},"flushEvent");try{for(;;){let{value:a,done:c}=await t.read();if(c)break;r+=n.decode(a,{stream:!0});let l;for(;(l=r.indexOf(`
284
- `))!==-1;){let u=r.slice(0,l);r=r.slice(l+1);let d=u.endsWith("\r")?u.slice(0,-1):u;if(d===""){o();continue}d.startsWith(":")||d.startsWith("data:")&&i.push(d.slice(5).replace(/^\s/,""))}}}finally{o()}}s(If,"pipeSseToStdout");function Cf(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return e;let r=n.result;return typeof r!="object"||r===null||!Array.isArray(r.content)?e:(r.content.push({type:"text",text:`[maind] ${t}`}),JSON.stringify(n))}catch{return e}}s(Cf,"appendNoteToToolResult");function Nf(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(Nf,"parseRpc");async function Kr(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=[],a=s(()=>{if(o.length===0)return;let c=o.join(`
285
- `).trim();o=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let u;for(;(u=r.indexOf(`
286
- `))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let p=d.endsWith("\r")?d.slice(0,-1):d;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&o.push(p.slice(5).replace(/^\s/,""))}}}finally{a()}return i.join(`
287
- `)}s(Kr,"collectSseText");function hn(e){try{return JSON.parse(e).id??null}catch{return null}}s(hn,"tryExtractId");function gn(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(gn,"isInitializeRequest");function Pf(e){let t=e.toLowerCase();return t.includes("session not found")||t.includes("session expired")||t.includes("no valid session")||t.includes("reinitialize")||t.includes("session")&&t.includes("expired")}s(Pf,"isSessionLossBody");function Df(e){return e instanceof Error?e.message:String(e)}s(Df,"stringifyErr");function yn(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
288
- `)}s(yn,"emitJsonRpcError");function Of(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(Of,"extractHint");function Mf(e){try{let t=e.trim();if(t.length===0)return null;let n=t;if(!t.startsWith("{")){let o=t.split(`
289
- `).map(a=>a.trim()).filter(a=>a.startsWith("data:"));if(o.length===0)return null;n=o[o.length-1].slice(5).trim()}let i=JSON.parse(n).result?.content?.[0]?.text;return typeof i!="string"?null:JSON.parse(i)}catch{return null}}s(Mf,"parsePresenceToolResult");B();B();import{spawn as Bf}from"node:child_process";import{platform as Vf}from"node:os";var qf="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function zf(){let e=process.env.MAIND_FUNCTIONS_ORIGIN;return e&&e.length>0?e.replace(/\/+$/,""):qf}s(zf,"functionsOrigin");async function ze(e,t=process.stderr){let n=zf(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,o=wn(e),a=`mcp-bridge-${o.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:o})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await Qf(l.verification_uri_complete).catch(()=>{}),Xf(l,t);let u=Date.now()+l.expires_in*1e3,d=Math.max(l.interval,3)*1e3;for(;Date.now()<u;){await Yf(d);let p=await Jf(i,l.device_code).catch(m=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(m)}
290
- `),null));if(p){if(p.status==="approved")return Ee(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
291
- `),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
292
- `),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
284
+ `))!==-1;){let p=r.slice(0,l);r=r.slice(l+1);let d=p.endsWith("\r")?p.slice(0,-1):p;if(d===""){o();continue}d.startsWith(":")||d.startsWith("data:")&&i.push(d.slice(5).replace(/^\s/,""))}}}finally{o()}}s(Ff,"pipeSseToStdout");function Lf(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return e;let r=n.result;return typeof r!="object"||r===null||!Array.isArray(r.content)?e:(r.content.push({type:"text",text:`[maind] ${t}`}),JSON.stringify(n))}catch{return e}}s(Lf,"appendNoteToToolResult");function $f(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s($f,"parseRpc");async function Kr(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=[],a=s(()=>{if(o.length===0)return;let c=o.join(`
285
+ `).trim();o=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let p;for(;(p=r.indexOf(`
286
+ `))!==-1;){let d=r.slice(0,p);r=r.slice(p+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){a();continue}u.startsWith(":")||u.startsWith("data:")&&o.push(u.slice(5).replace(/^\s/,""))}}}finally{a()}return i.join(`
287
+ `)}s(Kr,"collectSseText");function hn(e){try{return JSON.parse(e).id??null}catch{return null}}s(hn,"tryExtractId");function gn(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(gn,"isInitializeRequest");function jf(e){let t=e.toLowerCase();return t.includes("session not found")||t.includes("session expired")||t.includes("no valid session")||t.includes("reinitialize")||t.includes("session")&&t.includes("expired")}s(jf,"isSessionLossBody");function Hf(e){return e instanceof Error?e.message:String(e)}s(Hf,"stringifyErr");function yn(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
288
+ `)}s(yn,"emitJsonRpcError");function Uf(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(Uf,"extractHint");function Gf(e){try{let t=e.trim();if(t.length===0)return null;let n=t;if(!t.startsWith("{")){let o=t.split(`
289
+ `).map(a=>a.trim()).filter(a=>a.startsWith("data:"));if(o.length===0)return null;n=o[o.length-1].slice(5).trim()}let i=JSON.parse(n).result?.content?.[0]?.text;return typeof i!="string"?null:JSON.parse(i)}catch{return null}}s(Gf,"parsePresenceToolResult");B();B();import{spawn as Qf}from"node:child_process";import{platform as Zf}from"node:os";var em="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function tm(){let e=process.env.MAIND_FUNCTIONS_ORIGIN;return e&&e.length>0?e.replace(/\/+$/,""):em}s(tm,"functionsOrigin");async function ze(e,t=process.stderr){let n=tm(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,o=wn(e),a=`mcp-bridge-${o.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:o})});if(!c.ok){let u=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${u}`)}let l=await c.json();await om(l.verification_uri_complete).catch(()=>{}),im(l,t);let p=Date.now()+l.expires_in*1e3,d=Math.max(l.interval,3)*1e3;for(;Date.now()<p;){await rm(d);let u=await nm(i,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
290
+ `),null));if(u){if(u.status==="approved")return Ee(u.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${u.plan}). API key saved to ~/.config/maind/api-key
291
+ `),{apiKey:u.api_key,plan:u.plan};if(u.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
292
+ `),null;if(u.status==="expired"||u.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${u.status}
293
293
  `),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
294
- `),null}s(ze,"runDeviceFlow");async function Jf(e,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:t})});if(!n.ok){let r=await n.text();throw new Error(`poll ${n.status}: ${r}`)}return await n.json()}s(Jf,"pollOnce");function Yf(e){return new Promise(t=>setTimeout(t,e))}s(Yf,"sleep");function Xf(e,t){let n=[""," \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"," \u2502 \u2502"," \u2502 maind-mcp-bridge \u2014 first-time setup \u2502"," \u2502 \u2502"," \u2502 Approve this bridge to bind it to your maind account: \u2502"," \u2502 \u2502",` \u2502 Open: ${Fs(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Fs(e.user_code,56)} \u2502`," \u2502 \u2502",` \u2502 (expires in ${Math.round(e.expires_in/60)} minutes)`.padEnd(67)+"\u2502"," \u2502 \u2502"," \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",""];t.write(n.join(`
294
+ `),null}s(ze,"runDeviceFlow");async function nm(e,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:t})});if(!n.ok){let r=await n.text();throw new Error(`poll ${n.status}: ${r}`)}return await n.json()}s(nm,"pollOnce");function rm(e){return new Promise(t=>setTimeout(t,e))}s(rm,"sleep");function im(e,t){let n=[""," \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"," \u2502 \u2502"," \u2502 maind-mcp-bridge \u2014 first-time setup \u2502"," \u2502 \u2502"," \u2502 Approve this bridge to bind it to your maind account: \u2502"," \u2502 \u2502",` \u2502 Open: ${Us(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Us(e.user_code,56)} \u2502`," \u2502 \u2502",` \u2502 (expires in ${Math.round(e.expires_in/60)} minutes)`.padEnd(67)+"\u2502"," \u2502 \u2502"," \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",""];t.write(n.join(`
295
295
  `)+`
296
- `)}s(Xf,"printAuthInstructions");function Fs(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}s(Fs,"pad");async function Qf(e){let t,n;switch(Vf()){case"darwin":t="open",n=[e];break;case"win32":t="cmd",n=["/c","start","",e];break;default:t="xdg-open",n=[e];break}return new Promise((r,i)=>{try{let o=Bf(t,n,{stdio:"ignore",detached:!0});o.on("error",i),o.unref(),r()}catch(o){i(o)}})}s(Qf,"openExternalBrowser");xe();ge();xe();import*as Ol from"node:os";function Ls(e){let t={projectRoot:null,full:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--no-preamble":t.noPreamble=!0;break;case"--no-hook":t.noHook=!0;break;case"--non-interactive":t.nonInteractive=!0;break;case"--telemetry":t.telemetry=!0;break;case"--skip-codex":t.skipCodex=!0;break;case"--dry-run":t.dryRun=!0;break;case"--auto-working-paths":t.autoWorkingPaths=!0;break;case"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--project-root requires a path argument");t.projectRoot=i,n++;break}case"--token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--token requires a token argument");t.token=i,n++;break}case"--one-click-token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--one-click-token requires a token argument");t.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=i,n++;break}case"--client":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--client requires a family argument (e.g. claude-code, cursor, windsurf, copilot, codex, claude-desktop)");t.client=i,n++;break}default:throw new Z(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}s(Ls,"parseInstallFlags");var Z=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function $s(){let e=["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Detects your project root, pairs this device with MAIND, merges the","MCP-server entry into every supported AI-client config it finds, and","(optionally) writes the MAIND preamble block into CLAUDE.md / AGENTS.md /","Cursor / Windsurf / Copilot files. Idempotent \u2014 re-running is safe.","","Usage:"," npx -y @maind-dev/mcp-bridge install [flags]","","Common flags:"," --project-root <path> Override project-root detection (default: walk up from cwd)"," --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)"," --no-preamble Skip the 5 preamble files (MCP-config + pairing only)"," --no-hook Never write the Claude Code hooks (overrides --full for hooks)"," --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)"," --token <key> Use a pre-issued mnd_ api-key instead of browser pairing"," --one-click-token <jwt> Exchange the dashboard one-click token for a device-bound"," key \u2014 no browser (needs --one-click-exchange-url; ADR-267)"," --one-click-exchange-url <url> Exchange endpoint (set by the launcher scripts)"," --client <family> Install only for one client family (claude-code, cursor, ...)"," --skip-codex Skip the Codex ~/.codex/config.toml target",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --telemetry Opt-in: post anonymous install_completed event"," -h, --help Show this help text","","Examples:"," npx -y @maind-dev/mcp-bridge install # interactive default"," npx -y @maind-dev/mcp-bridge install --dry-run # preview without writing anything"," npx -y @maind-dev/mcp-bridge install --full --telemetry # full setup, opt-in telemetry"," npx -y @maind-dev/mcp-bridge install --client cursor # only Cursor target","","After it finishes, restart your MCP client so the new server entry takes effect.",""];process.stdout.write(e.join(`
297
- `))}s($s,"printInstallHelp");var kn=class{static{s(this,"InstallReport")}results=[];add(t){this.results.push(t)}results_(){return this.results}summary(){let t=0,n=0,r=0;for(let i of this.results)i.status==="created"||i.status==="merged"||i.status==="skipped"||i.status==="would-create"||i.status==="would-merge"||i.status==="would-pair"?t++:i.status==="needs-user-decision"?n++:i.status==="failed"&&r++;return{total:this.results.length,ok:t,needsDecision:n,failed:r}}hasFailures(){return this.results.some(t=>t.status==="failed")}hasUserDecisionPending(){return this.results.some(t=>t.status==="needs-user-decision")}exitCode(){return this.hasFailures()||this.hasUserDecisionPending()?1:0}toMarkdownTable(){if(this.results.length===0)return`_no steps were attempted_
298
- `;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(u=>u.target.length)),r=Math.max(t[1].length,...this.results.map(u=>u.action.length)),i=Math.max(t[2].length,...this.results.map(u=>u.status.length)),o=Math.max(t[3].length,...this.results.map(u=>(u.detail??"").length)),a=s((u,d)=>u+" ".repeat(Math.max(0,d-u.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(o)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],i)} | ${a(t[3],o)} |`),l.push(c);for(let u of this.results)l.push(`| ${a(u.target,n)} | ${a(u.action,r)} | ${a(u.status,i)} | ${a(u.detail??"",o)} |`);return l.join(`
296
+ `)}s(im,"printAuthInstructions");function Us(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}s(Us,"pad");async function om(e){let t,n;switch(Zf()){case"darwin":t="open",n=[e];break;case"win32":t="cmd",n=["/c","start","",e];break;default:t="xdg-open",n=[e];break}return new Promise((r,i)=>{try{let o=Qf(t,n,{stdio:"ignore",detached:!0});o.on("error",i),o.unref(),r()}catch(o){i(o)}})}s(om,"openExternalBrowser");xe();ge();xe();import*as jl from"node:os";function Gs(e){let t={projectRoot:null,full:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--no-preamble":t.noPreamble=!0;break;case"--no-hook":t.noHook=!0;break;case"--non-interactive":t.nonInteractive=!0;break;case"--telemetry":t.telemetry=!0;break;case"--skip-codex":t.skipCodex=!0;break;case"--dry-run":t.dryRun=!0;break;case"--auto-working-paths":t.autoWorkingPaths=!0;break;case"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--project-root requires a path argument");t.projectRoot=i,n++;break}case"--token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--token requires a token argument");t.token=i,n++;break}case"--one-click-token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--one-click-token requires a token argument");t.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=i,n++;break}case"--client":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--client requires a family argument (e.g. claude-code, cursor, windsurf, copilot, codex, claude-desktop)");t.client=i,n++;break}default:throw new Z(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}s(Gs,"parseInstallFlags");var Z=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function Ws(){let e=["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Detects your project root, pairs this device with MAIND, merges the","MCP-server entry into every supported AI-client config it finds, and","(optionally) writes the MAIND preamble block into CLAUDE.md / AGENTS.md /","Cursor / Windsurf / Copilot files. Idempotent \u2014 re-running is safe.","","Usage:"," npx -y @maind-dev/mcp-bridge install [flags]","","Common flags:"," --project-root <path> Override project-root detection (default: walk up from cwd)"," --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)"," --no-preamble Skip the 5 preamble files (MCP-config + pairing only)"," --no-hook Never write the Claude Code hooks (overrides --full for hooks)"," --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)"," --token <key> Use a pre-issued mnd_ api-key instead of browser pairing"," --one-click-token <jwt> Exchange the dashboard one-click token for a device-bound"," key \u2014 no browser (needs --one-click-exchange-url; ADR-267)"," --one-click-exchange-url <url> Exchange endpoint (set by the launcher scripts)"," --client <family> Install only for one client family (claude-code, cursor, ...)"," --skip-codex Skip the Codex ~/.codex/config.toml target",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --telemetry Opt-in: post anonymous install_completed event"," -h, --help Show this help text","","Examples:"," npx -y @maind-dev/mcp-bridge install # interactive default"," npx -y @maind-dev/mcp-bridge install --dry-run # preview without writing anything"," npx -y @maind-dev/mcp-bridge install --full --telemetry # full setup, opt-in telemetry"," npx -y @maind-dev/mcp-bridge install --client cursor # only Cursor target","","After it finishes, restart your MCP client so the new server entry takes effect.",""];process.stdout.write(e.join(`
297
+ `))}s(Ws,"printInstallHelp");var kn=class{static{s(this,"InstallReport")}results=[];add(t){this.results.push(t)}results_(){return this.results}summary(){let t=0,n=0,r=0;for(let i of this.results)i.status==="created"||i.status==="merged"||i.status==="skipped"||i.status==="would-create"||i.status==="would-merge"||i.status==="would-pair"?t++:i.status==="needs-user-decision"?n++:i.status==="failed"&&r++;return{total:this.results.length,ok:t,needsDecision:n,failed:r}}hasFailures(){return this.results.some(t=>t.status==="failed")}hasUserDecisionPending(){return this.results.some(t=>t.status==="needs-user-decision")}exitCode(){return this.hasFailures()||this.hasUserDecisionPending()?1:0}toMarkdownTable(){if(this.results.length===0)return`_no steps were attempted_
298
+ `;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(p=>p.target.length)),r=Math.max(t[1].length,...this.results.map(p=>p.action.length)),i=Math.max(t[2].length,...this.results.map(p=>p.status.length)),o=Math.max(t[3].length,...this.results.map(p=>(p.detail??"").length)),a=s((p,d)=>p+" ".repeat(Math.max(0,d-p.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(o)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],i)} | ${a(t[3],o)} |`),l.push(c);for(let p of this.results)l.push(`| ${a(p.target,n)} | ${a(p.action,r)} | ${a(p.status,i)} | ${a(p.detail??"",o)} |`);return l.join(`
299
299
  `)+`
300
300
  `}print(t){let n=this.summary();t.write(`
301
301
  `),t.write(this.toMarkdownTable()),t.write(`
302
302
  Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
303
- `)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as js from"node:fs/promises";import*as ye from"node:path";import*as Hs from"node:readline";var om=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function Us(e){let t=ye.resolve(e),n=t;for(;;){if(await Ws(n))return n;let r=ye.dirname(n);if(r===n)return t;n=r}}s(Us,"detectProjectRoot");async function Gs(e){let n=ye.resolve(e),r=[];for(;;){await Ws(n)&&r.push(n);let i=ye.dirname(n);if(i===n)break;n=i}return r}s(Gs,"findAllProjectRoots");async function Ws(e){for(let t of om)try{return await js.access(ye.join(e,t)),!0}catch{}return!1}s(Ws,"hasAnyMarker");async function Ks(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
303
+ `)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as Ks from"node:fs/promises";import*as ye from"node:path";import*as Bs from"node:readline";var um=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function Vs(e){let t=ye.resolve(e),n=t;for(;;){if(await zs(n))return n;let r=ye.dirname(n);if(r===n)return t;n=r}}s(Vs,"detectProjectRoot");async function qs(e){let n=ye.resolve(e),r=[];for(;;){await zs(n)&&r.push(n);let i=ye.dirname(n);if(i===n)break;n=i}return r}s(qs,"findAllProjectRoots");async function zs(e){for(let t of um)try{return await Ks.access(ye.join(e,t)),!0}catch{}return!1}s(zs,"hasAnyMarker");async function Js(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
304
304
  Multiple project roots found between cwd and the filesystem root:
305
305
  `),e.forEach((o,a)=>{process.stdout.write(` [${a+1}] ${o}
306
306
  `)}),process.stdout.write(`
307
- Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=Hs.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(o=>{n.question("",a=>o(a.trim()))});if(n.close(),r==="")return e[0];let i=Number.parseInt(r,10);return Number.isNaN(i)||i<1||i>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
308
- `),null):e[i-1]}s(Ks,"disambiguateProjectRoot");Ye();import*as Y from"node:path";function zs(e){let t=e.launch??ee({entryPath:te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{command:t.command,args:t.args,env:{...t.env,MAIND_CLIENT_FAMILY:e.clientFamily,MAIND_MCP_URL:e.mcpUrl}}}s(zs,"buildMaindServerEntry");function lm(e){switch(e.platform){case"darwin":return Y.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??Y.join(e.homeDir,"AppData","Roaming");return Y.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??Y.join(e.homeDir,".config");return Y.join(t,"Claude","claude_desktop_config.json")}}}s(lm,"claudeDesktopConfigPath");function Js(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:Y.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:Y.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:lm(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:Y.join(e.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:Y.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:Y.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}s(Js,"getClientTargets");function Ys(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}s(Ys,"filterTargetsByFamily");function Xs(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:qs(e.env.XDG_CONFIG_HOME),appData:qs(e.env.APPDATA)}}s(Xs,"makeDefaultContext");function qs(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}s(qs,"nonEmpty");Ye();ce();var Ct="maind";async function na(e,t,n=!1){if(e.kind!=="json")return{target:e.key,action:"merge",status:"failed",detail:`expected json target, got ${e.kind}`};let r;try{r=await G(e.path)}catch(d){return Jr(e,"read",d)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{i=JSON.parse(r)}catch(d){return Jr(e,"parse",d)}}if(!be(i))return{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};let a=e.key==="claude-code-user"&&pm(i),c,l=!1;if(a){let d=i[Ct];be(d)&&ta(d,t)&&(l=!0),c={...i,[Ct]:ea(d,t)}}else{let d=be(i.mcpServers)?i.mcpServers:{},p=d[Ct];be(p)&&ta(p,t)&&(l=!0),c={...i,mcpServers:{...d,[Ct]:ea(p,t)}}}if(l&&r!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let u=JSON.stringify(c,null,2)+`
309
- `;if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await F(e.path,u)}catch(d){return Jr(e,"write",d)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(na,"mergeJsonConfig");function ea(e,t){let n=be(e)&&be(e.env)?e.env:{},r={...t.env};for(let[i,o]of Object.entries(n))!(i in r)&&typeof o=="string"&&(r[i]=o);return{command:t.command,args:[...t.args],env:r}}s(ea,"mergeEntry");function pm(e){return!("mcpServers"in e||!(Ct in e))}s(pm,"hasRootShape");function ta(e,t){if(!be(e)||e.command!==t.command||!fm(e.args,t.args)||!be(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(ta,"serverEntriesEqual");function fm(e,t){if(!Array.isArray(e)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}s(fm,"arrayEquals");function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(be,"isObject");function Jr(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(Jr,"failed");ce();import{parse as mm,stringify as hm}from"smol-toml";async function ra(e,t,n=!1){if(e.kind!=="toml")return{target:e.key,action:"merge",status:"failed",detail:`expected toml target, got ${e.kind}`};let r;try{r=await G(e.path)}catch(h){return xn(e,"read",h)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{let h=mm(r);if(!Re(h))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=h}catch(h){return xn(e,"parse",h)}}let a=Re(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(Re(c)&&gm(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Re(c)&&Re(c.env)?c.env:{},u={...t.env};for(let[h,g]of Object.entries(l))!(h in u)&&typeof g=="string"&&(u[h]=g);let d={command:t.command,args:[...t.args],env:u},p={...i,mcp_servers:{...a,maind:d}},m;try{m=hm(p),m.endsWith(`
310
- `)||(m+=`
311
- `)}catch(h){return xn(e,"write",h)}let f=m.match(/^\[mcp_servers\.maind\]/gm)??[];if(f.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${f.length}`};if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await F(e.path,m)}catch(h){return xn(e,"write",h)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(ra,"mergeTomlConfig");function gm(e,t){if(!Re(e)||e.command!==t.command||!Array.isArray(e.args)||e.args.length!==t.args.length)return!1;for(let n=0;n<e.args.length;n++)if(e.args[n]!==t.args[n])return!1;if(!Re(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(gm,"tomlServerEntryEqual");function Re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Re,"isObject");function xn(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(xn,"failed");import*as le from"node:path";var ym="__STACK__";var bm="__INTENT__";var Yr="https://mcp.maind.dev/mcp",_m=`?stack=${ym}&intent=${bm}`;function wm(e,t){let n=new URLSearchParams;t.stack&&t.stack.length>0&&n.set("stack",t.stack.join(",")),t.intent&&n.set("intent",t.intent),t.project&&n.set("project",t.project),t.verbosity&&n.set("verbosity",t.verbosity);let r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e}s(wm,"buildStackAwareEndpoint");var hS=wm(Yr,{stack:["nextjs","supabase"],intent:"mixed"}),Pt=`## maind MCP integration \u2014 Mandatory consultation
307
+ Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=Bs.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(o=>{n.question("",a=>o(a.trim()))});if(n.close(),r==="")return e[0];let i=Number.parseInt(r,10);return Number.isNaN(i)||i<1||i>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
308
+ `),null):e[i-1]}s(Js,"disambiguateProjectRoot");Ye();import*as Y from"node:path";function Zs(e){let t=e.launch??ee({entryPath:te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{command:t.command,args:t.args,env:{...t.env,MAIND_CLIENT_FAMILY:e.clientFamily,MAIND_MCP_URL:e.mcpUrl}}}s(Zs,"buildMaindServerEntry");function hm(e){switch(e.platform){case"darwin":return Y.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??Y.join(e.homeDir,"AppData","Roaming");return Y.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??Y.join(e.homeDir,".config");return Y.join(t,"Claude","claude_desktop_config.json")}}}s(hm,"claudeDesktopConfigPath");function ea(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:Y.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:Y.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:hm(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:Y.join(e.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:Y.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:Y.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}s(ea,"getClientTargets");function ta(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}s(ta,"filterTargetsByFamily");function na(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Qs(e.env.XDG_CONFIG_HOME),appData:Qs(e.env.APPDATA)}}s(na,"makeDefaultContext");function Qs(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}s(Qs,"nonEmpty");Ye();ce();var Ct="maind";async function aa(e,t,n=!1){if(e.kind!=="json")return{target:e.key,action:"merge",status:"failed",detail:`expected json target, got ${e.kind}`};let r;try{r=await G(e.path)}catch(d){return Yr(e,"read",d)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{i=JSON.parse(r)}catch(d){return Yr(e,"parse",d)}}if(!be(i))return{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};let a=e.key==="claude-code-user"&&bm(i),c,l=!1;if(a){let d=i[Ct];be(d)&&sa(d,t)&&(l=!0),c={...i,[Ct]:oa(d,t)}}else{let d=be(i.mcpServers)?i.mcpServers:{},u=d[Ct];be(u)&&sa(u,t)&&(l=!0),c={...i,mcpServers:{...d,[Ct]:oa(u,t)}}}if(l&&r!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let p=JSON.stringify(c,null,2)+`
309
+ `;if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await L(e.path,p)}catch(d){return Yr(e,"write",d)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(aa,"mergeJsonConfig");function oa(e,t){let n=be(e)&&be(e.env)?e.env:{},r={...t.env};for(let[i,o]of Object.entries(n))!(i in r)&&typeof o=="string"&&(r[i]=o);return{command:t.command,args:[...t.args],env:r}}s(oa,"mergeEntry");function bm(e){return!("mcpServers"in e||!(Ct in e))}s(bm,"hasRootShape");function sa(e,t){if(!be(e)||e.command!==t.command||!_m(e.args,t.args)||!be(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(sa,"serverEntriesEqual");function _m(e,t){if(!Array.isArray(e)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}s(_m,"arrayEquals");function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(be,"isObject");function Yr(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(Yr,"failed");ce();import{parse as wm,stringify as km}from"smol-toml";async function ca(e,t,n=!1){if(e.kind!=="toml")return{target:e.key,action:"merge",status:"failed",detail:`expected toml target, got ${e.kind}`};let r;try{r=await G(e.path)}catch(h){return xn(e,"read",h)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{let h=wm(r);if(!Re(h))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=h}catch(h){return xn(e,"parse",h)}}let a=Re(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(Re(c)&&vm(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Re(c)&&Re(c.env)?c.env:{},p={...t.env};for(let[h,g]of Object.entries(l))!(h in p)&&typeof g=="string"&&(p[h]=g);let d={command:t.command,args:[...t.args],env:p},u={...i,mcp_servers:{...a,maind:d}},f;try{f=km(u),f.endsWith(`
310
+ `)||(f+=`
311
+ `)}catch(h){return xn(e,"write",h)}let m=f.match(/^\[mcp_servers\.maind\]/gm)??[];if(m.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${m.length}`};if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await L(e.path,f)}catch(h){return xn(e,"write",h)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(ca,"mergeTomlConfig");function vm(e,t){if(!Re(e)||e.command!==t.command||!Array.isArray(e.args)||e.args.length!==t.args.length)return!1;for(let n=0;n<e.args.length;n++)if(e.args[n]!==t.args[n])return!1;if(!Re(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(vm,"tomlServerEntryEqual");function Re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Re,"isObject");function xn(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(xn,"failed");import*as le from"node:path";var Sm="__STACK__";var Em="__INTENT__";var Xr="https://mcp.maind.dev/mcp",xm=`?stack=${Sm}&intent=${Em}`;function Rm(e,t){let n=new URLSearchParams;t.stack&&t.stack.length>0&&n.set("stack",t.stack.join(",")),t.intent&&n.set("intent",t.intent),t.project&&n.set("project",t.project),t.verbosity&&n.set("verbosity",t.verbosity);let r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e}s(Rm,"buildStackAwareEndpoint");var RS=Rm(Xr,{stack:["nextjs","supabase"],intent:"mixed"}),Pt=`## maind MCP integration \u2014 Mandatory consultation
312
312
 
313
313
  This project uses the maind MCP server (mcp.maind.dev/mcp) as
314
314
  authoritative source for vetted coding conventions and lessons. The
@@ -377,7 +377,7 @@ For non-trivial changes, resolve documentation path in this order:
377
377
  If no path is discoverable, provide a guided fallback:
378
378
  \`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
379
379
 
380
- Full tool set + provenance via \`get_conventions\`.`;function km(e){return`I want to add the **maind MCP server** to my AI coding agent.
380
+ Full tool set + provenance via \`get_conventions\`.`;function Am(e){return`I want to add the **maind MCP server** to my AI coding agent.
381
381
 
382
382
  - My stack: \`__STACK__\`
383
383
  - MCP endpoint: \`${e}\`
@@ -573,7 +573,7 @@ written config.
573
573
 
574
574
  --- Preamble block ---
575
575
 
576
- ${Pt}`}s(km,"buildAiPromptBody");function Nt(e,t,n){let r=n?`
576
+ ${Pt}`}s(Am,"buildAiPromptBody");function Nt(e,t,n){let r=n?`
577
577
  MAIND_CLIENT_FAMILY="${n}"`:"";return`#!/usr/bin/env bash
578
578
  set -euo pipefail
579
579
 
@@ -608,7 +608,7 @@ ${n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":""}
608
608
  config.mcpServers.maind = server;
609
609
  fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
610
610
  console.log("WROTE " + file);
611
- NODE`}s(Nt,"buildJsonConfigInstaller");function vm(e){return`#!/usr/bin/env bash
611
+ NODE`}s(Nt,"buildJsonConfigInstaller");function Tm(e){return`#!/usr/bin/env bash
612
612
  set -euo pipefail
613
613
 
614
614
  CONFIG_FILE="$HOME/.codex/config.toml"
@@ -661,7 +661,7 @@ if (serverCount !== 1 || envCount !== 1) {
661
661
 
662
662
  fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
663
663
  console.log("WROTE " + file);
664
- NODE`}s(vm,"buildCodexTomlInstaller");function Sm(e=Yr){let t=`${e}${_m}`;return[{id:"bridge-installer",label:"Quick setup",description:"One-shot installer. Runs browser pairing, merges the MCP-server entry into every supported AI-client config it finds (Claude Code, Cursor, Windsurf, Codex, Copilot, Claude Desktop), and writes the maind preamble block into CLAUDE.md / AGENTS.md / .cursorrules / .windsurfrules / .github/copilot-instructions.md. Idempotent \u2014 re-running is safe. Run from your project root.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install",extraVariants:[{label:"Non-interactive (CI / scripts)",description:"Skip every TTY prompt. Includes the SessionStart-hook merge into ~/.claude/settings.json \u2014 pass --no-hook to opt out. Useful for Docker, CI, and Dashboard-One-Click flows.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --full"},{label:"Filter to one client",description:"Install for a single client family instead of all detected ones. Replace `<family>` with one of claude-code, cursor, windsurf, copilot, codex, claude-desktop.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --client <family>"}]},{id:"ai-prompt",label:"AI agent prompt (Power-User / Air-gapped fallback)",description:"Pre-installer fallback: paste this prompt into your AI agent (Claude Code, Copilot, Cursor, Codex, \u2026) and let it orchestrate the install manually. Use this when `npx` is restricted (corporate, air-gapped), when your workspace has a custom layout the auto-detect can't resolve, or when you want to see every config block before it's written. The Quick Setup tab above is the recommended path for most users.",lang:"markdown",template:km(t)},{id:"claude-code-cli",label:"Claude Code",description:"Browser-pairing project config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:".mcp.json",lang:"json",template:`{
664
+ NODE`}s(Tm,"buildCodexTomlInstaller");function Im(e=Xr){let t=`${e}${xm}`;return[{id:"bridge-installer",label:"Quick setup",description:"One-shot installer. Runs browser pairing, merges the MCP-server entry into every supported AI-client config it finds (Claude Code, Cursor, Windsurf, Codex, Copilot, Claude Desktop), and writes the maind preamble block into CLAUDE.md / AGENTS.md / .cursorrules / .windsurfrules / .github/copilot-instructions.md. Idempotent \u2014 re-running is safe. Run from your project root.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install",extraVariants:[{label:"Non-interactive (CI / scripts)",description:"Skip every TTY prompt. Includes the SessionStart-hook merge into ~/.claude/settings.json \u2014 pass --no-hook to opt out. Useful for Docker, CI, and Dashboard-One-Click flows.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --full"},{label:"Filter to one client",description:"Install for a single client family instead of all detected ones. Replace `<family>` with one of claude-code, cursor, windsurf, copilot, codex, claude-desktop.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --client <family>"}]},{id:"ai-prompt",label:"AI agent prompt (Power-User / Air-gapped fallback)",description:"Pre-installer fallback: paste this prompt into your AI agent (Claude Code, Copilot, Cursor, Codex, \u2026) and let it orchestrate the install manually. Use this when `npx` is restricted (corporate, air-gapped), when your workspace has a custom layout the auto-detect can't resolve, or when you want to see every config block before it's written. The Quick Setup tab above is the recommended path for most users.",lang:"markdown",template:Am(t)},{id:"claude-code-cli",label:"Claude Code",description:"Browser-pairing project config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:".mcp.json",lang:"json",template:`{
665
665
  "mcpServers": {
666
666
  "maind": {
667
667
  "command": "npx",
@@ -689,7 +689,7 @@ args = ["-y", "@maind-dev/mcp-bridge"]
689
689
 
690
690
  [mcp_servers.maind.env]
691
691
  MAIND_CLIENT_FAMILY = "codex"
692
- MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codex/config.toml. It replaces only the maind MCP sections and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-codex.sh",lang:"bash",template:vm(t)}]},{id:"copilot",label:"GitHub Copilot",description:"Browser-pairing VS Code workspace config for Copilot agent mode. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as GitHub Copilot. Replace `__STACK__` with your stack slugs.",filename:".mcp.json",lang:"json",template:`{
692
+ MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codex/config.toml. It replaces only the maind MCP sections and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-codex.sh",lang:"bash",template:Tm(t)}]},{id:"copilot",label:"GitHub Copilot",description:"Browser-pairing VS Code workspace config for Copilot agent mode. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as GitHub Copilot. Replace `__STACK__` with your stack slugs.",filename:".mcp.json",lang:"json",template:`{
693
693
  "mcpServers": {
694
694
  "maind": {
695
695
  "command": "npx",
@@ -798,15 +798,15 @@ const tools = await mcp.getTools();
798
798
  "env": {
799
799
  "MAIND_MCP_URL": "${t}"
800
800
  }
801
- }`}]}s(Sm,"buildSnippetTemplates");var gS=Sm(Yr);ce();var Em="## maind MCP integration";function xm(e){return[{key:"preamble:CLAUDE.md",path:le.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:le.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:le.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:le.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:le.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:le.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}s(xm,"buildPreambleTargets");async function ia(e,t=!1){let n=xm(e),r=[];for(let i of n)r.push(await Rm(i,t));return r}s(ia,"writePreambleFiles");async function Rm(e,t){try{if(e.mayNeedParentDir&&!t&&await zr(le.dirname(e.path)),await Qs(e.path,Em))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await G(e.path);if(t)return{target:e.key,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:e.path};let i=r===null||r.length===0?`${Pt}
802
- `:Am(r)+`${Pt}
803
- `;return await F(e.path,i),{target:e.key,action:r===null?"write":"append",status:r===null?"created":"merged",detail:e.path}}catch(n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"append",status:"failed",detail:r}}}s(Rm,"writeOnePreambleFile");function Am(e){return e.endsWith(`
801
+ }`}]}s(Im,"buildSnippetTemplates");var AS=Im(Xr);ce();var Cm="## maind MCP integration";function Nm(e){return[{key:"preamble:CLAUDE.md",path:le.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:le.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:le.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:le.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:le.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:le.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}s(Nm,"buildPreambleTargets");async function la(e,t=!1){let n=Nm(e),r=[];for(let i of n)r.push(await Pm(i,t));return r}s(la,"writePreambleFiles");async function Pm(e,t){try{if(e.mayNeedParentDir&&!t&&await Jr(le.dirname(e.path)),await ra(e.path,Cm))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await G(e.path);if(t)return{target:e.key,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:e.path};let i=r===null||r.length===0?`${Pt}
802
+ `:Dm(r)+`${Pt}
803
+ `;return await L(e.path,i),{target:e.key,action:r===null?"write":"append",status:r===null?"created":"merged",detail:e.path}}catch(n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"append",status:"failed",detail:r}}}s(Pm,"writeOnePreambleFile");function Dm(e){return e.endsWith(`
804
804
 
805
805
  `)?e:e.endsWith(`
806
806
  `)?e+`
807
807
  `:e+`
808
808
 
809
- `}s(Am,"ensureTrailingBlankLine");ii();Xe();ce();import*as ua from"node:readline";var Ae="config:auto_working_paths",jm=`
809
+ `}s(Dm,"ensureTrailingBlankLine");oi();Xe();ce();import*as ga from"node:readline";var Ae="config:auto_working_paths",Bm=`
810
810
  Enable presence enrichment (auto working_paths)?
811
811
  With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
812
812
  locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
@@ -815,34 +815,34 @@ before editing the same area. Directory names only: never file contents, never
815
815
  absolute paths. Server-side these paths are account-private (org members never
816
816
  see them) and revocable any time on the dashboard consent page or via
817
817
  {"auto_working_paths": false} in the bridge config.
818
- [y/N]: `;async function pa(e){let t=e.configPath??de(),n={};try{let a=await G(t);if(a!==null&&a.trim().length>0){let c=JSON.parse(a);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(n=c)}}catch{}if(typeof n.auto_working_paths=="boolean")return{target:Ae,action:"skip",status:"skipped",detail:`already decided (${n.auto_working_paths?"enabled":"disabled"}) in ${t}`};let r;if(e.explicitFlag)r=!0;else if(e.isInteractive){if(e.dryRun)return{target:Ae,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??Hm)(e.out,jm)}else return{target:Ae,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:Ae,action:"skip",status:"skipped",detail:"user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"};let i={...n,auto_working_paths:!0},o=JSON.stringify(i,null,2)+`
819
- `;if(e.dryRun)return{target:Ae,action:"merge",status:"would-merge",detail:t};try{await F(t,o,384)}catch(a){return{target:Ae,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:Ae,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}s(pa,"applyWorkingPathsConsent");async function Hm(e,t){e.write(t);let n=ua.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}s(Hm,"promptYesNoDefaultNo");B();async function fa(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let i=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),o={};try{o=await i.json()}catch{}return i.ok?o.status!=="exchanged"||typeof o.api_key!="string"||!o.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:o.api_key,plan:o.plan??"unknown"}:{ok:!1,reason:o.error??`http_${i.status}`}}catch(i){return i instanceof Error&&i.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:i instanceof Error?i.message:String(i)}}finally{clearTimeout(r)}}s(fa,"exchangeOneClickToken");async function ga(e){let t="browser-pair";if(e.token!==null)try{let o=Um(e.token);return e.dryRun?{apiKey:o,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(It(),Ee(o),{apiKey:o,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(o){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:ma(o)}}}let n=null;if(e.oneClickToken!==null&&e.oneClickExchangeUrl!==null){if(e.dryRun)return{apiKey:null,result:{target:t,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let o=wn(e.bridgeVersion),a=await fa({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:o.device_id,label:Ms(),clientMeta:{...o}});if(a.ok)return It(),Ee(a.apiKey),{apiKey:a.apiKey,result:{target:t,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${a.plan})`}};n=a.reason,ha(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
820
- `)}let r=n===null?"":` (after exchange failure: ${n})`,i=D();if(i!==null)return{apiKey:i,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let o=await ze(e.bridgeVersion,ha(e));return o===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:o.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${o.plan})${r}`}}}catch(o){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:ma(o)}}}}s(ga,"pairOrUseToken");function Um(e){let t=e.trim();if(t.length===0)throw new Error("--token is empty");if(!/^mnd_[A-Za-z0-9_]+$/.test(t))throw new Error("--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?");return t}s(Um,"validateTokenShape");function ma(e){return e instanceof Error?e.message:String(e)}s(ma,"errMessage");function ha(e){return e.out??process.stdout}s(ha,"out");var Gm="https://vsddmiosisvfrairepxv.supabase.co/functions/v1",Wm="/install-completed";async function ya(e){if(!e.enabled||e.apiKey===null)return;let n=`${(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"")||Gm}${Wm}`,r={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:Bm(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:Km(e.steps),client_family_filter:e.clientFamilyFilter??null},i=new AbortController,o=setTimeout(()=>i.abort(),3e3);try{await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${e.installerVersion}`},body:JSON.stringify(r),signal:i.signal})}catch{}finally{clearTimeout(o)}}s(ya,"postInstallTelemetry");function Km(e){let t={created:0,merged:0,skipped:0,"needs-user-decision":0,failed:0};for(let n of e)t[n.status]=(t[n.status]??0)+1;return t}s(Km,"countStatuses");function Bm(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}s(Bm,"parseNodeMajor");Xt();var oy="https://mcp.maind.dev/mcp";async function Ml(e){let t=Date.now(),n;try{n=Ls(e)}catch(w){if(w instanceof Z)return process.stderr.write(`error: ${w.message}
821
- `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw w}if(n.help)return $s(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,o=Ol.homedir();if(o.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
822
- `),2;let a;if(n.projectRoot!==null)a=n.projectRoot;else{let w=await Gs(process.cwd());if(w.length===0)a=await Us(process.cwd());else if(w.length===1)a=w[0];else{let v=await Ks(w,i);if(v===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
818
+ [y/N]: `;async function ya(e){let t=e.configPath??de(),n={};try{let a=await G(t);if(a!==null&&a.trim().length>0){let c=JSON.parse(a);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(n=c)}}catch{}if(typeof n.auto_working_paths=="boolean")return{target:Ae,action:"skip",status:"skipped",detail:`already decided (${n.auto_working_paths?"enabled":"disabled"}) in ${t}`};let r;if(e.explicitFlag)r=!0;else if(e.isInteractive){if(e.dryRun)return{target:Ae,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??Vm)(e.out,Bm)}else return{target:Ae,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:Ae,action:"skip",status:"skipped",detail:"user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"};let i={...n,auto_working_paths:!0},o=JSON.stringify(i,null,2)+`
819
+ `;if(e.dryRun)return{target:Ae,action:"merge",status:"would-merge",detail:t};try{await L(t,o,384)}catch(a){return{target:Ae,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:Ae,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}s(ya,"applyWorkingPathsConsent");async function Vm(e,t){e.write(t);let n=ga.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}s(Vm,"promptYesNoDefaultNo");B();async function ba(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let i=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),o={};try{o=await i.json()}catch{}return i.ok?o.status!=="exchanged"||typeof o.api_key!="string"||!o.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:o.api_key,plan:o.plan??"unknown"}:{ok:!1,reason:o.error??`http_${i.status}`}}catch(i){return i instanceof Error&&i.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:i instanceof Error?i.message:String(i)}}finally{clearTimeout(r)}}s(ba,"exchangeOneClickToken");async function ka(e){let t="browser-pair";if(e.token!==null)try{let o=qm(e.token);return e.dryRun?{apiKey:o,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(It(),Ee(o),{apiKey:o,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(o){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:_a(o)}}}let n=null;if(e.oneClickToken!==null&&e.oneClickExchangeUrl!==null){if(e.dryRun)return{apiKey:null,result:{target:t,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let o=wn(e.bridgeVersion),a=await ba({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:o.device_id,label:Hs(),clientMeta:{...o}});if(a.ok)return It(),Ee(a.apiKey),{apiKey:a.apiKey,result:{target:t,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${a.plan})`}};n=a.reason,wa(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
820
+ `)}let r=n===null?"":` (after exchange failure: ${n})`,i=O();if(i!==null)return{apiKey:i,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let o=await ze(e.bridgeVersion,wa(e));return o===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:o.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${o.plan})${r}`}}}catch(o){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:_a(o)}}}}s(ka,"pairOrUseToken");function qm(e){let t=e.trim();if(t.length===0)throw new Error("--token is empty");if(!/^mnd_[A-Za-z0-9_]+$/.test(t))throw new Error("--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?");return t}s(qm,"validateTokenShape");function _a(e){return e instanceof Error?e.message:String(e)}s(_a,"errMessage");function wa(e){return e.out??process.stdout}s(wa,"out");var zm="https://vsddmiosisvfrairepxv.supabase.co/functions/v1",Jm="/install-completed";async function va(e){if(!e.enabled||e.apiKey===null)return;let n=`${(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"")||zm}${Jm}`,r={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:Xm(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:Ym(e.steps),client_family_filter:e.clientFamilyFilter??null},i=new AbortController,o=setTimeout(()=>i.abort(),3e3);try{await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${e.installerVersion}`},body:JSON.stringify(r),signal:i.signal})}catch{}finally{clearTimeout(o)}}s(va,"postInstallTelemetry");function Ym(e){let t={created:0,merged:0,skipped:0,"needs-user-decision":0,failed:0};for(let n of e)t[n.status]=(t[n.status]??0)+1;return t}s(Ym,"countStatuses");function Xm(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}s(Xm,"parseNodeMajor");Xt();var uy="https://mcp.maind.dev/mcp";async function Hl(e){let t=Date.now(),n;try{n=Gs(e)}catch(w){if(w instanceof Z)return process.stderr.write(`error: ${w.message}
821
+ `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw w}if(n.help)return Ws(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,o=jl.homedir();if(o.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
822
+ `),2;let a;if(n.projectRoot!==null)a=n.projectRoot;else{let w=await qs(process.cwd());if(w.length===0)a=await Vs(process.cwd());else if(w.length===1)a=w[0];else{let v=await Js(w,i);if(v===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
823
823
  `);for(let k of w)process.stderr.write(` candidate: ${k}
824
- `);return 2}a=v}}let c=new kn,l=(process.env.MAIND_MCP_URL??"").trim()||oy;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
824
+ `);return 2}a=v}}let c=new kn,l=(process.env.MAIND_MCP_URL??"").trim()||uy;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
825
825
  `),process.stdout.write(`maind install \u2014 project root: ${a}
826
826
  `),process.stdout.write(` \u2014 mcp endpoint: ${l}
827
827
 
828
- `);let u=await ga({bridgeVersion:P,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(c.add(u.result),u.result.status==="failed")return process.stderr.write(`
829
- pairing failed: ${u.result.detail??"unknown"}
828
+ `);let p=await ka({bridgeVersion:P,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(c.add(p.result),p.result.status==="failed")return process.stderr.write(`
829
+ pairing failed: ${p.result.detail??"unknown"}
830
830
  Skipping remaining steps.
831
- `),c.print(process.stdout),2;let d=Xs({projectRoot:a,homeDir:o,platform:process.platform,env:process.env}),p=Js(d);if(p=Ys(p,n.client),n.skipCodex&&(p=p.filter(w=>w.key!=="codex-cli")),p.length===0)return process.stderr.write(n.client!==null?`error: --client "${n.client}" matched no known target. Run --help for the list.
831
+ `),c.print(process.stdout),2;let d=na({projectRoot:a,homeDir:o,platform:process.platform,env:process.env}),u=ea(d);if(u=ta(u,n.client),n.skipCodex&&(u=u.filter(w=>w.key!=="codex-cli")),u.length===0)return process.stderr.write(n.client!==null?`error: --client "${n.client}" matched no known target. Run --help for the list.
832
832
  `:`error: no client targets selected (did you skip all of them?)
833
- `),c.print(process.stdout),2;for(let w of p){let v=zs({mcpUrl:l,clientFamily:w.clientFamilyEnv}),k;w.kind==="json"?k=await na(w,v,n.dryRun):k=await ra(w,v,n.dryRun),c.add(k)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let w=await ia({projectRoot:a,homeDir:o},n.dryRun);for(let v of w)c.add(v)}let m={homeDir:o,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await la(m));for(let w of await da(m))c.add(w);c.add(await pa({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let f=Tl();f.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${f.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await ya({enabled:n.telemetry||n.full,installerVersion:P,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:u.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let h=c.exitCode(),g=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
833
+ `),c.print(process.stdout),2;for(let w of u){let v=Zs({mcpUrl:l,clientFamily:w.clientFamilyEnv}),k;w.kind==="json"?k=await aa(w,v,n.dryRun):k=await ca(w,v,n.dryRun),c.add(k)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let w=await la({projectRoot:a,homeDir:o},n.dryRun);for(let v of w)c.add(v)}let f={homeDir:o,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await ma(f));for(let w of await ha(f))c.add(w);c.add(await ya({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let m=Dl();m.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${m.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await va({enabled:n.telemetry||n.full,installerVersion:P,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:p.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let h=c.exitCode(),g=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
834
834
  DRY RUN finished in ${g}s. No files were modified. Re-run without --dry-run to apply.
835
835
  `):process.stdout.write(`
836
836
  Finished in ${g}s. Restart your MCP client so it picks up the new server entry.
837
837
  `);let y=ee({entryPath:te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),b=y.fallbackReason===null?`${Je(y)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${b}
838
838
  `),h===1&&process.stdout.write(`Note: some steps were skipped or failed \u2014 review the table above. The MCP setup is usable as long as 'browser-pair' and at least one JSON/TOML target succeeded.
839
- `),h}s(Ml,"runInstall");Xt();import{readFileSync as sy}from"node:fs";import{join as Fl}from"node:path";function dr(e){return e?Math.ceil(e.length/4):0}s(dr,"estimateTokens");var Ll=1e6,ur=class{static{s(this,"SavingsAggregator")}pendingTokens=0;pendingCalls=0;add(t){!Number.isFinite(t)||t<=0||(this.pendingTokens+=Math.floor(t),this.pendingCalls+=1)}hasPending(){return this.pendingTokens>0}takePending(){let t={tokens:this.pendingTokens,calls:this.pendingCalls};return this.pendingTokens=0,this.pendingCalls=0,t}};function $l(e){try{let t=sy(e,"utf8");return t.length>Ll?t.slice(0,Ll):t}catch{return""}}s($l,"readFileCapped");function ay(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=n?.filePath;typeof r=="string"&&r.length>0&&t.add(r)}return[...t]}s(ay,"distinctFilePaths");function jl(e,t,n,r){try{let i=dr(n);if(e==="codebase_search"){let o=ay(t);if(o.length===0)return 0;let a=0;for(let c of o)a+=dr($l(Fl(r,c)));return Math.max(0,a-i)}if(e==="codebase_snippet"){let o=t?.filePath;if(typeof o!="string"||o.length===0)return 0;let a=dr($l(Fl(r,o)));return Math.max(0,a-i)}return 0}catch{return 0}}s(jl,"measureLocalToolSaved");Qt();Xt();import{createHash as by}from"node:crypto";function pr(e){return by("sha256").update(e,"utf8").digest("hex")}s(pr,"nodeKeyHash");var _y=["module","class","interface","function","method","type_alias","enum","variable"],vo=[{name:"codebase_index",description:"Build or update the LOCAL codebase index for the current repo (tree-sitter \u2192 symbol graph in .maind/code-index.sqlite). Runs on this machine; nothing is uploaded. Incremental by default \u2014 only changed files are re-parsed. Call once before codebase_search/trace/map if the index is empty (see codebase_status).",inputSchema:{type:"object",properties:{full:{type:"boolean",description:"Force a full rebuild instead of incremental."}}}},{name:"codebase_status",description:"Report the local codebase index status: file/symbol/edge counts, languages, and when it was last built. Use this to decide whether to run codebase_index first.",inputSchema:{type:"object",properties:{}}},{name:"codebase_search",description:"Search indexed symbols by name/identifier (lexical FTS over function/class/method/\u2026 names, split on camelCase & snake_case). Returns matching symbols with their node_key, file, and line. Feed a node_key into codebase_snippet or codebase_trace.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text (identifier fragments)."},kind:{type:"string",enum:_y,description:"Restrict to a symbol kind."},limit:{type:"number",description:"Max results (default 20)."}},required:["query"]}},{name:"codebase_trace",description:"Traverse the call/dependency graph from a symbol. direction 'out' = what this symbol calls/contains/imports; 'in' = what calls/depends on it. Returns edges as node_key \u2192 node_key with the edge kind. CALLS/EXTENDS are best-effort name heuristics.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"Start symbol's node_key (from codebase_search)."},direction:{type:"string",enum:["out","in"],description:"Traversal direction (default out)."},max_depth:{type:"number",description:"BFS depth 1\u20135 (default 3)."},limit:{type:"number",description:"Max edges returned (default 100)."}},required:["node_key"]}},{name:"codebase_snippet",description:"Return the exact source text of a symbol by node_key (read locally from disk \u2014 never uploaded). Use after codebase_search/trace to read a function/class without opening the file.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"The symbol's node_key."}},required:["node_key"]}},{name:"codebase_map",description:"Architecture overview of the indexed repo: symbol-kind distribution, languages, and the most-imported (highest fan-in) modules \u2014 a cheap way to orient in an unfamiliar codebase.",inputSchema:{type:"object",properties:{top_n:{type:"number",description:"How many top modules to list (default 10)."}}}},{name:"codebase_changes",description:"Enumerate the symbols in files you changed (git diff/status against the LOCAL index \u2014 runs on this machine, nothing is uploaded). Call after finishing an edit batch, before committing. The output includes a ready-to-paste `briefing_args` block with paths deliberately stripped \u2014 feed it to the cloud tool codebase_change_briefing to get the maind conventions and lessons that apply to exactly these symbols. Requires a built index (codebase_index) for symbol enumeration; files without index rows are counted but contribute no symbols.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."}}}},{name:"codebase_review_changes",description:"Review-grade change enumeration (ADR-228): like codebase_changes, but hunk-aware \u2014 each symbol is graded added|modified|co_located by intersecting git diff hunks with symbol spans (runs on this machine, nothing is uploaded), plus closed-enum risk_flags from the raw path list (SQL migrations, RLS/SECURITY DEFINER, CI workflows, env files \u2014 files the index itself cannot see). The output's `review_args` block is path-free by construction \u2014 feed it to the cloud tool review_changes for provenance-backed convention findings. It ALSO runs the four repo-health detectors (number collisions, spec drift, dead theme classes, table ACL \u2014 ADR-324) and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full keeps a run attestation-grade. diff_stats carries the attest anchors (head_sha, dirty, resolved base_sha \u2014 commit object hashes, no source): pass them through to review_verdict to persist a replayable review_runs record (ADR-230). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],Zl=new Set(vo.map(e=>e.name));function L(e){return typeof e=="string"&&e.length>0?e:void 0}s(L,"str");var wy=10;function ky(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,o=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=wy&&r++,c>i&&(i=c);for(let u of a.ownership?.topAuthors??[])n.add(u.email.toLowerCase()||u.name);let l=a.lastCommits[0]?.dateIso;if(l){let u=Date.parse(l);Number.isFinite(u)&&u>o&&(o=u)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:o>0?Math.max(0,Math.floor((t-o)/864e5)):0}}s(ky,"aggregateHistoryContext");function Me(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Me,"num");function Xl(e){if(e===void 0)return{repoRoot:z(),scanDirs:void 0};let t=lr(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(Xl,"anchorRepo");function Ql(e,t){return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,projects:[],findings:[],hint:`No opinion \u2014 this directory could not be located, so no repository was scanned. ${t} Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. \`Asgard/Maind\`) or an absolute path. Nothing was verified as ${e}.`}}s(Ql,"dirNotFound");async function ed(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(a=>a.status==="open").length,o=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:o,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${o} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=L(n.for_path);if(i!==void 0){let d=Nl(i);if(d===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await Ce(d.repoRoot,d.repoRelPath,{minFiles:r}),m=p.namespace,f=s(g=>g===null?null:`${m?.prefix??""}${g}`,"full"),h=m===null?"no_opinion":p.taken?"taken":"free";return{ok:h==="free",mode:"proposed_path",verdict:h,reason:h==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:d.repoRoot,namespace:m===null?null:{dir:m.dir,prefix:m.prefix,file_count:m.fileCount},number:f(p.number),taken:h==="no_opinion"?null:p.taken,suggestion:f(p.suggestion),held_by:p.sightings.map(g=>({kind:g.kind,where:g.where,path:g.path})),hint:h==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${f(p.number)} is already held (see held_by). Create the file as ${f(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${f(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let o=Array.isArray(n.dirs)?n.dirs.filter(d=>typeof d=="string"):void 0;if(o!==void 0&&o.length>0){let d=new Map,p=[];for(let v of o){let k=lr(v);if(k===null){p.push(v);continue}let E=d.get(k.repoRoot)??new Set;E.add(k.repoRelDir),d.set(k.repoRoot,E)}if(d.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let m=[],f=[],h=[],g=[];for(let[v,k]of d){let E=[...k],R=E.includes(""),I=await Ie(v,{dirs:R?void 0:E,minFiles:r});m.push({repo_root:v,dirs:R?null:E}),f.push(...I.findings),h.push(...I.facts.namespaces.map(T=>({repo_root:v,dir:T.dir,prefix:T.prefix,file_count:T.fileCount}))),g.push(...I.facts.skipped)}let y=f.filter(v=>v.status==="open"),b=f.filter(v=>v.status==="info"),w=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:y.length===0,open_count:y.length,preexisting_count:b.length,findings:y,preexisting:b.map(v=>`${v.namespace.prefix}${v.number}`),namespaces:h,skipped:g,scanned:m,...p.length>0?{unresolved_dirs:p}:{},hint:(y.length===0?h.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${y.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+w}}let a=z(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(d=>d.status==="open"),u=c.findings.filter(d=>d.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:u.length,findings:l,preexisting:u.map(d=>`${d.namespace.prefix}${d.number}`),namespaces:c.facts.namespaces.map(d=>({dir:d.dir,prefix:d.prefix,file_count:d.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:L(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=s(p=>r.findings.filter(m=>m.status===p),"of"),o=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let u="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",d=o.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:a.length,preexisting_count:c.length,findings:[...o,...a],preexisting:c.map(p=>p.id),coverage_note:u,hint:(r.ok?"The declared entries agree.":d.length>0?`${d.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${o.length-d.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${o.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+u}}case"check_theme_class_drift":{let r=L(n.dir),i,o;if(r!==void 0){let d=lr(r);if(d===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};i=d.repoRoot,o=d.repoRelDir===""?void 0:[d.repoRelDir]}else i=z(),o=void 0;let a=De(i,{dirs:o,baseRef:L(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(d=>d.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(d=>({file:d.file,class:d.klass,status:d.status,missing_token:d.token,namespace:d.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=Xl(L(n.dir));if(r===null)return Ql("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Pe(r.repoRoot,{dirs:r.scanDirs,baseRef:L(n.base_ref),includeBaseline:n.include_baseline!==!1}),o="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+o}}case"check_migration_ledger_drift":{let r=Xl(L(n.dir));if(r===null)return Ql("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=ko(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:L(n.remote_db_url)}),o=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=s(p=>i.findings.filter(m=>m.status===p),"of"),c=a("open"),l=a("warn"),u=a("info"),d=o.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:o,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:u.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:d,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${d}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${d}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${d}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=L(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:L(n.kind),limit:Me(n.limit)})).map(o=>({...o,nodeKeyHash:pr(o.nodeKey)}))}case"codebase_trace":{let r=L(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:i,maxDepth:Me(n.max_depth),limit:Me(n.limit)})}case"codebase_snippet":{let r=L(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await e.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:pr(r)}}case"codebase_map":return e.getArchitecture({topN:Me(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:L(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Me(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language,file:i.filePath,start_line:i.startLine,node_key:i.nodeKey,node_key_hash:pr(i.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:L(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Me(n.limit)}),i;if(n.include_history!==!1)try{i=ky(await e.fileHistory({since:L(n.since),limit:1}))}catch{i=void 0}let o;try{o=await e.reviewDetectors({baseRef:L(n.since)})}catch(l){o=ot(Bt(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,...r.headSha?{head_sha:r.headSha}:{},dirty:r.dirty,...r.baseSha?{base_sha:r.baseSha}:{},code_index_version:Yl,detector_coverage:o.coverage},c=o.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,u)=>l+u.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:pr(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...i?{history:i}:{}},verdict_args:{detector_findings:o.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:o.coverage,truncated:o.truncated,block_eligible:c,engines:o.engines,findings:o.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${o.findings.length} detector row(s) (${c} block-eligible, coverage ${o.coverage}) are hashes only; keep detector_findings even when it is []. Persisting a replayable record additionally needs commit_sha / diff_stats.head_sha.`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(o=>typeof o=="string"):void 0,i=await e.fileHistory({paths:r,since:L(n.since),limit:Me(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(o=>({path:o.path,last_commits:o.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:o.ownership?{top_authors:o.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:o.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(o=>({sha:o.sha,date_iso:o.dateIso,author_name:o.authorName,subject:o.subject,files_touched:o.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}s(ed,"dispatchLocalTool");var fr=class{constructor(t=Dl,n=null,r=z){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return vo}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Zl.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",o=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=await ed(this.getEngine(),i,o),c=JSON.stringify(a,null,2);return this.recordSavings(i,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=Il(a)?`${Cl} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(o=>o&&typeof o=="object"?o.name:void 0).filter(o=>typeof o=="string")),i=this.descriptors().filter(o=>!r.has(o.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=jl(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};var vy="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function td(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:vy}s(td,"functionsOrigin");var Sy="/mcp-client-metrics-ingest",Ey=4e3,xy="codebase_search_tokens_saved";async function nd(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${td()}${Sy}`,n=new AbortController,r=setTimeout(()=>n.abort(),Ey);try{let i=await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"x-maind-device-id":e.deviceId,"user-agent":`@maind-dev/mcp-bridge/${e.bridgeVersion}`},body:JSON.stringify({metrics:[{session_id:e.sessionId,metric_key:xy,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await i.text().catch(()=>""),i.ok}catch(i){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${i instanceof Error?i.message:String(i)}
840
- `),!1}finally{clearTimeout(r)}}s(nd,"postSavingsMetric");xo();hr();yr();bt();import{join as n_}from"node:path";var r_="<synthetic>";function Jd(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:n_(Wo,Ko(e.cwd),`${e.transcript_stem}.jsonl`)}s(Jd,"transcriptPathFromSideChannel");var xr=class{constructor(t){this.deps=t}static{s(this,"TranscriptMetaReader")}path=null;offset=0;model=null;title=null;async read(){try{let n=this.deps.resolvePath();if(n!==this.path&&(this.path=n,this.offset=0,this.model=null,this.title=null),n!==null){let i=await(this.deps.stream??Go)(n,{start:this.offset});for(let o of i.events)if(o.kind==="title"){let a=o.title.trim();a.length>0&&(this.title=a)}else o.kind==="assistant"&&!o.isSidechain&&typeof o.model=="string"&&o.model.length>0&&o.model!==r_&&(this.model=o.model);i.bytesRead>this.offset&&(this.offset=i.bytesRead)}}catch{}let t=null;try{t=this.deps.fallbackModel?.()??null}catch{t=null}return{model:this.model??t,title:this.title}}};import{execFile as i_}from"node:child_process";var o_=8,s_=32;function a_(e){return e.split(`
841
- `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,s_)}s(a_,"parsePorcelain");function c_(e,t=o_){let n=[];for(let r of e){let i=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(i.length===0)continue;let o=i.includes("/")?i.slice(0,i.lastIndexOf("/")):i;if(!(o.length===0||n.includes(o))&&(n.push(o),n.length>=t))break}return n}s(c_,"condenseToDirs");async function Yd(e=l_){let t=await e();if(t===null)return null;let n=c_(a_(t));return n.length>0?n:null}s(Yd,"deriveWorkingPaths");async function l_(){return await new Promise(e=>{i_("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(l_,"defaultGitStatus");var nv=1,rv=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function iv(e){return rv.includes(e)}s(iv,"isHookSubcommand");var ov=6e4;async function sv(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==D()&&Ee(e),e;let t=D();if(t!==null)return t;let n=await ze(P);return n===null&&(process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
842
- `),process.exit(1)),n.apiKey}s(sv,"ensureApiKey");async function av(){let e=await ze(P);return e===null&&(process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
843
- `),process.exit(1)),e.apiKey}s(av,"reauth");async function cv(){let e=process.argv.slice(2).find(y=>!y.startsWith("-"));if(e==="install"){let y=process.argv.indexOf("install"),b=process.argv.slice(y+1),w=await Ml(b);process.exit(w)}if(e==="on-session-end"){let{runOnSessionEnd:y}=await Promise.resolve().then(()=>(ju(),$u));process.exit(await y())}if(e==="guard"){let y=process.argv.indexOf("guard"),{runGuard:b}=await Promise.resolve().then(()=>(zu(),qu));process.exit(await b(process.argv.slice(y+1)))}if(e==="guard-inject"){let{runGuardInject:y}=await Promise.resolve().then(()=>(ep(),Zu));process.exit(await y())}if(e==="guard-gate"){let{runGuardGate:y}=await Promise.resolve().then(()=>(op(),ip));process.exit(await y())}if(e==="guard-stop"){let{runGuardStop:y}=await Promise.resolve().then(()=>(cp(),ap));process.exit(await y())}if(e==="gateway"){let y=process.argv.indexOf("gateway"),{runGateway:b}=await Promise.resolve().then(()=>(Vp(),Bp));process.exit(await b(process.argv.slice(y+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:y}=await Promise.resolve().then(()=>(ms(),fs));process.exit(await y())}if(e==="guard-cross-check"){let{runGuardCrossCheck:y}=await Promise.resolve().then(()=>(ms(),fs));process.exit(await y())}if(e==="on-index-refresh"){let{runOnIndexRefresh:y}=await Promise.resolve().then(()=>(ys(),gs));process.exit(await y())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:y}=await Promise.resolve().then(()=>(ys(),gs));process.exit(await y())}if(e!==void 0&&iv(e)){let y=await Promise.resolve().then(()=>(Zo(),Iu)),b={"on-session-start":y.runOnSessionStart,"on-tool-use":y.runOnToolUse,"on-file-write":y.runOnFileWrite,"on-file-edit":y.runOnFileEdit,"on-repo-health":y.runOnRepoHealth,"on-write-health":y.runOnWriteHealth,"sync-config":y.runSyncConfig,flush:y.runFlush,status:y.runHookStatus}[e];process.exit(await b())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(P+`
844
- `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(lv(),process.exit(0)),process.argv.includes("--reauth")&&(It(),await ze(P,process.stdout)===null&&process.exit(1),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
845
- `),process.exit(0));let t=U(),n=await sv(),r=O(),o=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new ur:null,a=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new fr(void 0,o),c=`bridge-${tv()}`,l=s(async()=>{if(!o)return;let y=o.takePending();y.tokens<=0||await nd({apiKey:n,deviceId:t,sessionId:c,tokensSaved:y.tokens,bridgeVersion:P})},"flushSavings"),u=o?setInterval(()=>{l()},ov):null;u?.unref();let d=null,p=new gr({projectKey:r}),m=new xr({resolvePath:s(()=>Jd(p.sideChannel()),"resolvePath"),fallbackModel:s(()=>p.sideChannel()?.model??null,"fallbackModel")}),f=new mr({projectKey:r,identity:p,sessionMeta:s(()=>m.read(),"sessionMeta"),postToolCall:s((y,b)=>d===null?Promise.reject(new Error("presence: no active forwarder")):d.postPresenceToolCall(y,b),"postToolCall"),deriveWorkingPaths:s(()=>Yd(),"deriveWorkingPaths"),snapshot:r!==null?md({projectKey:r}):void 0}),h=f.isEnabled?setInterval(()=>{f.pollActivity()},od):null;if(h?.unref(),f.isEnabled){let y=s(b=>{f.end().finally(()=>process.exit(b))},"endAndExit");process.on("SIGTERM",()=>y(143)),process.on("SIGINT",()=>y(130))}let g=0;try{for(;;){let y=new bn({apiKey:n,deviceId:t,bridgeVersion:P,projectKey:r,localRouter:a,presence:f});d=y;try{await y.run();return}catch(b){if(b instanceof At&&g<nv){g+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${b.message}; re-authorizing\u2026
846
- `),n=await av();continue}throw b}}}finally{u&&clearInterval(u),h&&clearInterval(h),await f.end(),await l()}}s(cv,"main");function lv(){let e=["","@maind-dev/mcp-bridge \u2014 local MCP wrapper that pins your maind API key to this device.","","Usage:"," npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)"," npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble, hooks)"," npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow"," npx -y @maind-dev/mcp-bridge --version"," npx -y @maind-dev/mcp-bridge --help","","Run `install --help` for full setup flags:"," npx -y @maind-dev/mcp-bridge install --help","","Claude Code hook subcommands (wired by `install`; run them by hand only for","diagnostics). They read the hook payload on stdin and use the bridge's own","paired credential \u2014 no separate init:"," on-session-start open a tracked session (Tier-3 flat metrics)"," on-tool-use bump counters + evaluate the ADR-039 context advisory"," on-file-write block a Write that claims a taken number (ADR-263)"," on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)"," on-repo-health surface this worktree's repo-health findings before the first edit in it (ADR-323, never blocks)"," on-write-health after an edit, run the path-relevant checks (spec/theme/table-acl) and report what this branch introduced (ADR-323, never blocks)"," on-session-end session analytics + close/flush the tracked session"," sync-config pull your context thresholds from the server (ADR-039)"," flush post queued Tier-3 metrics now"," status show pairing, queued metrics and active thresholds","","Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:"," guard install wire the guard hook pack (consent per hook) + set mode"," guard status mode, guard-hook wiring, local enforcement-event counts"," guard mode <warn|block> | guard off | guard stop-gate <on|off>",' guard skip --session <id> --reason "\u2026" logged override (block-gate exit)'," (hook subcommands, wired by `guard install`: guard-inject, guard-gate, guard-stop)","","Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent","Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.","","Environment overrides (rarely needed):"," MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)"," MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)"," MAIND_CLIENT_VERSION Optional client version marker (max 64 chars)"," MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth"," MAIND_AUTO_ANNOUNCE Set to 'off' to disable automatic presence announces (ADR-242)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," XDG_CONFIG_HOME Override config-dir parent on Linux/BSD","","Auto-presence (ADR-242): the bridge announces this session on the repo's","shared working tree (project_key hash + branch only \u2014 no hostname, no paths),","refreshes while tools are actually called, and ends the row on exit.","Persistent opt-out / explicit machine_label via config.json in the maind",'config dir: { "auto_announce": false, "machine_label": "my-box" }',"","Place this in your .mcp.json (or equivalent):",""," {",' "mcpServers": {',' "maind": {',' "command": "npx",',' "args": ["-y", "@maind-dev/mcp-bridge"]'," }"," }"," }",""];process.stderr.write(e.join(`
847
- `))}s(lv,"printHelp");cv().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
839
+ `),h}s(Hl,"runInstall");Xt();import{readFileSync as py}from"node:fs";import{join as Ul}from"node:path";function dr(e){return e?Math.ceil(e.length/4):0}s(dr,"estimateTokens");var Gl=1e6,ur=class{static{s(this,"SavingsAggregator")}pendingTokens=0;pendingCalls=0;add(t){!Number.isFinite(t)||t<=0||(this.pendingTokens+=Math.floor(t),this.pendingCalls+=1)}hasPending(){return this.pendingTokens>0}takePending(){let t={tokens:this.pendingTokens,calls:this.pendingCalls};return this.pendingTokens=0,this.pendingCalls=0,t}};function Wl(e){try{let t=py(e,"utf8");return t.length>Gl?t.slice(0,Gl):t}catch{return""}}s(Wl,"readFileCapped");function fy(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=n?.filePath;typeof r=="string"&&r.length>0&&t.add(r)}return[...t]}s(fy,"distinctFilePaths");function Kl(e,t,n,r){try{let i=dr(n);if(e==="codebase_search"){let o=fy(t);if(o.length===0)return 0;let a=0;for(let c of o)a+=dr(Wl(Ul(r,c)));return Math.max(0,a-i)}if(e==="codebase_snippet"){let o=t?.filePath;if(typeof o!="string"||o.length===0)return 0;let a=dr(Wl(Ul(r,o)));return Math.max(0,a-i)}return 0}catch{return 0}}s(Kl,"measureLocalToolSaved");Qt();Xt();import{createHash as Ey}from"node:crypto";function pr(e){return Ey("sha256").update(e,"utf8").digest("hex")}s(pr,"nodeKeyHash");var xy=["module","class","interface","function","method","type_alias","enum","variable"],So=[{name:"codebase_index",description:"Build or update the LOCAL codebase index for the current repo (tree-sitter \u2192 symbol graph in .maind/code-index.sqlite). Runs on this machine; nothing is uploaded. Incremental by default \u2014 only changed files are re-parsed. Call once before codebase_search/trace/map if the index is empty (see codebase_status).",inputSchema:{type:"object",properties:{full:{type:"boolean",description:"Force a full rebuild instead of incremental."}}}},{name:"codebase_status",description:"Report the local codebase index status: file/symbol/edge counts, languages, and when it was last built. Use this to decide whether to run codebase_index first.",inputSchema:{type:"object",properties:{}}},{name:"codebase_search",description:"Search indexed symbols by name/identifier (lexical FTS over function/class/method/\u2026 names, split on camelCase & snake_case). Returns matching symbols with their node_key, file, and line. Feed a node_key into codebase_snippet or codebase_trace.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text (identifier fragments)."},kind:{type:"string",enum:xy,description:"Restrict to a symbol kind."},limit:{type:"number",description:"Max results (default 20)."}},required:["query"]}},{name:"codebase_trace",description:"Traverse the call/dependency graph from a symbol. direction 'out' = what this symbol calls/contains/imports; 'in' = what calls/depends on it. Returns edges as node_key \u2192 node_key with the edge kind. CALLS/EXTENDS are best-effort name heuristics.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"Start symbol's node_key (from codebase_search)."},direction:{type:"string",enum:["out","in"],description:"Traversal direction (default out)."},max_depth:{type:"number",description:"BFS depth 1\u20135 (default 3)."},limit:{type:"number",description:"Max edges returned (default 100)."}},required:["node_key"]}},{name:"codebase_snippet",description:"Return the exact source text of a symbol by node_key (read locally from disk \u2014 never uploaded). Use after codebase_search/trace to read a function/class without opening the file.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"The symbol's node_key."}},required:["node_key"]}},{name:"codebase_map",description:"Architecture overview of the indexed repo: symbol-kind distribution, languages, and the most-imported (highest fan-in) modules \u2014 a cheap way to orient in an unfamiliar codebase.",inputSchema:{type:"object",properties:{top_n:{type:"number",description:"How many top modules to list (default 10)."}}}},{name:"codebase_changes",description:"Enumerate the symbols in files you changed (git diff/status against the LOCAL index \u2014 runs on this machine, nothing is uploaded). Call after finishing an edit batch, before committing. The output includes a ready-to-paste `briefing_args` block with paths deliberately stripped \u2014 feed it to the cloud tool codebase_change_briefing to get the maind conventions and lessons that apply to exactly these symbols. Requires a built index (codebase_index) for symbol enumeration; files without index rows are counted but contribute no symbols.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."}}}},{name:"codebase_review_changes",description:"Review-grade change enumeration (ADR-228): like codebase_changes, but hunk-aware \u2014 each symbol is graded added|modified|co_located by intersecting git diff hunks with symbol spans (runs on this machine, nothing is uploaded), plus closed-enum risk_flags from the raw path list (SQL migrations, RLS/SECURITY DEFINER, CI workflows, env files \u2014 files the index itself cannot see). The output's `review_args` block is path-free by construction \u2014 feed it to the cloud tool review_changes for provenance-backed convention findings. It ALSO runs the four repo-health detectors (number collisions, spec drift, dead theme classes, table ACL \u2014 ADR-324) and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full keeps a run attestation-grade. diff_stats carries the attest anchors (head_sha, dirty, resolved base_sha \u2014 commit object hashes, no source): pass them through to review_verdict to persist a replayable review_runs record (ADR-230). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],id=new Set(So.map(e=>e.name));function $(e){return typeof e=="string"&&e.length>0?e:void 0}s($,"str");var Ry=10;function Ay(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,o=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=Ry&&r++,c>i&&(i=c);for(let p of a.ownership?.topAuthors??[])n.add(p.email.toLowerCase()||p.name);let l=a.lastCommits[0]?.dateIso;if(l){let p=Date.parse(l);Number.isFinite(p)&&p>o&&(o=p)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:o>0?Math.max(0,Math.floor((t-o)/864e5)):0}}s(Ay,"aggregateHistoryContext");function Me(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Me,"num");function nd(e){if(e===void 0)return{repoRoot:z(),scanDirs:void 0};let t=lr(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(nd,"anchorRepo");function rd(e,t){return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,projects:[],findings:[],hint:`No opinion \u2014 this directory could not be located, so no repository was scanned. ${t} Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. \`Asgard/Maind\`) or an absolute path. Nothing was verified as ${e}.`}}s(rd,"dirNotFound");async function od(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(a=>a.status==="open").length,o=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:o,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${o} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=$(n.for_path);if(i!==void 0){let d=Fl(i);if(d===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let u=await Ce(d.repoRoot,d.repoRelPath,{minFiles:r}),f=u.namespace,m=s(g=>g===null?null:`${f?.prefix??""}${g}`,"full"),h=f===null?"no_opinion":u.taken?"taken":"free";return{ok:h==="free",mode:"proposed_path",verdict:h,reason:h==="no_opinion"?"no_namespace":void 0,path:u.path,repo_root:d.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:m(u.number),taken:h==="no_opinion"?null:u.taken,suggestion:m(u.suggestion),held_by:u.sightings.map(g=>({kind:g.kind,where:g.where,path:g.path})),hint:h==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":u.taken?`${m(u.number)} is already held (see held_by). Create the file as ${m(u.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${m(u.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let o=Array.isArray(n.dirs)?n.dirs.filter(d=>typeof d=="string"):void 0;if(o!==void 0&&o.length>0){let d=new Map,u=[];for(let v of o){let k=lr(v);if(k===null){u.push(v);continue}let E=d.get(k.repoRoot)??new Set;E.add(k.repoRelDir),d.set(k.repoRoot,E)}if(d.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:u,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],m=[],h=[],g=[];for(let[v,k]of d){let E=[...k],R=E.includes(""),I=await Ie(v,{dirs:R?void 0:E,minFiles:r});f.push({repo_root:v,dirs:R?null:E}),m.push(...I.findings),h.push(...I.facts.namespaces.map(T=>({repo_root:v,dir:T.dir,prefix:T.prefix,file_count:T.fileCount}))),g.push(...I.facts.skipped)}let y=m.filter(v=>v.status==="open"),b=m.filter(v=>v.status==="info"),w=u.length>0?` ${u.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:y.length===0,open_count:y.length,preexisting_count:b.length,findings:y,preexisting:b.map(v=>`${v.namespace.prefix}${v.number}`),namespaces:h,skipped:g,scanned:f,...u.length>0?{unresolved_dirs:u}:{},hint:(y.length===0?h.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${y.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+w}}let a=z(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(d=>d.status==="open"),p=c.findings.filter(d=>d.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:p.length,findings:l,preexisting:p.map(d=>`${d.namespace.prefix}${d.number}`),namespaces:c.facts.namespaces.map(d=>({dir:d.dir,prefix:d.prefix,file_count:d.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:$(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(u=>typeof u=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=s(u=>r.findings.filter(f=>f.status===u),"of"),o=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let p="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",d=o.filter(u=>u.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:a.length,preexisting_count:c.length,findings:[...o,...a],preexisting:c.map(u=>u.id),coverage_note:p,hint:(r.ok?"The declared entries agree.":d.length>0?`${d.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${o.length-d.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${o.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+p}}case"check_theme_class_drift":{let r=$(n.dir),i,o;if(r!==void 0){let d=lr(r);if(d===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};i=d.repoRoot,o=d.repoRelDir===""?void 0:[d.repoRelDir]}else i=z(),o=void 0;let a=De(i,{dirs:o,baseRef:$(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(d=>d.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(d=>({file:d.file,class:d.klass,status:d.status,missing_token:d.token,namespace:d.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=nd($(n.dir));if(r===null)return rd("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Pe(r.repoRoot,{dirs:r.scanDirs,baseRef:$(n.base_ref),includeBaseline:n.include_baseline!==!1}),o="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+o}}case"check_migration_ledger_drift":{let r=nd($(n.dir));if(r===null)return rd("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=vo(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:$(n.remote_db_url)}),o=i.facts.projects.map(u=>({dir:u.dir,migration_count:u.migrationCount,verdict:u.verdict,database:{host:u.db.host,port:u.db.port,config_source:u.db.configSource,reachable:u.db.reachable,ledger_count:u.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=s(u=>i.findings.filter(f=>f.status===u),"of"),c=a("open"),l=a("warn"),p=a("info"),d=o.map(u=>u.database.port===null?`${u.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${u.dir}: ${u.database.host}:${u.database.port} (config from ${u.database.config_source}, reachable=${u.database.reachable}, ledger rows=${u.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:o,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:p.map(u=>u.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:d,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${d}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${d}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${d}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=$(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:$(n.kind),limit:Me(n.limit)})).map(o=>({...o,nodeKeyHash:pr(o.nodeKey)}))}case"codebase_trace":{let r=$(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:i,maxDepth:Me(n.max_depth),limit:Me(n.limit)})}case"codebase_snippet":{let r=$(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await e.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:pr(r)}}case"codebase_map":return e.getArchitecture({topN:Me(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:$(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Me(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language,file:i.filePath,start_line:i.startLine,node_key:i.nodeKey,node_key_hash:pr(i.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:$(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Me(n.limit)}),i;if(n.include_history!==!1)try{i=Ay(await e.fileHistory({since:$(n.since),limit:1}))}catch{i=void 0}let o;try{o=await e.reviewDetectors({baseRef:$(n.since)})}catch(l){o=ot(Bt(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,...r.headSha?{head_sha:r.headSha}:{},dirty:r.dirty,...r.baseSha?{base_sha:r.baseSha}:{},code_index_version:td,detector_coverage:o.coverage},c=o.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,p)=>l+p.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:pr(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...i?{history:i}:{}},verdict_args:{detector_findings:o.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:o.coverage,truncated:o.truncated,block_eligible:c,engines:o.engines,findings:o.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${o.findings.length} detector row(s) (${c} block-eligible, coverage ${o.coverage}) are hashes only; keep detector_findings even when it is []. Persisting a replayable record additionally needs commit_sha / diff_stats.head_sha.`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(o=>typeof o=="string"):void 0,i=await e.fileHistory({paths:r,since:$(n.since),limit:Me(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(o=>({path:o.path,last_commits:o.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:o.ownership?{top_authors:o.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:o.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(o=>({sha:o.sha,date_iso:o.dateIso,author_name:o.authorName,subject:o.subject,files_touched:o.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}s(od,"dispatchLocalTool");var fr=class{constructor(t=$l,n=null,r=z){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return So}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&id.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",o=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=await od(this.getEngine(),i,o),c=JSON.stringify(a,null,2);return this.recordSavings(i,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=Ol(a)?`${Ml} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(o=>o&&typeof o=="object"?o.name:void 0).filter(o=>typeof o=="string")),i=this.descriptors().filter(o=>!r.has(o.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=Kl(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};var Ty="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function sd(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:Ty}s(sd,"functionsOrigin");var Iy="/mcp-client-metrics-ingest",Cy=4e3,Ny="codebase_search_tokens_saved";async function ad(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${sd()}${Iy}`,n=new AbortController,r=setTimeout(()=>n.abort(),Cy);try{let i=await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"x-maind-device-id":e.deviceId,"user-agent":`@maind-dev/mcp-bridge/${e.bridgeVersion}`},body:JSON.stringify({metrics:[{session_id:e.sessionId,metric_key:Ny,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await i.text().catch(()=>""),i.ok}catch(i){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${i instanceof Error?i.message:String(i)}
840
+ `),!1}finally{clearTimeout(r)}}s(ad,"postSavingsMetric");Ro();hr();yr();bt();import{join as p_}from"node:path";var f_="<synthetic>";function eu(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:p_(qo,zo(e.cwd),`${e.transcript_stem}.jsonl`)}s(eu,"transcriptPathFromSideChannel");var xr=class{constructor(t){this.deps=t}static{s(this,"TranscriptMetaReader")}path=null;offset=0;model=null;title=null;async read(){try{let n=this.deps.resolvePath();if(n!==this.path&&(this.path=n,this.offset=0,this.model=null,this.title=null),n!==null){let i=await(this.deps.stream??Vo)(n,{start:this.offset});for(let o of i.events)if(o.kind==="title"){let a=o.title.trim();a.length>0&&(this.title=a)}else o.kind==="assistant"&&!o.isSidechain&&typeof o.model=="string"&&o.model.length>0&&o.model!==f_&&(this.model=o.model);i.bytesRead>this.offset&&(this.offset=i.bytesRead)}}catch{}let t=null;try{t=this.deps.fallbackModel?.()??null}catch{t=null}return{model:this.model??t,title:this.title}}};import{execFile as m_}from"node:child_process";var h_=8,g_=32;function y_(e){return e.split(`
841
+ `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,g_)}s(y_,"parsePorcelain");function b_(e,t=h_){let n=[];for(let r of e){let i=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(i.length===0)continue;let o=i.includes("/")?i.slice(0,i.lastIndexOf("/")):i;if(!(o.length===0||n.includes(o))&&(n.push(o),n.length>=t))break}return n}s(b_,"condenseToDirs");async function tu(e=__){let t=await e();if(t===null)return null;let n=b_(y_(t));return n.length>0?n:null}s(tu,"deriveWorkingPaths");async function __(){return await new Promise(e=>{m_("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(__,"defaultGitStatus");var fv=1,mv=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function hv(e){return mv.includes(e)}s(hv,"isHookSubcommand");var gv=6e4;async function yv(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==O()&&Ee(e),e;let t=O();if(t!==null)return t;let n=await ze(P);return n===null&&(process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
842
+ `),process.exit(1)),n.apiKey}s(yv,"ensureApiKey");async function bv(){let e=await ze(P);return e===null&&(process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
843
+ `),process.exit(1)),e.apiKey}s(bv,"reauth");async function _v(){let e=process.argv.slice(2).find(y=>!y.startsWith("-"));if(e==="install"){let y=process.argv.indexOf("install"),b=process.argv.slice(y+1),w=await Hl(b);process.exit(w)}if(e==="on-session-end"){let{runOnSessionEnd:y}=await Promise.resolve().then(()=>(Vu(),Bu));process.exit(await y())}if(e==="guard"){let y=process.argv.indexOf("guard"),{runGuard:b}=await Promise.resolve().then(()=>(tp(),ep));process.exit(await b(process.argv.slice(y+1)))}if(e==="guard-inject"){let{runGuardInject:y}=await Promise.resolve().then(()=>(ap(),sp));process.exit(await y())}if(e==="guard-gate"){let{runGuardGate:y}=await Promise.resolve().then(()=>(pp(),up));process.exit(await y())}if(e==="guard-stop"){let{runGuardStop:y}=await Promise.resolve().then(()=>(hp(),mp));process.exit(await y())}if(e==="gateway"){let y=process.argv.indexOf("gateway"),{runGateway:b}=await Promise.resolve().then(()=>(Zp(),Qp));process.exit(await b(process.argv.slice(y+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:y}=await Promise.resolve().then(()=>(_s(),bs));process.exit(await y())}if(e==="guard-cross-check"){let{runGuardCrossCheck:y}=await Promise.resolve().then(()=>(_s(),bs));process.exit(await y())}if(e==="on-index-refresh"){let{runOnIndexRefresh:y}=await Promise.resolve().then(()=>(vs(),ks));process.exit(await y())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:y}=await Promise.resolve().then(()=>(vs(),ks));process.exit(await y())}if(e!==void 0&&hv(e)){let y=await Promise.resolve().then(()=>(rs(),Ou)),b={"on-session-start":y.runOnSessionStart,"on-tool-use":y.runOnToolUse,"on-file-write":y.runOnFileWrite,"on-file-edit":y.runOnFileEdit,"on-repo-health":y.runOnRepoHealth,"on-write-health":y.runOnWriteHealth,"sync-config":y.runSyncConfig,flush:y.runFlush,status:y.runHookStatus}[e];process.exit(await b())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(P+`
844
+ `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(wv(),process.exit(0)),process.argv.includes("--reauth")&&(It(),await ze(P,process.stdout)===null&&process.exit(1),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
845
+ `),process.exit(0));let t=U(),n=await yv(),r=M(),o=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new ur:null,a=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new fr(void 0,o),c=`bridge-${pv()}`,l=s(async()=>{if(!o)return;let y=o.takePending();y.tokens<=0||await ad({apiKey:n,deviceId:t,sessionId:c,tokensSaved:y.tokens,bridgeVersion:P})},"flushSavings"),p=o?setInterval(()=>{l()},gv):null;p?.unref();let d=null,u=new gr({projectKey:r}),f=new xr({resolvePath:s(()=>eu(u.sideChannel()),"resolvePath"),fallbackModel:s(()=>u.sideChannel()?.model??null,"fallbackModel")}),m=new mr({projectKey:r,identity:u,sessionMeta:s(()=>f.read(),"sessionMeta"),postToolCall:s((y,b)=>d===null?Promise.reject(new Error("presence: no active forwarder")):d.postPresenceToolCall(y,b),"postToolCall"),deriveWorkingPaths:s(()=>tu(),"deriveWorkingPaths"),snapshot:r!==null?_d({projectKey:r}):void 0}),h=m.isEnabled?setInterval(()=>{m.pollActivity()},dd):null;if(h?.unref(),m.isEnabled){let y=s(b=>{m.end().finally(()=>process.exit(b))},"endAndExit");process.on("SIGTERM",()=>y(143)),process.on("SIGINT",()=>y(130))}let g=0;try{for(;;){let y=new bn({apiKey:n,deviceId:t,bridgeVersion:P,projectKey:r,localRouter:a,presence:m});d=y;try{await y.run();return}catch(b){if(b instanceof At&&g<fv){g+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${b.message}; re-authorizing\u2026
846
+ `),n=await bv();continue}throw b}}}finally{p&&clearInterval(p),h&&clearInterval(h),await m.end(),await l()}}s(_v,"main");function wv(){let e=["","@maind-dev/mcp-bridge \u2014 local MCP wrapper that pins your maind API key to this device.","","Usage:"," npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)"," npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble, hooks)"," npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow"," npx -y @maind-dev/mcp-bridge --version"," npx -y @maind-dev/mcp-bridge --help","","Run `install --help` for full setup flags:"," npx -y @maind-dev/mcp-bridge install --help","","Claude Code hook subcommands (wired by `install`; run them by hand only for","diagnostics). They read the hook payload on stdin and use the bridge's own","paired credential \u2014 no separate init:"," on-session-start open a tracked session (Tier-3 flat metrics)"," on-tool-use bump counters + evaluate the ADR-039 context advisory"," on-file-write block a Write that claims a taken number (ADR-263)"," on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)"," on-repo-health surface this worktree's repo-health findings before the first edit in it (ADR-323, never blocks)"," on-write-health after an edit, run the path-relevant checks (spec/theme/table-acl) and report what this branch introduced (ADR-323, never blocks)"," on-session-end session analytics + close/flush the tracked session"," sync-config pull your context thresholds from the server (ADR-039)"," flush post queued Tier-3 metrics now"," status show pairing, queued metrics and active thresholds","","Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:"," guard install wire the guard hook pack (consent per hook) + set mode"," guard status mode, guard-hook wiring, local enforcement-event counts"," guard mode <warn|block> | guard off | guard stop-gate <on|off>",' guard skip --session <id> --reason "\u2026" logged override (block-gate exit)'," (hook subcommands, wired by `guard install`: guard-inject, guard-gate, guard-stop)","","Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent","Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.","","Environment overrides (rarely needed):"," MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)"," MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)"," MAIND_CLIENT_VERSION Optional client version marker (max 64 chars)"," MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth"," MAIND_AUTO_ANNOUNCE Set to 'off' to disable automatic presence announces (ADR-242)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," XDG_CONFIG_HOME Override config-dir parent on Linux/BSD","","Auto-presence (ADR-242): the bridge announces this session on the repo's","shared working tree (project_key hash + branch only \u2014 no hostname, no paths),","refreshes while tools are actually called, and ends the row on exit.","Persistent opt-out / explicit machine_label via config.json in the maind",'config dir: { "auto_announce": false, "machine_label": "my-box" }',"","Place this in your .mcp.json (or equivalent):",""," {",' "mcpServers": {',' "maind": {',' "command": "npx",',' "args": ["-y", "@maind-dev/mcp-bridge"]'," }"," }"," }",""];process.stderr.write(e.join(`
847
+ `))}s(wv,"printHelp");_v().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
848
848
  `),process.exit(1)});