@maind-dev/mcp-bridge 0.68.0 → 0.70.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 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)>=yf}function bf(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 mf){let a=r[o];typeof a=="string"&&As.test(a)&&i.push({field:o,sha:a})}for(let[o,a]of hf){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 _f(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>=gf;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 wf(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=bf(e);if(n.length===0)return[];let r=wf(t),i=[];for(let{field:o,sha:a}of n){let c=_f(a,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var mf,hf,As,gf,Ts,yf,Gr=_(()=>{"use strict";mf=["commit_sha","base_sha","head_sha"],hf=[["diff_stats","head_sha"],["diff_stats","base_sha"]],As=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,gf=7,Ts=12,yf=10;s(Cs,"isDenyGrade");s(bf,"extractShaArgs");s(_f,"classifySha");s(Ve,"shaFindingText");s(Ns,"cleanGitEnv");s(un,"resolveRepoRootForSha");s(wf,"gitShaResolver");s(pn,"inspectLineForShas")});import{execFileSync as kf}from"node:child_process";import{createHash as vf}from"node:crypto";import{mkdirSync as Sf,readFileSync as Ef,renameSync as xf,writeFileSync as Rf}from"node:fs";import{dirname as Af,join as Ps}from"node:path";function ae(e=process.cwd()){try{let t=kf("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 vf("sha256").update(e).digest("hex").slice(0,16)}function mn(e){return Ps(e,Tf)}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);Sf(Af(o),{recursive:!0});let a=`${o}.${process.pid}.tmp`;Rf(a,JSON.stringify(i,null,2),"utf8"),xf(a,o)}catch{}}function Ms(e,t){try{let n=Ef(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=If(t.cached_at,n),i=t.result.instructions??"",o={...t.result,instructions:`${r}
2
+ var Rs=Object.defineProperty;var s=(e,t)=>Rs(e,"name",{value:t,configurable:!0});var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var q=(e,t)=>{for(var n in t)Rs(e,n,{get:t[n],enumerable:!0})};function Ts(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 jr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Hr(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function Ur(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Gr=b(()=>{"use strict";s(Ts,"parseFrame");s(Be,"denyResult");s(jr,"toolEvent");s(Hr,"policyEvent");s(Ur,"shaEvent")});import{execFileSync as Ns}from"node:child_process";function Ps(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=wf}function kf(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 yf){let a=r[o];typeof a=="string"&&Is.test(a)&&i.push({field:o,sha:a})}for(let[o,a]of _f){let c=r[o];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&Is.test(l)&&i.push({field:`${o}.${a}`,sha:l})}return i}function vf(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,Cs);for(let i=Cs;i>=bf;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 Ds(){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=Ns("git",["rev-parse","--show-toplevel"],{cwd:e,env:Ds(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function Sf(e){return t=>{try{let r=Ns("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Ds(),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=kf(e);if(n.length===0)return[];let r=Sf(t),i=[];for(let{field:o,sha:a}of n){let c=vf(a,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var yf,_f,Is,bf,Cs,wf,Wr=b(()=>{"use strict";yf=["commit_sha","base_sha","head_sha"],_f=[["diff_stats","head_sha"],["diff_stats","base_sha"]],Is=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,bf=7,Cs=12,wf=10;s(Ps,"isDenyGrade");s(kf,"extractShaArgs");s(vf,"classifySha");s(Ve,"shaFindingText");s(Ds,"cleanGitEnv");s(un,"resolveRepoRootForSha");s(Sf,"gitShaResolver");s(pn,"inspectLineForShas")});import{execFileSync as Ef}from"node:child_process";import{createHash as xf}from"node:crypto";import{mkdirSync as Rf,readFileSync as Af,renameSync as Tf,writeFileSync as If}from"node:fs";import{dirname as Cf,join as Os}from"node:path";function ae(e=process.cwd()){try{let t=Ef("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 xf("sha256").update(e).digest("hex").slice(0,16)}function mn(e){return Os(e,Nf)}function Ms(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Fs(e,t,n,r=new Date().toISOString()){try{if(!Ms(n))return;let i={version:Kr,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},o=mn(e);Rf(Cf(o),{recursive:!0});let a=`${o}.${process.pid}.tmp`;If(a,JSON.stringify(i,null,2),"utf8"),Tf(a,o)}catch{}}function Ls(e,t){try{let n=Af(mn(e),"utf8"),r=JSON.parse(n);return r.version!==Kr||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Ms(r.result)?null:{version:Kr,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function $s(e,t,n=new Date){let r=Pf(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 If(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${Cf(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function Cf(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,Tf,qe=_(()=>{"use strict";Wr=1,Tf=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(If,"fallbackMarker");s(Cf,"relativeAge")});import{existsSync as _n,mkdirSync as Gf,readFileSync as Ls,writeFileSync as Vr,chmodSync as $s}from"node:fs";import{homedir as Wf,hostname as Kf,platform as Br,release as Bf}from"node:os";import{randomUUID as Vf}from"node:crypto";import{join as Se}from"node:path";function Tt(){let e=Wf(),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)||Gf(e,{recursive:!0,mode:448})}function U(){let e=Tt();js(e);let t=Se(e,qf);if(_n(t)){let r=Ls(t,"utf8").trim();if(Yf(r))return r}let n=Vf();Vr(t,n+`
5
- `,{encoding:"utf8",mode:384});try{$s(t,384)}catch{}return n}function Yf(e){return Jf.test(e)}function qr(){return Se(Tt(),zf)}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 D(){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-${Kf()}`}catch{return"mcp-bridge"}}function wn(e){return{os:`${Br()} ${Bf()}`,ide:"mcp-bridge",ext_version:e,device_id:U()}}var qf,zf,Jf,B=_(()=>{"use strict";s(Tt,"configDir");s(js,"ensureDir");qf="device-id",zf="api-key";s(U,"ensureDeviceId");Jf=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(Yf,"isUuid");s(qr,"apiKeyPath");s(Ee,"writeApiKey");s(D,"readApiKey");s(It,"clearApiKey");s(Hs,"bridgeLabel");s(wn,"clientMeta")});var P,xe=_(()=>{"use strict";P="0.68.0"});import{execFileSync as om}from"node:child_process";import{createHash as sm}from"node:crypto";function am(e){return sm("sha256").update(e).digest("hex")}function cm(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=cm(e);return t?am(t):null}function O(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&lm.test(e))return e;let t;try{t=om("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?zr(t):null}var lm,ge=_(()=>{"use strict";s(am,"sha256Hex");s(cm,"normalizeRemoteUrl");s(zr,"projectKeyFromRemote");lm=/^[a-f0-9]{64}$/;s(O,"computeProjectKey")});import um from"node:path";import{fileURLToPath as pm}from"node:url";function fm(e,t=um.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"):fm(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=pm(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(fm,"isEphemeralEntry");s(ee,"resolveBridgeLaunch");s(te,"currentBridgeEntry");s(Je,"launchToShellCommand");s(vn,"isNpxForm");s(Sn,"isLegacyHookForm");s(Ys,"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(hm(t))return null;throw t}}async function Jr(e){await M.mkdir(e,{recursive:!0})}async function F(e,t,n){let r=En.dirname(e);await Jr(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(gm(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 ra(e,t){let n=await G(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function hm(e){return ia(e)&&e.code==="ENOENT"}function gm(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(F,"atomicWriteFile");s(ra,"hasLinePrefix");s(hm,"isNoEnt");s(gm,"isWindowsRenameFailure");s(ia,"isNodeError")});import{existsSync as Dm}from"node:fs";import*as da from"node:path";function Dt(e,t={},n=Zr){let r=t.fileExists??Dm,i=t.expectedCommand??Om,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=Mm(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=Fm(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 Om(e){return Je(ee({entryPath:te(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function Mm(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 Fm(e){for(let t of Lm(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return da.isAbsolute(t)?t:null;return null}function Lm(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(Om,"defaultExpectedCommand");s(Mm,"findCommand");s(Fm,"extractScriptPath");s(Lm,"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=jm(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 Hm(e.out,`
4
+ ${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:o})}function Pf(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${Df(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function Df(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 Kr,Nf,qe=b(()=>{"use strict";Kr=1,Nf=Os(".maind","conventions-cache.json");s(ae,"resolveRepoRoot");s(fn,"keyFingerprint");s(mn,"cachePath");s(Ms,"hasInstructions");s(Fs,"writeConventionsCache");s(Ls,"readConventionsCache");s($s,"buildCachedInitializeResponse");s(Pf,"fallbackMarker");s(Df,"relativeAge")});import{existsSync as bn,mkdirSync as Bf,readFileSync as js,writeFileSync as qr,chmodSync as Hs}from"node:fs";import{homedir as Vf,hostname as qf,platform as Vr,release as zf}from"node:os";import{randomUUID as Jf}from"node:crypto";import{join as Se}from"node:path";function Tt(){let e=Vf(),t=process.env;if(Vr()==="darwin")return Se(e,"Library","Application Support","maind");if(Vr()==="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 Us(e){bn(e)||Bf(e,{recursive:!0,mode:448})}function U(){let e=Tt();Us(e);let t=Se(e,Yf);if(bn(t)){let r=js(t,"utf8").trim();if(Zf(r))return r}let n=Jf();qr(t,n+`
5
+ `,{encoding:"utf8",mode:384});try{Hs(t,384)}catch{}return n}function Zf(e){return Qf.test(e)}function zr(){return Se(Tt(),Xf)}function Ee(e){let t=Tt();Us(t);let n=zr();qr(n,e+`
6
+ `,{encoding:"utf8",mode:384});try{Hs(n,384)}catch{}}function O(){let e=zr();if(!bn(e))return null;let t=js(e,"utf8").trim();return t.length>0?t:null}function It(){let e=zr();bn(e)&&qr(e,"",{encoding:"utf8",mode:384})}function Gs(){try{return`mcp-bridge-${qf()}`}catch{return"mcp-bridge"}}function wn(e){return{os:`${Vr()} ${zf()}`,ide:"mcp-bridge",ext_version:e,device_id:U()}}var Yf,Xf,Qf,B=b(()=>{"use strict";s(Tt,"configDir");s(Us,"ensureDir");Yf="device-id",Xf="api-key";s(U,"ensureDeviceId");Qf=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(Zf,"isUuid");s(zr,"apiKeyPath");s(Ee,"writeApiKey");s(O,"readApiKey");s(It,"clearApiKey");s(Gs,"bridgeLabel");s(wn,"clientMeta")});var P,xe=b(()=>{"use strict";P="0.70.0"});import{execFileSync as cm}from"node:child_process";import{createHash as lm}from"node:crypto";function dm(e){return lm("sha256").update(e).digest("hex")}function um(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 Jr(e){let t=um(e);return t?dm(t):null}function M(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&pm.test(e))return e;let t;try{t=cm("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Jr(t):null}var pm,ge=b(()=>{"use strict";s(dm,"sha256Hex");s(um,"normalizeRemoteUrl");s(Jr,"projectKeyFromRemote");pm=/^[a-f0-9]{64}$/;s(M,"computeProjectKey")});import mm from"node:path";import{fileURLToPath as hm}from"node:url";function gm(e,t=mm.sep){return e.split(t).includes("_npx")}function ee(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",Zs,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):gm(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=hm(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}=${Qs(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Qs(n)).join(" ")}function vn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Zs)}function Sn(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Qs(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Zs,Ye=b(()=>{"use strict";Zs="@maind-dev/mcp-bridge";s(gm,"isEphemeralEntry");s(ee,"resolveBridgeLaunch");s(te,"currentBridgeEntry");s(Je,"launchToShellCommand");s(vn,"isNpxForm");s(Sn,"isLegacyHookForm");s(Qs,"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(_m(t))return null;throw t}}async function Yr(e){await F.mkdir(e,{recursive:!0})}async function L(e,t,n){let r=En.dirname(e);await Yr(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(bm(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 oa(e,t){let n=await G(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function _m(e){return sa(e)&&e.code==="ENOENT"}function bm(e){return!sa(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function sa(e){return typeof e=="object"&&e!==null&&"code"in e}var ce=b(()=>{"use strict";s(G,"readFileSafe");s(Yr,"ensureDir");s(L,"atomicWriteFile");s(oa,"hasLinePrefix");s(_m,"isNoEnt");s(bm,"isWindowsRenameFailure");s(sa,"isNodeError")});import{existsSync as Fm}from"node:fs";import*as pa from"node:path";function Dt(e,t={},n=ei){let r=t.fileExists??Fm,i=t.expectedCommand??Lm,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Zr(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=$m(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=jm(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 ti(e){return e.some(t=>t.status!=="ok")}function An(e){return e.some(t=>t.remedy==="run-install")}function Lm(e){return Je(ee({entryPath:te(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function $m(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Zr(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Zr(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function jm(e){for(let t of Hm(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return pa.isAbsolute(t)?t:null;return null}function Hm(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 Zr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ei,Rn,Ot=b(()=>{"use strict";Ye();ei=[{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(ti,"hasWiringDrift");s(An,"needsInstallRun");s(Lm,"defaultExpectedCommand");s($m,"findCommand");s(jm,"extractScriptPath");s(Hm,"tokenize");s(Zr,"isObject")});import*as ii from"node:path";import*as ma from"node:readline";async function ha(e,t){let n=ii.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: ${ni(f)}`}}let o,a="create";if(i===null||i.trim().length===0)o={};else{a="merge";try{let f=JSON.parse(i);if(!ri(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: ${ni(f)}`}}}let c=Gm(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 Wm(e.out,`
7
7
  Merge a ${t.event} hook into ${n}?
8
8
  ${t.consentDescription}
9
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 F(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 $m(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:$m(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 jm(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 Hm(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($m,"targetKeyFor");s(ii,"mergeSubcommandHook");s(ha,"mergeAllSubcommandHooks");s(jm,"findExistingHookCommand");s(Hm,"promptYesNo");s(ni,"isObject");s(ti,"errMessage")});import{existsSync as Um,readFileSync as Gm}from"node:fs";import{join as Wm}from"node:path";function de(){return Wm(Tt(),"config.json")}function ne(){try{let e=de();if(!Um(e))return null;let t=JSON.parse(Gm(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 Xm}from"node:child_process";import{createHash as Qm}from"node:crypto";function si(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 eh(e){let t=Zm(e);return t?si(t):null}function nh(e){return typeof e=="string"&&th.test(e)}function Sa(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(nh(t))return t;let n;try{n=Xm("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?eh(n):null}var th,ai=_(()=>{"use strict";s(si,"sha256Hex");s(Zm,"normalizeRemoteUrl");s(eh,"projectKeyFromRemote");th=/^[a-f0-9]{64}$/;s(nh,"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 rh(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 ih(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=rh(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Qe(e,t,n,r){for(let i of ih(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(rh,"calleeName");s(ih,"collectCallTargets");s(Qe,"addCallRefs")});function xa(e,t){let n=Pn();for(let r of e.namedChildren)oh(r,t,n);return n}function Ra(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function oh(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??ah(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":sh(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 sh(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 ah(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(oh,"handleTopLevel");s(sh,"addClass");s(Mn,"makeNode");s(ah,"firstDottedName")});function Ca(e,t){let n=Pn();for(let r of e.namedChildren)lh(r,t,n);return n}function ch(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function lh(e,t,n){let r=ch(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:uh(i)});return}case"function_declaration":case"generator_function_declaration":{Ta(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{dh(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 dh(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 uh(e){return e.replace(/^["'`]|["'`]$/g,"")}var Ia,Na=_(()=>{"use strict";Mt();On();Ia="call_expression";s(Ca,"extractTypescript");s(ch,"unwrapExport");s(lh,"handleTopLevel");s(Ta,"addFunctionLike");s(li,"addSimpleNamed");s(dh,"addClass");s(Fn,"makeNode");s(uh,"stripQuotes")});import{createRequire as ph}from"node:module";import{join as fh}from"node:path";function Oa(e,t){return t?fh(t,Pa[e]):ph(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 mh}from"node:path";import di from"web-tree-sitter";var hh,Ln,Fa=_(()=>{"use strict";Mt();Nn();Aa();Na();On();Ma();hh=["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=>mh(this.assetDir,t||Da),"locateFile")}:void 0),this.parser=new di,this.initialized=!0)}supports(t){return hh.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),!gh.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=yh(e.filePath,a.specifier,t.files);c&&o(a.fromModuleKey,Tn(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}function yh(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 gh,$n,Wa=_(()=>{"use strict";Mt();gh=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(yh,"resolveImportTarget")});import{execFileSync as bh}from"node:child_process";import{createHash as _h}from"node:crypto";import{readdirSync as wh,statSync as kh}from"node:fs";import{posix as qa,sep as Ka}from"node:path";function S(e,t){try{return bh("git",[...vh,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function Sh(e){return Ka==="/"?e:e.split(Ka).join("/")}function jn(e){let t=[];for(let n of e){let r=Sh(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=wh(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=kh(qa.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Un(e){return _h("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,vh,Ze,W=_(()=>{"use strict";Nn();Ba=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),vh=["-c","diff.renames=true","-c","core.quotePath=false"];s(S,"runGit");Ze=S;s(Sh,"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")>Eh?c="none":Th(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 Th(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=Ah.exec(l);if(p){if(i++,i>xh){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<Rh&&r.addedLines.push(l.slice(1))}c()}var Eh,xh,Rh,ec,Ah,nc=_(()=>{"use strict";W();Eh=16*1024*1024,xh=500,Rh=4e3,ec=256*1024,Ah=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(tc,"changedHunks");s(Th,"parseUnifiedDiff")});function Nh(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(Ih).filter(t=>t.trim().length>0)}function oc(e){let[t,n,r,i,o]=e.replace(/\n+$/,"").split(Ch);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:o??""}}function Ph(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=Nh(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:Ph(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 Ih,Ch,sc,hi,Wn,rc,gi=_(()=>{"use strict";W();Ih="",Ch="\0",sc=200,hi=50,Wn=100,rc="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";s(Nh,"clamp");s(ic,"splitRecords");s(oc,"parseHistoryRecord");s(Ph,"aggregateOwnership");s(ac,"readFileHistory")});import{execFileSync as Dh}from"node:child_process";import{readdirSync as Oh,statSync as cc}from"node:fs";import{isAbsolute as Mh,join as yi,relative as Fh,resolve as Lh}from"node:path";function jh(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function Hh(e,t){try{let n=Dh("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 Uh(e){let t;try{t=Oh(e)}catch{return null}for(let n of t.filter(jh))try{let r=cc(yi(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function Gh(e){try{return cc(e).isDirectory()}catch{return!1}}function Wh(e,t){let n=Fh(e,t);return!n||n.startsWith("..")?t:n}function bi(e){let t=$h.filter(c=>Gh(yi(e,c))),n=Hh(e,"core.hooksPath"),r=n?Mh(n)?n:Lh(e,n):yi(e,".git","hooks"),i=Wh(e,r),o=Uh(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 $h,wi=_(()=>{"use strict";$h=[".githooks",".husky"];s(jh,"isRealHook");s(Hh,"gitConfig");s(Uh,"hasExecutableHook");s(Gh,"isDir");s(Wh,"displayPath");s(bi,"resolveHookState");s(_i,"describeHookState")});import{posix as lc}from"node:path";function et(e){let t=Kh.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 Kh,Lt=_(()=>{"use strict";W();Kh=/^(\d+)_.+\.sql$/;s(et,"parseMigrationVersion");s(ue,"compareVersions");s(Te,"discoverSupabaseProjects");s(dc,"resolveDefaultBranch")});import{execFileSync as Bh}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 Jh(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=Yh(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=x.dirname(r)}return null}function Yh(e,t){let n=[];for(let r of qh){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>zh)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=Xh(e.hooks);return o&&t.push(o),Qh(t)}function Xh(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 Qh(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 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 eg(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 tg(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 ng(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 rg(e){try{return Te(e).map(t=>x.join(x.dirname(t.dir),"config.toml"))}catch{return[]}}function ig(e){let t=S(e,["ls-files","-z","--",...Vh]);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(!og(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 og(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=Zh(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"])),A=pe(S(e,["rev-parse","@{u}"]));l=T!=null&&A!=null?T===A: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[A,j]=T.split(/\s+/).map(N=>Number.parseInt(N,10));Number.isFinite(A)&&(u=A),Number.isFinite(j)&&(d=j)}}let m=(S(e,["status","--porcelain"])??"").split(`
21
- `).filter(T=>T.trim().length>0).length,h=eg(e),g=pe(S(e,["rev-parse","--show-toplevel"]))??e,y=tg(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(j=>H(x.join(b,j))&&!H(x.join(g,j)),"here"),A=[...hc,...rg(g),...ng(g),...t.probePaths??[]];k={mainWorktreePath:b,currentWorktreePath:g,missing:[...new Set(A.filter(T))],missingDeps:ig(g).filter(j=>T(j.dir))}}let E=Jh(g,e),R=t.includeRelease===!1?null:pg(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: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 cg(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>=ag)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 lg(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 dg(e){let t=[];for(let n of cg(e)){let r=n==="."?e:x.join(e,n),i=s(o=>n==="."?o:x.join(n,o),"prefix");for(let o of lg(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 ug(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=dg(e),r=ug(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>sg&&t.push({packageDir:i,buildDir:d,srcNewerByMs:Math.round(y),impact:u})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}function pg(e,t){if(!t)return null;let n=fg(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 fg(e,t){try{return Bh("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,Vh,qh,zh,uc,sg,ki,pc,ag,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"},Vh=Object.keys(gc).flatMap(e=>[e,"*/"+e]),qh=["scripts"],zh=512*1024;s(Jh,"gatherToolCopyDrift");s(Yh,"compareToolDirs");s(yc,"computeDivergence");s(Xh,"computeHookFinding");uc={open:0,warn:1,info:2,passed:3};s(Qh,"sortFindings");s(bc,"isHealthy");s(pe,"trimOrNull");s(Zh,"resolveDefaultBranch");s(eg,"detectInProgressOp");s(tg,"parseWorktrees");s(ng,"readWorktreeRequirements");s(rg,"discoverSupabaseConfigProbes");s(ig,"discoverDependencyDirs");s(og,"isWorkspaceRoot");s(Si,"hasWorkspaceMarkers");s(_c,"gatherRepoHealthFacts");s(Ei,"samePath");sg=2e3,ki=64,pc=4e3,ag=3,fc=400;s(cg,"findWorkspaceRoots");s(lg,"workspacePatternsAt");s(dg,"listWorkspacePackageDirs");s(mc,"newestMtimeUnder");s(ug,"consumedWorkspaceNames");s(wc,"gatherStalePackageBuilds");s(pg,"gatherReleaseFact");s(fg,"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=mg.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 hg(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=hg(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,mg,Ci,vc,Ht=_(()=>{"use strict";W();Ti="could not diff against the base ref \u2014 everything reported as info";s(Ii,"isNumberCollisionsGraded");mg=/^(?<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(hg,"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 gg(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(gg)}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(gg,"codePointCompare");s(Tc,"normalizeEvidenceForHash");s(Ut,"hashDetectorEvidence")});import{existsSync as yg,readFileSync as Ic}from"node:fs";import{posix as bg}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 _g(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=>_g(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 wg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ui(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${wg(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 kg(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=kg(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 vg(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 ${vg(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 Sg(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(...Sg(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 Eg(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 xg(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)=>bg.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(!yg(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 xg(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:Eg(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(_g,"stripLeadingTrivia");s(it,"splitTopLevel");s(Dc,"readStringLiteral");s(wg,"escapeRe");s(Ui,"findSymbolArray");s(Gi,"parseObjectFields");s(kg,"objectFieldRaw");s(Oc,"pickFields");s(Mc,"makeOrdinals");s(Fc,"extractObjectArray");s(Lc,"extractNestedList");s(Cc,"extractRecords");s($c,"isGrounded");s(jc,"findingId");s(vg,"partitionOf");s(Hc,"compareContract");s(Sg,"checkAssertions");s(Nc,"unreadable");Pc={open:0,warn:1,info:2,passed:3};s(Uc,"computeSpecDrift");s(Hi,"trimOrNull");s(Xn,"parseManifest");s(Eg,"resolveDefaultBranch");s(xg,"declaredPaths");s(Gc,"gatherSpecDriftFacts");s(Ne,"checkSpecDrift");s(Wi,"isSpecDriftGraded")});import{readFileSync as Rg}from"node:fs";import{join as Ag,posix as Tg}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 Ig(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(Cg.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=Ig(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 Pg(e,t){try{let n=Rg(e,"utf8");return n.length>t?null:n}catch{return null}}function Dg(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=Tg.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??Ng,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=Pg(Ag(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:Dg(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,Cg,Ng,Qn,Vi,Zn=_(()=>{"use strict";W();Lt();s(Wc,"stripSql");s(X,"normalizeQualifiedIdent");s(fe,"splitTopLevel");Kt=["INSERT","UPDATE","DELETE"];s(Ig,"parseDefaultAclTables");Cg=/^(?: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");Ng=5e6,Qn="\u2014 findings reported ungraded (open)",Vi="\u2014 baseline degraded";s(qi,"isTableAclGraded");s(Pg,"safeRead");s(Dg,"baseFilesFor");s(Pe,"checkTableAclLint")});import{readFileSync as Og}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(Mg))t.add(n[1]);return t}function Qi(e){return new Set([...e].map(t=>t.split("-")[0]))}function Qc(e){return e.split(`
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: ${ni(f)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function ga(e){let t=ii.join(e.homeDir,fa);return ha(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 ${fa} into every new Claude Code session.`})}function Um(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function oi(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 ha(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:Um(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 ya(e){let t=[];for(let n of ei)t.push(await oi(e,n));return t}function Gm(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!ri(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!ri(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function Wm(e,t){e.write(t);let n=ma.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 ri(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ni(e){return e instanceof Error?e.message:String(e)}var fa,si=b(()=>{"use strict";ce();Ye();Ot();fa=".claude/maind-session-start-reminder.md";s(ha,"mergeClaudeHook");s(ga,"mergeSessionStartHook");s(Um,"targetKeyFor");s(oi,"mergeSubcommandHook");s(ya,"mergeAllSubcommandHooks");s(Gm,"findExistingHookCommand");s(Wm,"promptYesNo");s(ri,"isObject");s(ni,"errMessage")});import{existsSync as Km,readFileSync as Bm}from"node:fs";import{join as Vm}from"node:path";function de(){return Vm(Tt(),"config.json")}function ne(){try{let e=de();if(!Km(e))return null;let t=JSON.parse(Bm(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=b(()=>{"use strict";B();s(de,"bridgeConfigPath");s(ne,"readBridgeConfig")});import{execFileSync as eh}from"node:child_process";import{createHash as th}from"node:crypto";function ai(e){return th("sha256").update(e).digest("hex")}function nh(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 rh(e){let t=nh(e);return t?ai(t):null}function oh(e){return typeof e=="string"&&ih.test(e)}function xa(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(oh(t))return t;let n;try{n=eh("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?rh(n):null}var ih,ci=b(()=>{"use strict";s(ai,"sha256Hex");s(nh,"normalizeRemoteUrl");s(rh,"projectKeyFromRemote");ih=/^[a-f0-9]{64}$/;s(oh,"isProjectKey");s(xa,"computeProjectKey")});function Tn(e){return`${e}#<module>`}function In(e,t,n){return`${e}#${t}:${n}`}var Mt=b(()=>{"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 li(e){return e.toLowerCase().endsWith(".d.ts")}var Nn=b(()=>{"use strict";s(Cn,"languageForPath");s(li,"isSkippablePath")});function Pn(){return{nodes:[],edges:[],refs:[],imports:[]}}function be(e){return e+1}function Dn(e){return(e.text.split(`
11
+ `,1)[0]??"").trim().slice(0,200)}function sh(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 ah(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=sh(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Qe(e,t,n,r){for(let i of ah(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}var On=b(()=>{"use strict";s(Pn,"newResult");s(be,"line1");s(Dn,"signatureOf");s(sh,"calleeName");s(ah,"collectCallTargets");s(Qe,"addCallRefs")});function Aa(e,t){let n=Pn();for(let r of e.namedChildren)ch(r,t,n);return n}function Ta(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function ch(e,t,n){let r=Ta(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??dh(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,Ra);return}case"class_definition":lh(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 lh(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=Ta(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,Ra)}}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:be(e.startPosition.row),endLine:be(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Dn(e),doc:null}}function dh(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var Ra,Ia=b(()=>{"use strict";Mt();On();Ra="call";s(Aa,"extractPython");s(Ta,"unwrapDecorated");s(ch,"handleTopLevel");s(lh,"addClass");s(Mn,"makeNode");s(dh,"firstDottedName")});function Pa(e,t){let n=Pn();for(let r of e.namedChildren)ph(r,t,n);return n}function uh(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function ph(e,t,n){let r=uh(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:mh(i)});return}case"function_declaration":case"generator_function_declaration":{Ca(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{fh(r,t,n);return}case"interface_declaration":di(r,t,n,"interface");return;case"type_alias_declaration":di(r,t,n,"type_alias");return;case"enum_declaration":di(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";Ca(i,t,n,c?"function":"variable",o,a)}return}default:return}}function Ca(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,Na)}function di(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 fh(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,Na)}}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:be(e.startPosition.row),endLine:be(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Dn(e),doc:null}}function mh(e){return e.replace(/^["'`]|["'`]$/g,"")}var Na,Da=b(()=>{"use strict";Mt();On();Na="call_expression";s(Pa,"extractTypescript");s(uh,"unwrapExport");s(ph,"handleTopLevel");s(Ca,"addFunctionLike");s(di,"addSimpleNamed");s(fh,"addClass");s(Fn,"makeNode");s(mh,"stripQuotes")});import{createRequire as hh}from"node:module";import{join as gh}from"node:path";function Fa(e,t){return t?gh(t,Oa[e]):hh(import.meta.url).resolve(`tree-sitter-wasms/out/${Oa[e]}`)}var Oa,Ma,La=b(()=>{"use strict";Oa={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Ma="tree-sitter.wasm";s(Fa,"grammarPath")});import{join as yh}from"node:path";import ui from"web-tree-sitter";var _h,Ln,$a=b(()=>{"use strict";Mt();Nn();Ia();Da();On();La();_h=["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 ui.init(this.assetDir?{locateFile:s(t=>yh(this.assetDir,t||Ma),"locateFile")}:void 0),this.parser=new ui,this.initialized=!0)}supports(t){return _h.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:be(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},p={filePath:t,language:r,source:n,moduleKey:c},d=r==="python"?Aa(a,p):Pa(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 ui.Language.load(Fa(t,this.assetDir)),this.grammars.set(t,n)),n}}});function ja(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
12
+ `).slice(0,1e3)}var Ha=b(()=>{"use strict";s(ja,"nodeEmbedText")});var pi,fi=b(()=>{"use strict";pi=["function","method","class","interface","enum","type_alias"]});function Ua(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 Ga=b(()=>{"use strict";s(Ua,"cosineSimilarity")});import{posix as mi}from"node:path";function Wa(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!bh.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 Ka(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=wh(e.filePath,a.specifier,t.files);c&&o(a.fromModuleKey,Tn(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}function wh(e,t,n){if(!t.startsWith("."))return null;let r=mi.normalize(mi.join(mi.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 bh,$n,Ba=b(()=>{"use strict";Mt();bh=new Set(["function","method","class","interface","enum","type_alias"]),$n=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];s(Wa,"buildResolutionIndex");s(Ka,"resolveFileEdges");s(wh,"resolveImportTarget")});import{execFileSync as kh}from"node:child_process";import{createHash as vh}from"node:crypto";import{readdirSync as Sh,statSync as Eh}from"node:fs";import{posix as Ja,sep as Va}from"node:path";function S(e,t){try{return kh("git",[...xh,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function Rh(e){return Va==="/"?e:e.split(Va).join("/")}function jn(e){let t=[];for(let n of e){let r=Rh(n).trim();if(!r||li(r))continue;let i=Cn(r);i&&t.push({path:r,language:i})}return t}function Ya(e){return jn(e)}function Xa(e){let t=Ze(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return jn(t.split(`
13
+ `));let n=[];return Qa(e,"",n),jn(n)}function Qa(e,t,n){let r;try{r=Sh(Ja.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&qa.has(i.name)||qa.has(i.name))continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?Qa(e,o,n):i.isFile()&&n.push(o)}}function hi(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?hi(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=za((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=za(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 za(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Za(e,t={}){let n=Hn(e,t);return n===null?null:jn(n.keys())}function ec(e,t){try{let n=Eh(Ja.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Un(e){return vh("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 tc(e){let t=Ze(e,["status","--porcelain","-uall"]);return t!==null&&t.trim().length>0}var qa,xh,Ze,W=b(()=>{"use strict";Nn();qa=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),xh=["-c","diff.renames=true","-c","core.quotePath=false"];s(S,"runGit");Ze=S;s(Rh,"toPosix");s(jn,"classify");s(Ya,"classifyPaths");s(Xa,"discoverSourceFiles");s(Qa,"walk");s(hi,"resolveDiffBase");s(Hn,"enumerateChangedPaths");s(za,"unquote");s(Za,"changedSourceFiles");s(ec,"statFile");s(Un,"hashContent");s(Ft,"headCommit");s(Gn,"resolveCommitSha");s(tc,"isWorktreeDirty")});function rc(e,t={}){if(S(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?hi(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")>Ah?c="none":Nh(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 Nh(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=Ch.exec(l);if(p){if(i++,i>Th){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<Ih&&r.addedLines.push(l.slice(1))}c()}var Ah,Th,Ih,nc,Ch,ic=b(()=>{"use strict";W();Ah=16*1024*1024,Th=500,Ih=4e3,nc=256*1024,Ch=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(rc,"changedHunks");s(Nh,"parseUnifiedDiff")});function Oh(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function sc(e){return e.split(Ph).filter(t=>t.trim().length>0)}function ac(e){let[t,n,r,i,o]=e.replace(/\n+$/,"").split(Dh);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:o??""}}function Mh(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 lc(e,t,n={}){let r=Oh(n.limit,20,100),i=n.includeOwnership!==!1,o=Math.max(r,cc),a=t.map(d=>d.trim()).filter(d=>d.length>0&&!d.startsWith(":")),c=a.slice(0,gi),l=[];for(let d of c){let u=S(e,["log","-n",String(o),oc,"--",d]),f=u===null?[]:sc(u).map(ac).filter(m=>m!==null);l.push({path:d,lastCommits:f.slice(0,r),ownership:i?{topAuthors:Mh(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),oc,"--name-only","--",...c]),m=[];if(f!==null)for(let h of sc(f)){let g=h.split(`
18
+ `),y=ac(g[0]??"");if(!y)continue;let _=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:_})}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>gi}}var Ph,Dh,cc,gi,Wn,oc,yi=b(()=>{"use strict";W();Ph="",Dh="\0",cc=200,gi=50,Wn=100,oc="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";s(Oh,"clamp");s(sc,"splitRecords");s(ac,"parseHistoryRecord");s(Mh,"aggregateOwnership");s(lc,"readFileHistory")});import{execFileSync as Fh}from"node:child_process";import{readdirSync as Lh,statSync as dc}from"node:fs";import{isAbsolute as $h,join as _i,relative as jh,resolve as Hh}from"node:path";function Gh(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function Wh(e,t){try{let n=Fh("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 Kh(e){let t;try{t=Lh(e)}catch{return null}for(let n of t.filter(Gh))try{let r=dc(_i(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function Bh(e){try{return dc(e).isDirectory()}catch{return!1}}function Vh(e,t){let n=jh(e,t);return!n||n.startsWith("..")?t:n}function bi(e){let t=Uh.filter(c=>Bh(_i(e,c))),n=Wh(e,"core.hooksPath"),r=n?$h(n)?n:Hh(e,n):_i(e,".git","hooks"),i=Vh(e,r),o=Kh(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 wi(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 Uh,ki=b(()=>{"use strict";Uh=[".githooks",".husky"];s(Gh,"isRealHook");s(Wh,"gitConfig");s(Kh,"hasExecutableHook");s(Bh,"isDir");s(Vh,"displayPath");s(bi,"resolveHookState");s(wi,"describeHookState")});import{posix as uc}from"node:path";function et(e){let t=qh.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=uc.basename(o),c=et(a);if(c===null)continue;let l=uc.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 pc(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 qh,Lt=b(()=>{"use strict";W();qh=/^(\d+)_.+\.sql$/;s(et,"parseMigrationVersion");s(ue,"compareVersions");s(Te,"discoverSupabaseProjects");s(pc,"resolveDefaultBranch")});import{execFileSync as zh}from"node:child_process";import{existsSync as H,readFileSync as we,readdirSync as Kn,statSync as Si}from"node:fs";import{posix as x}from"node:path";function Qh(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&&xi(n,o))){let c=Zh(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=x.dirname(r)}return null}function Zh(e,t){let n=[];for(let r of Yh){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=Si(c),d=Si(l);if(!d.isFile())continue;if(p.size!==d.size){n.push(a);continue}if(p.size>Xh)continue;we(c).equals(we(l))||n.push(a)}catch{continue}}}return n.sort()}function bc(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 c=e.upstream.split("/").slice(1).join("/");c&&c!==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;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}`});let o=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(o){let c=e.ahead??0;t.push({id:"worktree.commit-on-shared-base",status:"open",scope:"worktree",title:"Commit on the shared base tree",detail:`${c} commit(s) sit on the shared '${e.defaultBranch}' checkout and not on ${e.upstream??`origin/${e.defaultBranch}`} \u2014 in a workflow that reaches the base branch only through a pull request, a commit here is one that landed in the wrong place. A branch switch in a tree other sessions share can be undone by one of them between the switch and the commit, and nothing reports it.`,hint:`Move the commit onto its branch, then reset the base tree: git branch -f <branch> HEAD && git reset --hard ${e.upstream??`origin/${e.defaultBranch}`} (check for uncommitted work first). Do the work in its own worktree.`})}if(!o&&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 c=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${c} 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 c=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${c.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 ${Ri}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let c=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${c.map(l=>l.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:c.map(l=>`${l.install} (in ${x.dirname(l.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:c,diverging:l}=e.toolCopyDrift,p=l.slice(0,3).join(", "),d=l.length>3?` (+${l.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:`${c} ships ${p}${d} 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 ${l[0]}\` from this repo root), not via a path into ${c}.`})}if(e.stalePackageBuilds.length>0){let c=e.stalePackageBuilds,l=s(d=>d.impact==="runtime"?`${d.packageDir} (runtime)`:d.packageDir,"label"),p=c.every(d=>d.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".`:c.some(d=>d.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:`${c.map(l).join(", ")}: src/ is newer than the built ${[...new Set(c.map(d=>d.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${p}`,hint:`Rebuild: pnpm --filter ./${c[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 a=eg(e.hooks);return a&&t.push(a),tg(t)}function eg(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:wi(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 tg(e){return[...e].sort((t,n)=>fc[t.status]-fc[n.status]||t.id.localeCompare(n.id))}function wc(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function pe(e){let t=e?.trim();return t||null}function ng(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 rg(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 ig(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 og(e){let t=x.join(e,Ri);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 sg(e){try{return Te(e).map(t=>x.join(x.dirname(t.dir),"config.toml"))}catch{return[]}}function ag(e){let t=S(e,["ls-files","-z","--",...Jh]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=_c[x.basename(r)];if(i===void 0)continue;let o=x.dirname(r);if(!cg(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 cg(e,t){return t==="."?!0:Ei(e,t)}function Ei(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 kc(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=ng(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=rg(e),g=pe(S(e,["rev-parse","--show-toplevel"]))??e,y=ig(S(e,["worktree","list","--porcelain"])??""),_=y[0]?.path??null,w=_!=null&&xi(_,g),v=Math.max(0,y.length-1),k=null;if(_&&!xi(_,g)){let T=s(A=>H(x.join(_,A))&&!H(x.join(g,A)),"here"),D=[...yc,...sg(g),...og(g),...t.probePaths??[]];k={mainWorktreePath:_,currentWorktreePath:g,missing:[...new Set(D.filter(T))],missingDeps:ag(g).filter(A=>T(A.dir))}}let E=Qh(g,e),R=t.includeRelease===!1?null:hg(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:vc(g),release:R,unmergedMigrations:I,hooks:bi(e)}}function xi(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function ug(e){let t=new Set;Ei(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<hc;){let i=n.pop();if(i===void 0)break;if(i.depth>=dg)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>=hc)break;Ei(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function pg(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 fg(e){let t=[];for(let n of ug(e)){let r=n==="."?e:x.join(e,n),i=s(o=>n==="."?o:x.join(n,o),"prefix");for(let o of pg(r)){if(t.length>=vi)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>=vi)break}else o.includes("*")||t.push(i(o))}catch{}}}return t.slice(0,vi)}function gc(e){let t=null,n=0,r=[e];for(;r.length>0&&n<mc;){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=Si(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=mc)break}}}return t}function mg(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 vc(e){let t=[],n=fg(e),r=mg(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(_=>{if(typeof _!="string")return null;let w=_.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=gc(f),g=gc(m);if(h===null||g===null)continue;let y=h-g;y>lg&&t.push({packageDir:i,buildDir:d,srcNewerByMs:Math.round(y),impact:u})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}function hg(e,t){if(!t)return null;let n=gg(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 gg(e,t){try{return zh("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 kc(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=bc(n),i=wc(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var yc,Ri,_c,Jh,Yh,Xh,fc,lg,vi,mc,dg,hc,Ai=b(()=>{"use strict";ki();W();Lt();yc=["supabase/config.toml","supabase/.temp",".env"],Ri=".maind/worktree-requirements",_c={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},Jh=Object.keys(_c).flatMap(e=>[e,"*/"+e]),Yh=["scripts"],Xh=512*1024;s(Qh,"gatherToolCopyDrift");s(Zh,"compareToolDirs");s(bc,"computeDivergence");s(eg,"computeHookFinding");fc={open:0,warn:1,info:2,passed:3};s(tg,"sortFindings");s(wc,"isHealthy");s(pe,"trimOrNull");s(ng,"resolveDefaultBranch");s(rg,"detectInProgressOp");s(ig,"parseWorktrees");s(og,"readWorktreeRequirements");s(sg,"discoverSupabaseConfigProbes");s(ag,"discoverDependencyDirs");s(cg,"isWorkspaceRoot");s(Ei,"hasWorkspaceMarkers");s(kc,"gatherRepoHealthFacts");s(xi,"samePath");lg=2e3,vi=64,mc=4e3,dg=3,hc=400;s(ug,"findWorkspaceRoots");s(pg,"workspacePatternsAt");s(fg,"listWorkspacePackageDirs");s(gc,"newestMtimeUnder");s(mg,"consumedWorkspaceNames");s(vc,"gatherStalePackageBuilds");s(hg,"gatherReleaseFact");s(gg,"runGh");s($t,"checkDivergence")});import{existsSync as Ti,readdirSync as Sc}from"node:fs";import{posix as re}from"node:path";function Ci(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Ii)}function xc(e,t={}){let n=t.minFiles??Ni;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Ec)}function nt(e){return`${e.dir}#${e.prefix}`}function jt(e){let t=yg.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function Rc(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}${Pi(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 Ac(e){return!e.some(t=>t.status==="open")}function Pi(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 Di(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Tc(e,t){let n=Di(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:Pi(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 _g(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 Ic(e,t={}){let n=t.minFiles??Ni,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=>xc(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 Oi(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=Ic(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 _=re.dirname(h),w=jt(re.basename(h));if(!w)return;let v=`${_}#${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 _=S(e,["ls-tree","-r","--name-only",h,"--",...a]);if(_===null){n.push(`could not read ${y}`);return}for(let w of tt(_))l(w,g,y)},"scanTree");for(let h of a){let g=re.join(e,h);if(Ti(g))try{for(let y of Sc(g))l(`${h}/${y}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let d=_g(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||!Ti(y)))for(let _ of a){let w=re.join(y,_);if(Ti(w))try{for(let v of Sc(w))l(`${_}/${v}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${_} 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(Ii):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 Oi(e,t),r=Rc(n);return{ok:Ac(r),findings:r,facts:n}}async function Ce(e,t,n={}){let r=Di(t);if(!jt(re.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Oi(e,{...n,dirs:n.dirs??[re.dirname(r)]});return Tc(i,r)}var Ii,yg,Ni,Ec,Ht=b(()=>{"use strict";W();Ii="could not diff against the base ref \u2014 everything reported as info";s(Ci,"isNumberCollisionsGraded");yg=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Ni=3,Ec=.8;s(xc,"isCounterNamespace");s(nt,"namespaceKey");s(jt,"parseNumbered");s(Rc,"computeNumberCollisions");s(Ac,"isCollisionFree");s(Pi,"suggestNextNumber");s(Di,"normaliseRepoPath");s(Tc,"checkProposedNumber");s(Bn,"trimOrNull");s(tt,"lines");s(_g,"resolveDefaultBranch");s(Ic,"detectNamespaces");s(Oi,"gatherNumberCollisionFacts");s(Ie,"checkNumberCollisions");s(Ce,"checkNumberForPath")});function ji(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 bg(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 Cc(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(bg)}function Ut(e){return ai(JSON.stringify(Cc(e)))}var Mi,Fi,Li,$i,Hi=b(()=>{"use strict";ci();Mi={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"]}},Fi="number.collision",Li="theme.dead_class",$i="acl.missing_revoke";s(ji,"specDriftRuleId");s(rt,"gradeEngineStatus");s(bg,"codePointCompare");s(Cc,"normalizeEvidenceForHash");s(Ut,"hashDetectorEvidence")});import{existsSync as wg,readFileSync as Nc}from"node:fs";import{posix as kg}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 vg(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=>vg(o).trim()).filter(o=>o.length>0)}function Mc(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 Sg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gi(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${Sg(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 Wi(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]=Mc(o))}return t}function Eg(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 Fc(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Lc(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function $c(e,t){let n=Gi(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Lc(),i=[],o=0;for(let a of it(n.slice(1,-1))){if(!a.startsWith("{")){o++;continue}let c=Wi(a),l=c[t.key_field];if(!l){o++;continue}let p=(t.partition_by??[]).map(d=>c[d]??"");i.push({key:l,fields:Fc(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 jc(e,t){let n=Gi(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=Lc(),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=Wi(f);for(let[y,_]of Object.entries(d.fields??{}))m[y]=g[String(_)]??"";if(!u&&typeof d.children=="string"){let y=Eg(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,_]of Object.entries(d.fields??{})){let w=g[Number(_)];m[y]=w!==void 0&&Gt(w[0]??"")?Mc(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(_=>m[_]??"");i.push({key:g,fields:Fc(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 Pc(e,t){return t.extractor==="object-array"?$c(e,t):jc(e,t)}function Hc(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 Uc(e,t,n){return`spec.drift:${e}#${t}:${n}`}function xg(e){return e.orderPath.join(" / ")||"(flat)"}function Gc(e,t,n,r){let i=[],o=s((p,d,u,f,m,h)=>{i.push({id:Uc(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 ${xg(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(Hc(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 Rg(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 Dc(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 Wc(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(Dc(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=Pc(h,m.spec),_=Pc(g,m.impl);if(y.error||_.error){u.push(Dc(m.id,y.error??_.error??"unknown")),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let w=y.dropped>0||_.dropped>0;f.push({id:m.id,measured:!0,specRecords:y.records.length,implRecords:_.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 ${_.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(...Gc(m,y.records,_.records,e.files)),u.push(...Rg(m,{spec:y.records.length,impl:_.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(Uc(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)=>Oc[d.status]-Oc[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 Ui(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 Ag(e){let t=Ui(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=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 Kc(e,t={}){let n=s((h,g)=>kg.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(Ui(S(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...o,manifestError:"not a git work tree"};let a=n(e,r);if(!wg(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(Nc(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 Tg(c))try{p.set(h,Nc(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:Ag(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=Ui(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 Kc(e,t);return{...Wc(n,t),facts:n}}function Ki(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var qn,Oc,Wt=b(()=>{"use strict";W();qn=".maind/spec-contracts.json";s(zn,"endOfString");s(Jn,"skipComment");s(Gt,"isQuote");s(Yn,"isCommentStart");s(Vn,"sliceBalanced");s(vg,"stripLeadingTrivia");s(it,"splitTopLevel");s(Mc,"readStringLiteral");s(Sg,"escapeRe");s(Gi,"findSymbolArray");s(Wi,"parseObjectFields");s(Eg,"objectFieldRaw");s(Fc,"pickFields");s(Lc,"makeOrdinals");s($c,"extractObjectArray");s(jc,"extractNestedList");s(Pc,"extractRecords");s(Hc,"isGrounded");s(Uc,"findingId");s(xg,"partitionOf");s(Gc,"compareContract");s(Rg,"checkAssertions");s(Dc,"unreadable");Oc={open:0,warn:1,info:2,passed:3};s(Wc,"computeSpecDrift");s(Ui,"trimOrNull");s(Xn,"parseManifest");s(Ag,"resolveDefaultBranch");s(Tg,"declaredPaths");s(Kc,"gatherSpecDriftFacts");s(Ne,"checkSpecDrift");s(Ki,"isSpecDriftGraded")});import{readFileSync as Ig}from"node:fs";import{join as Cg,posix as Ng}from"node:path";function Bc(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 Pg(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 Vc(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(Dg.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 Vi(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=Bc(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=Pg(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=Vc(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 _ of u.writePrivs)y.authWritesRevoked.add(_)}continue}}}return t}function Bi(e){let t=[];for(let[n,r]of Vi(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 qc(e){let t=Bi(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Bi(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 zc(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function zi(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(Qn)||t.endsWith(qi))}function Mg(e,t){try{let n=Ig(e,"utf8");return n.length>t?null:n}catch{return null}}function Fg(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=Ng.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} ${qi}`),null;l.push({name:u,version:f,content:m})}return l}function Pe(e,t={}){let n=t.maxFileBytes??Og,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=pc(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 _=Mg(Cg(e,y.path),n);if(_===null){r.push(`could not read ${y.path} \u2014 excluded from the fold`);continue}m.push({ref:y,content:_})}let h=m.map(({ref:y,content:_})=>({name:y.name,version:y.version,content:_})),g=a===null?null:Fg(e,f.dir,m,a,r);c.push(...qc({dir:f.dir,files:h,baseFiles:g})),l.push({dir:f.dir,migrationCount:h.length,tableCount:Vi(h).size})}let p=l.reduce((f,m)=>f+m.migrationCount,0),d=zc(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,Dg,Og,Qn,qi,Zn=b(()=>{"use strict";W();Lt();s(Bc,"stripSql");s(X,"normalizeQualifiedIdent");s(fe,"splitTopLevel");Kt=["INSERT","UPDATE","DELETE"];s(Pg,"parseDefaultAclTables");Dg=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(Vc,"parseTableRevoke");s(Vi,"foldTableAcl");s(Bi,"evaluateTableAcl");s(qc,"computeTableAclFindings");s(zc,"deriveTableAclVerdict");Og=5e6,Qn="\u2014 findings reported ungraded (open)",qi="\u2014 baseline degraded";s(zi,"isTableAclGraded");s(Mg,"safeRead");s(Fg,"baseFilesFor");s(Pe,"checkTableAclLint")});import{readFileSync as Lg}from"node:fs";import{join as Ji}from"node:path";function Xi(e){return e.verdict!=="no_opinion"&&e.graded}function Qi(e){let t=new Set;for(let n of e.matchAll($g))t.add(n[1]);return t}function Zi(e){return new Set([...e].map(t=>t.split("-")[0]))}function el(e){return e.split(`
31
31
  `).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
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(Fg)){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 Lg(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??$g,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:jg(e,i,n,t.baseRef),l=Lg(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 jg(e,t,n,r){let i=r??Ug(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=>Hg(i,o)))}function Hg(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 Ug(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=Og(e,"utf8");return n.length>t?null:n}catch{return null}}var Xc,Mg,Fg,zc,$g,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"],Mg=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,Fg=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(Lg,"gradeAgainstBaseline");s(Zc,"deriveThemeClassVerdict");zc=["*.ts","*.tsx","*.js","*.jsx"],$g=15e5;s(eo,"isScannableSource");s(Jc,"listTracked");s(De,"checkThemeClassDrift");s(jg,"baselineFindings");s(Yc,"listTrackedAt");s(Hg,"matchesSourcePattern");s(Ug,"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 Wg(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 Kg(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 Bg(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 Vg(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 qg(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 zg(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:Wg(e.number),det_spec_drift:Kg(e.spec),det_theme_class_drift:Bg(e.theme),det_table_acl_lint:Vg(e.acl)},n=el.map(l=>t[l].summary),r=el.flatMap(l=>t[l].findings),i=qg(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:zg(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={...Gg,...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,Gg,el,nr,tl,io=_(()=>{"use strict";W();ji();Ht();Wt();Zn();er();rl=64,Gg={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(Wg,"adaptNumber");s(Kg,"adaptSpec");s(Bg,"adaptTheme");s(Vg,"adaptAcl");nr={open:0,warn:1,info:2},tl={introduced:0,pre_existing:1};s(no,"compareWire");s(nl,"capPriority");s(qg,"buildWire");s(zg,"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=Jg(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function Jg(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(Jg,"contentForPath")});var st,ll,at,ct,so,rr,ir,or,ao,dl,qt=_(()=>{"use strict";st="1",ll=`
32
+ `)}function eo(e){let t=Zi(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let o=el(i),a=new Set;for(let c of o.matchAll(jg)){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 Jc(e){return`${e.file} ${e.klass}`}function Hg(e,t){let n=t===null?null:new Set(t.map(Jc));return e.map(r=>({...r,status:n!==null&&n.has(Jc(r))?"info":"open"}))}function tl(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function to(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Xc(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??Ug,r=new Set;for(let d of Xc(e,["*.css"])){let u=Yi(Ji(e,d),n);if(u!==null)for(let f of Qi(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=>Yc.map(u=>`${d.replace(/\/+$/,"")}/**/${u}`)):Yc,o=[];for(let d of Xc(e,i)){if(!to(d))continue;let u=Yi(Ji(e,d),n);u!==null&&o.push({path:d,content:u})}let a=eo({tokens:r,sources:o}),c=t.includeBaseline===!1?null:Gg(e,i,n,t.baseRef),l=Hg(a,c?.findings??null),p=tl(r.size,l.length);return{ok:p!=="no_opinion"&&!l.some(d=>d.status==="open"),verdict:p,tokenCount:r.size,namespaceCount:Zi(r).size,findings:l,scannedFiles:o.length,graded:c!==null,baseRef:c?.mergeBase??null}}function Gg(e,t,n,r){let i=r??Kg(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}`]):Yi(Ji(e,u),n),"atBase"),p=new Set;for(let u of Qc(e,o,["*.css"])){let f=l(u);if(f!==null)for(let m of Qi(f))p.add(m)}if(p.size===0)return{findings:[],mergeBase:o};let d=[];for(let u of Qc(e,o,t)){if(!to(u))continue;let f=l(u);f===null||f.length>n||d.push({path:u,content:f})}return{findings:eo({tokens:p,sources:d}),mergeBase:o}}function Qc(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=>Wg(i,o)))}function Wg(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 Kg(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 Yi(e,t){try{let n=Lg(e,"utf8");return n.length>t?null:n}catch{return null}}var Zc,$g,jg,Yc,Ug,er=b(()=>{"use strict";W();s(Xi,"isThemeClassDriftGraded");Zc=["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"],$g=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,jg=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Zc.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(Qi,"extractTokens");s(Zi,"deriveNamespaces");s(el,"stripCommentLines");s(eo,"evaluateThemeClasses");s(Jc,"findingKey");s(Hg,"gradeAgainstBaseline");s(tl,"deriveThemeClassVerdict");Yc=["*.ts","*.tsx","*.js","*.jsx"],Ug=15e5;s(to,"isScannableSource");s(Xc,"listTracked");s(De,"checkThemeClassDrift");s(Gg,"baselineFindings");s(Qc,"listTrackedAt");s(Wg,"matchesSourcePattern");s(Kg,"resolveBaseRef");s(Yi,"safeRead")});function no(e){return Mi[e].version}function Vt(e,t,n,r){return{detector_id:e,detector_version:no(e),state:t,finding_count:n,...r?{reason:r}:{}}}function K(e,t,n){return{summary:Vt(e,t,0,n),findings:[]}}function sl(e){return e==="open"||e==="warn"||e==="info"}function Vg(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(!Ci(n))return K(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let o of r){if(!sl(o.status))continue;let{level:a,baseline:c}=rt(o.status);i.push({detector_id:t,rule_id:Fi,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 qg(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(!Ki(n))return K(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!sl(i.status))continue;let{level:o,baseline:a}=rt(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:ji(i.dimension),level:o,baseline:a,evidence:[i.id],title:i.title})}return{summary:Vt(t,"ran",r.length),findings:r}}function zg(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(!Xi(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:Li,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 Jg(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(!zi(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:$i,level:o,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:Vt(t,"ran",r.length),findings:r}}function ro(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||nr[e.level]-nr[t.level]||rl[e.baseline]-rl[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function il(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function Yg(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:no(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:no(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(ro)}function Xg(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:Vg(e.number),det_spec_drift:qg(e.spec),det_theme_class_drift:zg(e.theme),det_table_acl_lint:Jg(e.acl)},n=nl.map(l=>t[l].summary),r=nl.flatMap(l=>t[l].findings),i=Yg(r),o=[...i].sort((l,p)=>il(l)-il(p)||ro(l,p)).slice(0,ol).sort(ro),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:Xg(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 al(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:al(t)}}}async function io(e,t={}){let n={...Bg,...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: ${al(r)}`))}}var ol,Bg,nl,nr,rl,oo=b(()=>{"use strict";W();Hi();Ht();Wt();Zn();er();ol=64,Bg={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")},nl=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint"];s(no,"versionOf");s(Vt,"summary");s(K,"noFindings");s(sl,"isFindingStatus");s(Vg,"adaptNumber");s(qg,"adaptSpec");s(zg,"adaptTheme");s(Jg,"adaptAcl");nr={open:0,warn:1,info:2},rl={introduced:0,pre_existing:1};s(ro,"compareWire");s(il,"capPriority");s(Yg,"buildWire");s(Xg,"deriveCoverage");s(ot,"adaptDetectorReports");s(Bt,"unavailableDetectorReports");s(al,"errorText");s(tr,"attempt");s(io,"runRepoHealthDetectors")});var cl,so=b(()=>{"use strict";cl=[{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 ll(e){let t=new Set;for(let[n,r]of e.paths)for(let i of cl){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let o=Qg(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function Qg(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
36
+ `):t.readUntracked(e)}var dl=b(()=>{"use strict";so();s(ll,"scanRiskFlags");s(Qg,"contentForPath")});var st,ul,at,ct,ao,rr,ir,or,co,pl,qt=b(()=>{"use strict";st="1",ul=`
37
37
  CREATE TABLE IF NOT EXISTS meta (
38
38
  key TEXT PRIMARY KEY,
39
39
  value TEXT NOT NULL
@@ -92,7 +92,7 @@ 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",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 Yg(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(Yg(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(Yg,"classifyReviewSymbol")});import{createRequire as Xg}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 Qg(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 Zg(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 ey(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function sr(e){let t=ey(),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 yl,Jt,po=_(()=>{"use strict";yl=Xg(import.meta.url);s(bl,"loadBuiltin");Jt=null;s(lt,"probeBuiltinSqlite");s(Qg,"openBuiltin");s(Zg,"openBetter");s(ey,"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
95
+ `,at="schema_version",ct="last_index_commit",ao="last_indexed_at",rr="embed_recipe_version",ir="embed_model",or="embed_dim",co="last_synced_at",pl="last_synced_commit"});function lo(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 fl(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of lo(e.name))t.add(i);for(let i of lo(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function ml(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 lo(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var uo=b(()=>{"use strict";s(lo,"splitIdentifier");s(fl,"buildSearchText");s(ml,"toFtsMatchQuery")});import{readFileSync as hl}from"node:fs";import{posix as gl}from"node:path";function yl(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 _l(e){return e==="added"?0:e==="modified"?1:2}function Zg(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,po=b(()=>{"use strict";Ha();fi();Ga();Ba();W();ic();yi();Ai();Ht();oo();Wt();dl();qt();uo();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=Xa(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=ec(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 _=this.readRepoFile(h.path);if(_===null){d.filesSkipped++;continue}let w=Un(_);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,_,h.language),k=new Map;for(let R of v.nodes)k.set(R.nodeKey,fl(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=Wa(h);for(let y of u){let _=Ka(y,g);await this.store.replaceOutgoingEdges(_.srcKeys,_.edges)}}if(this.embedder&&t.embed){let h=await this.store.getNodesByKinds([...pi]),g=await this.store.getEmbeddingContentHashes(),y=[];for(let w of h){let v=ja(w),k=Un(`${this.embedder.recipeVersion}\0${v}`);g.get(w.nodeKey)!==k&&y.push({nodeKey:w.nodeKey,text:v,hash:k})}let _=64;for(let w=0;w<y.length;w+=_){let v=y.slice(w,w+_),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+_,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(ao,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(ao);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({...yl(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:Ua(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({...yl(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 _=r==="out"?g.dstKey:g.srcKey;p.has(_)||(p.add(_),f.push(_))}}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=hl(gl.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=Za(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 lc(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 io(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=rc(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=ll({paths:n,hunks:i,readUntracked:s(f=>this.readRepoFileHead(f,nc),"readUntracked")}),c=Ya(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 _=n.get(f.path)??"modified",w=i.get(f.path);for(let v of m)p.push(Zg(v,_,w,y))}return p.sort((f,m)=>_l(f.change)-_l(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:tc(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 hl(gl.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(yl,"toHit");s(Oe,"clampLimit");s(_l,"changeRank");s(Zg,"classifyReviewSymbol")});import{createRequire as ey}from"node:module";function wl(){return bl("node:sqlite")}function lt(){if(Jt)return Jt;try{let{DatabaseSync:e}=wl(),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 ty(e){let{DatabaseSync:t}=wl(),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 ny(e){let t=bl("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 ry(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function sr(e){let t=ry(),n=s(i=>{let o=i==="node:sqlite"?ty(e):ny(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 bl,Jt,fo=b(()=>{"use strict";bl=ey(import.meta.url);s(wl,"loadBuiltin");Jt=null;s(lt,"probeBuiltinSqlite");s(ty,"openBuiltin");s(ny,"openBetter");s(ry,"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 kl,Yt,vl=b(()=>{"use strict";fo();qt();uo();s(ar,"toNodeRow");kl=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(ul)}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=ml(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
@@ -105,7 +105,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
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+=_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(
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+=kl)for(let a of n.slice(o,o+kl))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 ty}from"node:crypto";function dt(e){return ty("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 ry(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var ut,pt,ny,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:ry(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,ny),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}},ny=250;s(fo,"chunkArray");s(xl,"numOrNull");s(ry,"numOr0")});var Rl={};q(Rl,{CodeIndexSync:()=>pt,DEFAULT_DB_RELPATH:()=>go,SyncError:()=>ut,createCodeIndexSync:()=>oy,createNodeCodeIndex:()=>yo,openSqliteDatabase:()=>sr,probeBuiltinSqlite:()=>lt});import{mkdirSync as iy}from"node:fs";import{posix as ho}from"node:path";function yo(e){let t=e.dbPath??ho.join(e.repoRoot,go);iy(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 oy(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(oy,"createCodeIndexSync")});import{execFileSync as Al}from"node:child_process";import{existsSync as Tl,realpathSync as Il}from"node:fs";import{createRequire as sy}from"node:module";import{basename as ay,dirname as cy,isAbsolute as Cl,join as ly,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 sy(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=cy(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,ly(a,ay(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 fy,PR,ql=_(()=>{"use strict";W();fy=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],PR=new RegExp(fy.join("|"),"g")});import{existsSync as _o,readdirSync as my,readFileSync as hy}from"node:fs";import{spawnSync as gy}from"node:child_process";import{dirname as yy,join as wo,posix as by}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,_y,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 wy(e){let t=S(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=yy(t);return n===e?null:n}function ky(e,t,n){let r=by.dirname(t),o=[{path:wo(e,r,"config.toml"),source:"worktree"}],a=wy(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(hy(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 vy(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 my(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=ky(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:vy(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,_y,ed=_(()=>{"use strict";W();Lt();ko=54322;s(Jl,"evaluateLedgerProject");s(Yl,"deriveLedgerVerdict");Xl=s((e,t,n)=>{let r=gy("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"),_y="select version from supabase_migrations.schema_migrations order by version";s(Ql,"classifyLedgerError");s(zl,"readLedger");s(Zl,"parseDbPort");s(wy,"mainWorktreeRoot");s(ky,"resolveConfig");s(vy,"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 Ny}from"node:crypto";function Ly(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return Eo.test(t)?t:Ny()}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 $y(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 jy(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(Hy(r))})})}function Hy(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 Uy(){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 Gy(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function Wy(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,Py,Dy,Oy,My,Fy,Eo,mr,Ro=_(()=>{"use strict";Xe();cd=45e3,dd=3e4,Py=5,Dy=120,Oy=3e4,My=15*6e4,Fy=1500,Eo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Ly,"resolveClientSessionId");s(xo,"autoAnnounceDisabled");s($y,"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??Uy,this.gitBranchObject=t.gitBranchObject??jy,this.log=t.log??(i=>process.stderr.write(i+`
122
- `)),this.machineLabel=Gy(r?.machine_label),this.enabled=this.projectKey!==null&&!xo(n,r),this.workingPathsEnabled=$y(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??Wy(n,Ly(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<Py||(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,Fy).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(Oy*2**(this.consecutiveFailures-1),My);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:Dy,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(jy,"defaultGitBranchObject");s(Hy,"normalizeObjectId");s(Uy,"defaultGitBranch");s(Gy,"normalizeMachineLabel");s(Wy,"staticIdentity")});import{mkdirSync as ud,readdirSync as hd,readFileSync as Ky,renameSync as pd,statSync as By,unlinkSync as gd,writeFileSync as fd}from"node:fs";import{homedir as Vy}from"node:os";import{join as ft}from"node:path";function yd(){return ft(Vy(),".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-By(i).mtimeMs>qy&&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(Ky(ft(n,i),"utf8")),a=zy(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function zy(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 qy,hr=_(()=>{"use strict";qy=120*6e4;s(yd,"presenceSnapshotBaseDir");s(bd,"projectDir");s(_d,"createSnapshotStore");s(md,"pruneStale");s(mt,"readSnapshots");s(zy,"parseSnapshot")});import{execFileSync as Jy}from"node:child_process";import{createHash as Yy,randomUUID as Xy}from"node:crypto";import{existsSync as Qy,mkdirSync as Zy,readdirSync as eb,readFileSync as kd,renameSync as tb,statSync as Ao,unlinkSync as vd,writeFileSync as nb}from"node:fs";import{homedir as rb}from"node:os";import{basename as ib,join as ke}from"node:path";function ht(e){return ke(e??ke(rb(),".maind","presence"),"identity")}function Sd(e,t){if(e){let n=ib(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();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(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}:{}};nb(r,JSON.stringify(c,null,2)+`
123
- `,{mode:384}),tb(r,n),lb(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 lb(e,t){try{for(let n of eb(e))if(n.endsWith(".json"))try{let r=Ao(ke(e,n));t-r.mtimeMs>sb&&vd(ke(e,n))}catch{}}catch{}}function db(e){return Ad(e)?.file??null}function Ad(e){let t=ke(e.dir,`${e.agentPid}.json`);try{if(!Qy(t))return null;let n=Ao(t);if(n.mtimeMs<e.bridgeStartMs-ab)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||!ub(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function wd(e){return e.replace(/\/+$/,"")}function ub(e,t){let n=wd(e),r=wd(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function pb(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=Yy("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 fb(e){if(process.platform==="win32")return null;try{let t=Jy("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function mb(){try{return U()}catch{return null}}var Zt,ob,sb,ab,cb,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,ob=8,sb=48*60*6e4,ab=6e4,cb="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(ht,"identityDirPath");s(Sd,"transcriptStemOf");s(Ed,"writeAgentIdentityFile");s(xd,"identityFileStale");s(Rd,"deleteAgentIdentityFile");s(lb,"pruneIdentityDir");s(db,"readAgentIdentityFile");s(Ad,"readAgentIdentityEntry");s(wd,"normDir");s(ub,"sameSessionTree");s(pb,"uuidV5");s(fb,"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??mb)(),o=(t.ppidStart??fb)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=pb(`${i}|${this.agentPid}|${o}|${t.projectKey}`,cb),this.source="derived";return}this.id=Xy(),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>ob&&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 db({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(mb,"defaultDeviceId")});function To(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Io=_(()=>{"use strict";s(To,"newModeState")});import{createReadStream as hb,existsSync as gb}from"node:fs";import{stat as yb}from"node:fs/promises";import{createInterface as bb}from"node:readline";async function Co(e){if(!e||!gb(e))return null;let t;try{t=await yb(e)}catch{return null}let n=new Set,r=0,i=0,o=0;return await new Promise(a=>{let c=hb(e,{encoding:"utf-8"}),l=bb({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(wb)){let r=n[1].toLowerCase();_b.has(r)&&(t=r)}return t}var _b,wb,br=_(()=>{"use strict";_b=new Set(["low","medium","high","xhigh","max"]),wb=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(en,"detectEffortLevel")});import{createReadStream as kb,existsSync as vb,readdirSync as Sb}from"node:fs";import{basename as Pd,dirname as Eb,join as Cd}from"node:path";import{createInterface as xb}from"node:readline";function gt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function Tb(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=Ab[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(Eb(e),t,"subagents"),r;try{r=Sb(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>Cd(n,i))}async function Nd(e,t,n,r,i){vb(e)&&await new Promise(o=>{let a=kb(e,{encoding:"utf-8"}),c=xb({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=Tb(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===Rb,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,Rb,Ab,wr=_(()=>{"use strict";Fe="main",Rb="<synthetic>",Ab={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(gt,"num");s(Tb,"editedPathsOf");s(_r,"subagentFilesOf");s(Nd,"readStream");s(No,"fillTimestamps");s(tn,"collectTurns")});import{createReadStream as Dd,existsSync as Ib}from"node:fs";import{createInterface as Od}from"node:readline";function Fb(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 Lb(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
124
- `)}function $b(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 jb(e,t,n){return Cb.test(e)?{polarity:-1,magnitude:yt.rework,kind:"rework"}:n&&Nb.test(e)?{polarity:-1,magnitude:yt.correction,kind:"correction"}:Pb.test(e)?{polarity:1,magnitude:yt.acceptance,kind:"acceptance"}:t!==null&&$b(t,e)?{polarity:-1,magnitude:yt.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function Hb(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}}async function Ub(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=Hb("");if(!e||!Ib(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=Lb(R);if(I.includes(Db)){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(Ob))){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=jb(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",()=>m()),g.on("error",()=>m()),h.on("error",()=>m())}),await Ub(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||Fb(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*Mb+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,Cb,Nb,Pb,Db,Ob,Mb,yt,Fd=_(()=>{"use strict";br();wr();vr="mcp__maind__",Md="2026-09-09",Cb=/(\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,Nb=/(\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,Pb=/(\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,Db="[Request interrupted by user",Ob="The user doesn't want to proceed with this tool use",Mb=.7,yt={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(Fb,"bumpModel");s(kr,"asBlocks");s(Lb,"textOf");s($b,"isRepeat");s(jb,"classifyGenuine");s(Hb,"emptyAnalysis");s(Ub,"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 Gb}from"node:os";import{join as Wb}from"node:path";var Kb,$d=_(()=>{"use strict";Kb=Wb(Gb(),".codex","sessions")});import{isAbsolute as $o,relative as Bb,resolve as jd,sep as jo}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 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 Ud(e,t){if(!$o(e))return null;let n=Bb(jd(t),jd(e));return!n||n==="."||n.startsWith("..")||$o(n)?null:jo==="/"?n:n.split(jo).join("/")}function Vb(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 Gd(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 Gd(t))if(Vb(e,n.path_prefix))return n.object_id;return null}function qb(e,t){for(let n of Gd(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 Wd(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=qb(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=Ud(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=Wd(k,w.rels,b,t),I=k.input_tokens+k.cache_read_tokens+k.cache_creation_tokens>Hd?"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 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(zb(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 zb(e){let t=e.split(jo).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var Hd,Fo,Kd=_(()=>{"use strict";wr();Hd=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(Ud,"toRepoRelative");s(Vb,"underPrefix");s(Uo,"prefixesOverlap");s(Gd,"sortedAnchors");s(Go,"anchorFor");s(qb,"bestAnchorOverlapping");s(Lo,"inWindow");s(Wd,"assignTurn");s(Wo,"sliceSession");s(Ko,"dominantCheckoutRoot");s(zb,"dirOf")});import{createReadStream as Jb,existsSync as Yb}from"node:fs";import{createInterface as Xb}from"node:readline";function Bd(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function e_(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
125
- `)}function zd(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 t_(e){let t=e.message?.role;if(t==="assistant")return{holder:Bd(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Bd(e.message?.content),r=e_(n);return r.includes(Qb)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(Zb))?{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=zd("");if(!e||!Yb(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(l=>{let p=Jb(e,{encoding:"utf-8"}),d=Xb({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=t_(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>=Vd*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<qd&&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 Qb,Zb,Vd,qd,Jd=_(()=>{"use strict";Qb="[Request interrupted by user",Zb="The user doesn't want to proceed with this tool use",Vd=60,qd=200;s(Bd,"asBlocks");s(e_,"textOf");s(zd,"emptySpan");s(t_,"classify");s(Bo,"analyzeSpan")});import{createReadStream as n_,existsSync as r_}from"node:fs";import{createInterface as i_}from"node:readline";function s_(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function Er(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function a_(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||!r_(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=n_(e,{encoding:"utf-8",start:t.start??0}),p=i_({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=o_[m.attachment.type];b&&(o[s_(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=a_(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 o_,Yd=_(()=>{"use strict";br();Io();o_={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(s_,"modeFlagKey");s(Er,"num");s(a_,"extractUserText");s(Vo,"streamTranscript")});var Xd=_(()=>{"use strict"});import{homedir as c_}from"node:os";import{join as l_}from"node:path";function zo(e){return e.replace(/[/.]/g,"-")}var d_,qo,Qd=_(()=>{"use strict";d_=c_(),qo=l_(d_,".claude","projects");s(zo,"projectPathFromCwd")});var bt=_(()=>{"use strict";Io();Td();Id();Fd();Ld();wr();$d();Kd();Jd();Yd();br();Xd();Qd()});async function tu(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:__,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 w_(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 w_(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(`
118
+ indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as iy}from"node:crypto";function dt(e){return iy("sha256").update(e,"utf8").digest("hex")}function Sl(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 El(e){return{src_key_hash:dt(e.srcKey),dst_key_hash:dt(e.dstKey),kind:e.kind}}function xl(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 Rl=b(()=>{"use strict";s(dt,"sha256");s(Sl,"toCloudNode");s(El,"toCloudEdge");s(xl,"toCloudEmbedding")});function mo(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Al(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function sy(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var ut,pt,oy,ho=b(()=>{"use strict";qt();Rl();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:Al(await this.store.getMeta(co))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Sl),n=(await this.store.getAllEdges()).map(El),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=mo(t,this.chunk),d=mo(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(co,String(Date.now())),i&&await this.store.setMeta(pl,i),{nodes:t.length,edges:n.length,pruned:sy(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=>xl(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=mo(a,oy),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=Al(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}},oy=250;s(mo,"chunkArray");s(Al,"numOrNull");s(sy,"numOr0")});var Tl={};q(Tl,{CodeIndexSync:()=>pt,DEFAULT_DB_RELPATH:()=>yo,SyncError:()=>ut,createCodeIndexSync:()=>cy,createNodeCodeIndex:()=>_o,openSqliteDatabase:()=>sr,probeBuiltinSqlite:()=>lt});import{mkdirSync as ay}from"node:fs";import{posix as go}from"node:path";function _o(e){let t=e.dbPath??go.join(e.repoRoot,yo);ay(go.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 cy(e){let t=e.dbPath??go.join(e.repoRoot,yo),n=e.projectKey??xa(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 yo,bo=b(()=>{"use strict";ci();$a();po();vl();ho();ho();fo();yo=".maind/code-index.sqlite";s(_o,"createNodeCodeIndex");s(cy,"createCodeIndexSync")});import{execFileSync as Il}from"node:child_process";import{existsSync as Cl,realpathSync as Nl}from"node:fs";import{createRequire as ly}from"node:module";import{basename as dy,dirname as uy,isAbsolute as Pl,join as py,relative as Dl,resolve as cr,sep as Ol}from"node:path";function Ml(){let e=lt();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return ly(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 Fl(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=Il("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 $l(e,t=z(),n=process.cwd()){let r=Pl(e)?[e]:[cr(t,e),cr(n,e)];for(let i of r){let o=uy(i);if(!Cl(o))continue;let a;try{a=Nl(o)}catch{continue}let c=jl(a);if(c===null)continue;let l=Dl(c,py(a,dy(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Ol).join("/")}}return null}function lr(e,t=z(),n=process.cwd()){let r=Pl(e)?[e]:[cr(t,e),cr(n,e)];for(let i of r){if(!Cl(i))continue;let o;try{o=Nl(i)}catch{continue}let a=jl(o);if(a===null)continue;let c=Dl(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Ol).join("/")}}return null}function jl(e){try{let t=Il("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 Hl(){return _o({repoRoot:z()})}var Ll,Xt=b(()=>{"use strict";bo();s(Ml,"probeNativeStore");s(Fl,"isNativeStoreUnavailable");Ll="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($l,"resolveRepoRootForPath");s(lr,"resolveRepoRootForDir");s(jl,"gitToplevelOf");s(Hl,"defaultEngineFactory")});var ql=b(()=>{"use strict"});var zl=b(()=>{"use strict";W()});var gy,MR,Jl=b(()=>{"use strict";W();gy=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],MR=new RegExp(gy.join("|"),"g")});import{existsSync as wo,readdirSync as yy,readFileSync as _y}from"node:fs";import{spawnSync as by}from"node:child_process";import{dirname as wy,join as pr,posix as ko}from"node:path";function Xl(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 ${vo} 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 ${vo} 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:(e.projectRoot?`cd ${e.projectRoot} && npx supabase migration up`:"`npx supabase migration up` im Projektverzeichnis")+" (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen. Meldet der Lauf nichts Angewendetes, war es das falsche Verzeichnis ODER die Migration lief bereits \u2014 diese Pruefung sagt, was davon.",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 Ql(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function ed(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 Yl(e,t,n){let r=e(t,ky,n);return r.ok===!1?ed(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
120
+ `).map(i=>i.trim()).filter(Boolean)}}function td(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 vy(e){let t=S(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=wy(t);return n===e?null:n}function Sy(e,t,n){let r=ko.dirname(t),o=[{path:pr(e,r,"config.toml"),source:"worktree"}],a=vy(e);a&&o.push({path:pr(a,r,"config.toml"),source:"main_worktree"});for(let c of o)if(wo(c.path))try{let l=td(_y(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 Ey(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||!wo(a))continue;let c=pr(a,t);if(wo(c))try{for(let l of yy(c)){let p=et(l);p!==null&&!n.has(p)&&n.set(p,a)}}catch{}}return n}function So(e,t={}){let n=t.runPsql??Zl,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=Sy(e,u.dir,i),m=f.source==="missing"?null:Yl(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),h=t.remoteDbUrl!==void 0?Yl(n,t.remoteDbUrl,r):null,g=Xl({dir:u.dir,projectRoot:pr(e,ko.dirname(ko.dirname(u.dir))),fileVersions:u.files.map(y=>y.version),config:f,ledger:m,siblingVersions:Ey(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=Ql(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 vo,Zl,ky,nd=b(()=>{"use strict";W();Lt();vo=54322;s(Xl,"evaluateLedgerProject");s(Ql,"deriveLedgerVerdict");Zl=s((e,t,n)=>{let r=by("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"),ky="select version from supabase_migrations.schema_migrations order by version";s(ed,"classifyLedgerError");s(Yl,"readLedger");s(td,"parseDbPort");s(vy,"mainWorktreeRoot");s(Sy,"resolveConfig");s(Ey,"gatherSiblingVersions");s(So,"checkMigrationLedgerDrift")});var rd,Qt=b(()=>{"use strict";ql();po();yi();so();Ai();zl();Jl();ki();Ht();er();Wt();Lt();Zn();nd();Hi();oo();Ht();Wt();er();Zn();Nn();fi();qt();rd="0.1.0"});import{execFile as ud}from"node:child_process";import{randomUUID as Dy}from"node:crypto";function jy(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return xo.test(t)?t:Dy()}function Ro(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function Hy(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 Uy(e){return await new Promise(t=>{ud("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(Gy(r))})})}function Gy(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 Wy(){return await new Promise(e=>{ud("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 Ky(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function By(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=xo.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(o=>{xo.test(o)&&(n=o.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var dd,pd,Oy,My,Fy,Ly,$y,xo,hr,Ao=b(()=>{"use strict";Xe();dd=45e3,pd=3e4,Oy=5,My=120,Fy=3e4,Ly=15*6e4,$y=1500,xo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(jy,"resolveClientSessionId");s(Ro,"autoAnnounceDisabled");s(Hy,"autoWorkingPathsEnabled");hr=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??Wy,this.gitBranchObject=t.gitBranchObject??Uy,this.log=t.log??(i=>process.stderr.write(i+`
122
+ `)),this.machineLabel=Ky(r?.machine_label),this.enabled=this.projectKey!==null&&!Ro(n,r),this.workingPathsEnabled=Hy(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??By(n,jy(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<dd||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<dd||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<Oy||(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,$y).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(Fy*2**(this.consecutiveFailures-1),Ly);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:My,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(Uy,"defaultGitBranchObject");s(Gy,"normalizeObjectId");s(Wy,"defaultGitBranch");s(Ky,"normalizeMachineLabel");s(By,"staticIdentity")});import{mkdirSync as fd,readdirSync as yd,readFileSync as Vy,renameSync as md,statSync as qy,unlinkSync as _d,writeFileSync as hd}from"node:fs";import{homedir as zy}from"node:os";import{join as ft}from"node:path";function bd(){return ft(zy(),".maind","presence")}function wd(e,t){return ft(e,t)}function kd(e){let t=e.baseDir??bd(),n=wd(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:[]};fd(n,{recursive:!0,mode:448}),c=ft(n,`${p.sessionId}.json`);let f=`${c}.tmp-${r}`;hd(f,JSON.stringify(u),{mode:384}),md(f,c),gd(n,a(),c)}catch{}},endSession(){try{c&&_d(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};fd(n,{recursive:!0,mode:448}),c=ft(n,`${p.sessionId}.json`);let u=`${c}.tmp-${r}`;hd(u,JSON.stringify(d),{mode:384}),md(u,c),gd(n,a(),c)}catch{}}}}function gd(e,t,n){try{for(let r of yd(e)){if(!r.endsWith(".json"))continue;let i=ft(e,r);if(i!==n)try{t-qy(i).mtimeMs>Jy&&_d(i)}catch{}}}catch{}}function mt(e,t=bd()){try{let n=wd(t,e),r=[];for(let i of yd(n))if(i.endsWith(".json"))try{let o=JSON.parse(Vy(ft(n,i),"utf8")),a=Yy(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function Yy(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 Jy,gr=b(()=>{"use strict";Jy=120*6e4;s(bd,"presenceSnapshotBaseDir");s(wd,"projectDir");s(kd,"createSnapshotStore");s(gd,"pruneStale");s(mt,"readSnapshots");s(Yy,"parseSnapshot")});import{execFileSync as Xy}from"node:child_process";import{createHash as Qy,randomUUID as Zy}from"node:crypto";import{existsSync as e_,mkdirSync as t_,readdirSync as n_,readFileSync as Sd,renameSync as r_,statSync as To,unlinkSync as Ed,writeFileSync as i_}from"node:fs";import{homedir as o_}from"node:os";import{basename as s_,join as ke}from"node:path";function ht(e){return ke(e??ke(o_(),".maind","presence"),"identity")}function xd(e,t){if(e){let n=s_(e).replace(/\.jsonl$/i,"");if(Zt.test(n))return n.toLowerCase()}return t&&Zt.test(t)?t.toLowerCase():null}function Rd(e){let t=e.nowMs??Date.now();t_(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(Sd(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}:{}};i_(r,JSON.stringify(c,null,2)+`
123
+ `,{mode:384}),r_(r,n),u_(e.dir,t)}function Ad(e,t,n,r=Date.now()){try{let i=To(ke(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function Td(e,t){try{Ed(ke(e,`${t}.json`))}catch{}}function u_(e,t){try{for(let n of n_(e))if(n.endsWith(".json"))try{let r=To(ke(e,n));t-r.mtimeMs>c_&&Ed(ke(e,n))}catch{}}catch{}}function p_(e){return Id(e)?.file??null}function Id(e){let t=ke(e.dir,`${e.agentPid}.json`);try{if(!e_(t))return null;let n=To(t);if(n.mtimeMs<e.bridgeStartMs-l_)return null;let r=JSON.parse(Sd(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||!f_(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function vd(e){return e.replace(/\/+$/,"")}function f_(e,t){let n=vd(e),r=vd(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function m_(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=Qy("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 h_(e){if(process.platform==="win32")return null;try{let t=Xy("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function g_(){try{return U()}catch{return null}}var Zt,a_,c_,l_,d_,yr,_r=b(()=>{"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,a_=8,c_=48*60*6e4,l_=6e4,d_="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(ht,"identityDirPath");s(xd,"transcriptStemOf");s(Rd,"writeAgentIdentityFile");s(Ad,"identityFileStale");s(Td,"deleteAgentIdentityFile");s(u_,"pruneIdentityDir");s(p_,"readAgentIdentityFile");s(Id,"readAgentIdentityEntry");s(vd,"normDir");s(f_,"sameSessionTree");s(m_,"uuidV5");s(h_,"processStartTime");yr=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??g_)(),o=(t.ppidStart??h_)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=m_(`${i}|${this.agentPid}|${o}|${t.projectKey}`,d_),this.source="derived";return}this.id=Zy(),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>a_&&this.aliases.shift())}activityAtMs(){return Id({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 p_({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(g_,"defaultDeviceId")});function Io(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Co=b(()=>{"use strict";s(Io,"newModeState")});import{createReadStream as y_,existsSync as __}from"node:fs";import{stat as b_}from"node:fs/promises";import{createInterface as w_}from"node:readline";async function No(e){if(!e||!__(e))return null;let t;try{t=await b_(e)}catch{return null}let n=new Set,r=0,i=0,o=0;return await new Promise(a=>{let c=y_(e,{encoding:"utf-8"}),l=w_({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 Cd=b(()=>{"use strict";s(No,"summariseTranscript")});var Nd=b(()=>{"use strict"});function en(e){if(!e)return null;let t=null;for(let n of e.matchAll(v_)){let r=n[1].toLowerCase();k_.has(r)&&(t=r)}return t}var k_,v_,br=b(()=>{"use strict";k_=new Set(["low","medium","high","xhigh","max"]),v_=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(en,"detectEffortLevel")});import{createReadStream as S_,existsSync as E_,readdirSync as x_}from"node:fs";import{basename as Od,dirname as R_,join as Pd}from"node:path";import{createInterface as A_}from"node:readline";function gt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function C_(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=I_[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 wr(e){let t=Od(e).replace(/\.jsonl$/,""),n=Pd(R_(e),t,"subagents"),r;try{r=x_(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>Pd(n,i))}async function Dd(e,t,n,r,i){E_(e)&&await new Promise(o=>{let a=S_(e,{encoding:"utf-8"}),c=A_({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=C_(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 _=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===T_,input_tokens:gt(_.input_tokens),output_tokens:gt(_.output_tokens),cache_read_tokens:gt(_.cache_read_input_tokens),cache_creation_tokens:gt(_.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(gt(_.cache_creation?.ephemeral_1h_input_tokens),gt(_.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 Po(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?wr(e):[];if(!e)return{turns:r,subagent_files:i};let o=[];await Dd(e,Fe,t,n,o),Po(o),r.push(...o);for(let a of i){let c=[],l=Od(a).replace(/\.jsonl$/,"");await Dd(a,l,t,n,c),Po(c);for(let p of c)p.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:i}}var Fe,T_,I_,kr=b(()=>{"use strict";Fe="main",T_="<synthetic>",I_={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(gt,"num");s(C_,"editedPathsOf");s(wr,"subagentFilesOf");s(Dd,"readStream");s(Po,"fillTimestamps");s(tn,"collectTurns")});import{createReadStream as Md,existsSync as N_}from"node:fs";import{createInterface as Fd}from"node:readline";function $_(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 vr(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function j_(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
124
+ `)}function H_(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 U_(e,t,n){return P_.test(e)?{polarity:-1,magnitude:yt.rework,kind:"rework"}:n&&D_.test(e)?{polarity:-1,magnitude:yt.correction,kind:"correction"}:O_.test(e)?{polarity:1,magnitude:yt.acceptance,kind:"acceptance"}:t!==null&&H_(t,e)?{polarity:-1,magnitude:yt.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function G_(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:Ld,behaviour_measured:!0}}async function W_(e,t){for(let n of wr(e))await new Promise(r=>{let i=Fd({input:Md(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 vr(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(Sr))continue;let p=l.name.slice(Sr.length);p&&(t.maind_tool_calls??={},t.maind_tool_calls[p]=(t.maind_tool_calls[p]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function Do(e,t={}){let n=G_("");if(!e||!N_(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=Md(e,{encoding:"utf-8"}),g=Fd({input:h}),y=s(_=>{let w=_.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 vr(v.message?.content)){if(N.type!=="tool_use"||typeof N.name!="string"||!N.name.startsWith(Sr))continue;let Ke=N.name.slice(Sr.length);Ke&&(n.maind_tool_calls??={},n.maind_tool_calls[Ke]=(n.maind_tool_calls[Ke]??0)+1)}if(E)return;if(k==="assistant"){let N=vr(v.message?.content),Ke=!1;for(let xs of N)xs.type==="tool_use"&&(n.tool_calls++,Ke=!0,xs.name==="AskUserQuestion"&&n.agent_questions++);c=Ke;return}if(k!=="user")return;let R=vr(v.message?.content),I=j_(R);if(I.includes(M_)){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(F_))){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=U_(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",_=>{try{y(_)}catch{}}),g.on("close",()=>m()),g.on("error",()=>m()),h.on("error",()=>m())}),await W_(e,n),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||$_(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*L_+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 Sr,Ld,P_,D_,O_,M_,F_,L_,yt,$d=b(()=>{"use strict";br();kr();Sr="mcp__maind__",Ld="2026-09-09",P_=/(\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,D_=/(\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,O_=/(\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,M_="[Request interrupted by user",F_="The user doesn't want to proceed with this tool use",L_=.7,yt={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s($_,"bumpModel");s(vr,"asBlocks");s(j_,"textOf");s(H_,"isRepeat");s(U_,"classifyGenuine");s(G_,"emptyAnalysis");s(W_,"tallySubagentMaindCalls");s(Do,"analyzeSession")});function Oo(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 Mo(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 Fo(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 jd=b(()=>{"use strict";s(Oo,"parseIngestResponse");s(Mo,"describeSliceVerdict");s(Fo,"ingestBody")});import{homedir as K_}from"node:os";import{join as B_}from"node:path";var V_,Lo=b(()=>{"use strict";V_=B_(K_(),".codex","sessions")});var Hd=b(()=>{"use strict";Lo()});import{isAbsolute as Ho,relative as z_,resolve as Ud,sep as Uo}from"node:path";function Gd(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function Er(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Go(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=Er(p.from);typeof p.object_id!="string"||!$o.test(p.object_id)||d===null||c.push({object_id:p.object_id.toLowerCase(),from:d,to:Er(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=Er(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:Er(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"||!$o.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"&&$o.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 Kd(e,t){if(!Ho(e))return null;let n=z_(Ud(t),Ud(e));return!n||n==="."||n.startsWith("..")||Ho(n)?null:Uo==="/"?n:n.split(Uo).join("/")}function J_(e,t){return t===""||e===t||e.startsWith(t+"/")}function Wo(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Bd(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function Ko(e,t){for(let n of Bd(t))if(J_(e,n.path_prefix))return n.object_id;return null}function Y_(e,t){for(let n of Bd(t))if(Wo(e,n.path_prefix))return n.object_id;return null}function jo(e,t){return e>=t.from&&(t.to===null||e<t.to)}function Vd(e,t,n,r){let i=e.ts,o=r?.anchors??[],a=t.map(c=>Ko(c,o)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(d=>jo(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=>jo(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=>jo(i,d));if(p.length){let d=t[0]??n?.rel??null,u=(d===null?p:p.filter(f=>Wo(f.path_prefix,d))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of u){let m=Y_(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 Bo(e,t,n){let r=t?.anchors??[],i=s(h=>{if(!n.repoRoot)return[];let g=[];for(let y of h.edited_paths){let _=Kd(y,n.repoRoot);_!==null&&!g.includes(_)&&g.push(_)}return g},"relOf"),o=s(h=>{for(let g of h){let y=Ko(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),_=null;for(let w of y){let v=o(w.rels);if(v){_=v;break}}!_&&h!==Fe&&y.length&&(_=p(y[0].t.ts));for(let w of y){let v=o(w.rels);v&&(_=v),h===Fe&&l.push({ts:w.t.ts,seg:_});let k=w.t;if(k.input_tokens+k.output_tokens+k.cache_read_tokens+k.cache_creation_tokens===0)continue;let R=Vd(k,w.rels,_,t),I=k.input_tokens+k.cache_read_tokens+k.cache_creation_tokens>Wd?"above_200k":"standard",T=Gd(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,..._}=h;_.first_ts=new Date(g>0?g:u).toISOString(),_.last_ts=new Date(y>0?y:u).toISOString(),f.push(_)}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 Vo(e,t){let n=new Map;for(let o of e){let a=new Set;for(let c of o.edited_paths){if(!Ho(c))continue;let l=t(X_(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 X_(e){let t=e.split(Uo).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var Wd,$o,qd=b(()=>{"use strict";kr();s(Gd,"normalizeModelId");Wd=2e5,$o=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Er,"msOf");s(Go,"parseCostContext");s(Kd,"toRepoRelative");s(J_,"underPrefix");s(Wo,"prefixesOverlap");s(Bd,"sortedAnchors");s(Ko,"anchorFor");s(Y_,"bestAnchorOverlapping");s(jo,"inWindow");s(Vd,"assignTurn");s(Bo,"sliceSession");s(Vo,"dominantCheckoutRoot");s(X_,"dirOf")});import{createReadStream as Q_,existsSync as Z_}from"node:fs";import{createInterface as eb}from"node:readline";function zd(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function rb(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
125
+ `)}function Xd(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 ib(e){let t=e.message?.role;if(t==="assistant")return{holder:zd(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=zd(e.message?.content),r=rb(n);return r.includes(tb)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(nb))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function qo(e){let t=Xd("");if(!e||!Z_(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(l=>{let p=Q_(e,{encoding:"utf-8"}),d=eb({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 _=h.sessionId??h.session_id;typeof _=="string"&&_&&(t.session_id=_)}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=ib(h);if(y!==null){if(t.event_count++,y.genuine&&t.turn_count++,n===null&&(n=g),r=g,o!==null){let _=g-o;a==="agent"?i+=_:_>=Jd*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(_/1e3),c.length<Yd&&c.push({offset_seconds:Math.round((o-n)/1e3),duration_seconds:Math.round(_/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 tb,nb,Jd,Yd,Qd=b(()=>{"use strict";tb="[Request interrupted by user",nb="The user doesn't want to proceed with this tool use",Jd=60,Yd=200;s(zd,"asBlocks");s(rb,"textOf");s(Xd,"emptySpan");s(ib,"classify");s(qo,"analyzeSpan")});import{createReadStream as ob,existsSync as sb}from"node:fs";import{createInterface as ab}from"node:readline";function lb(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function xr(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function db(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 zo(e,t={}){if(!e||!sb(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Io(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,o=t.initialModes?{...t.initialModes}:Io(),a=t.start??0;return await new Promise(c=>{let l=ob(e,{encoding:"utf-8",start:t.start??0}),p=ab({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 _=cb[m.attachment.type];_&&(o[lb(_.mode)]=_.active,n.push({kind:"mode",session_id:h,ts:g,mode:_.mode,active:_.active}));return}if(y==="user"){let _=db(m.message?.content),w=en(_);w&&(i=w);let v={session_id:h,ts:g,text:_,effort_directive:w};n.push({kind:"user",...v});return}if(y==="assistant"){let _=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:xr(_?.input_tokens),output_tokens:E?0:xr(_?.output_tokens),cache_read_input_tokens:E?0:xr(_?.cache_read_input_tokens),cache_creation_input_tokens:E?0:xr(_?.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 cb,Zd=b(()=>{"use strict";br();Co();cb={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(lb,"modeFlagKey");s(xr,"num");s(db,"extractUserText");s(zo,"streamTranscript")});var eu=b(()=>{"use strict"});import{homedir as ub}from"node:os";import{join as pb}from"node:path";function Yo(e){return e.replace(/[/.]/g,"-")}var fb,Jo,tu=b(()=>{"use strict";fb=ub(),Jo=pb(fb,".claude","projects");s(Yo,"projectPathFromCwd")});var _t=b(()=>{"use strict";Co();Cd();Nd();$d();jd();kr();Lo();Hd();qd();Qd();Zd();br();eu();tu()});async function iu(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??Xo,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:vb,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 Sb(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 Sb(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
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,__,nn=_(()=>{"use strict";Jo="https://mcp.maind.dev/mcp",__="2025-06-18";s(tu,"fetchSessionBriefing");s(Le,"fetchToolText");s(w_,"readSseMessage")});function k_(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":U()}}async function nu(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:k_(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(k_,"ingestHeaders");s(nu,"postMetrics")});function ru(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function ou(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 su(e,t,n){let r=n.maxAgeMs??iu,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,a=ou(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)ru(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(ru(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):
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 Xo,vb,nn=b(()=>{"use strict";Xo="https://mcp.maind.dev/mcp",vb="2025-06-18";s(iu,"fetchSessionBriefing");s(Le,"fetchToolText");s(Sb,"readSseMessage")});function Eb(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":U()}}async function ou(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:Eb(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 Ar,Qo=b(()=>{"use strict";B();Ar=process.env.MAIND_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";s(Eb,"ingestHeaders");s(ou,"postMetrics")});function su(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function cu(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 bt(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 lu(e,t,n){let r=n.maxAgeMs??au,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,a=cu(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)su(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(su(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 au(e,t,n,r=iu,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=ou(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 iu,Xo=_(()=>{"use strict";s(ru,"prefixConflict");iu=10*6e4;s(ou,"parsePeers");s(_t,"selectOwnSnapshot");s(rn,"ageDisplay");s(su,"adviseOnPath");s(au,"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 cu(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}var kt=_(()=>{"use strict";s(wt,"denyPayload");s(ve,"advisoryPayload");s(cu,"postAdvisoryPayload")});import{realpathSync as v_}from"node:fs";import{basename as lu,dirname as du,join as S_}from"node:path";function $e(e){let t=du(e),n=[lu(e)];for(;;)try{let r=v_(t);return S_(r,...n.reverse())}catch{let r=du(t);if(r===t)return e;n.push(lu(t)),t=r}}var Ar=_(()=>{"use strict";s($e,"realpathOfUnwritten")});import{mkdir as E_,readFile as x_,writeFile as R_,rename as A_}from"node:fs/promises";import{existsSync as pu}from"node:fs";import{homedir as T_}from"node:os";import{join as fu}from"node:path";function uu(){return{config:null,sessions:{},pending_metrics:[]}}async function $(){if(!pu(Tr))return uu();try{let e=await x_(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
- `),uu()}}async function se(e){pu(je)||await E_(je,{recursive:!0,mode:448});let t=`${Tr}.tmp`;await R_(t,JSON.stringify(e,null,2),{mode:384}),await A_(t,Tr)}function Qo(e){return e.thresholds??e.config?.thresholds??I_}var je,Tr,I_,He=_(()=>{"use strict";je=fu(T_(),".maind"),Tr=fu(je,"state.json"),I_={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(uu,"emptyState");s($,"loadState");s(se,"saveState");s(Qo,"resolveThresholds")});import{existsSync as C_,realpathSync as N_,statSync as P_}from"node:fs";import{dirname as mu,isAbsolute as D_,join as O_}from"node:path";function L_(e,t){let n=e.filter(i=>hu.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 du(e,t,n,r=au,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=cu(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 au,Zo=b(()=>{"use strict";s(su,"prefixConflict");au=10*6e4;s(cu,"parsePeers");s(bt,"selectOwnSnapshot");s(rn,"ageDisplay");s(lu,"adviseOnPath");s(du,"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=b(()=>{"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 uu(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}var kt=b(()=>{"use strict";s(wt,"denyPayload");s(ve,"advisoryPayload");s(uu,"postAdvisoryPayload")});import{realpathSync as xb}from"node:fs";import{basename as pu,dirname as fu,join as Rb}from"node:path";function $e(e){let t=fu(e),n=[pu(e)];for(;;)try{let r=xb(t);return Rb(r,...n.reverse())}catch{let r=fu(t);if(r===t)return e;n.push(pu(t)),t=r}}var Tr=b(()=>{"use strict";s($e,"realpathOfUnwritten")});import{mkdir as Ab,readFile as Tb,writeFile as Ib,rename as Cb}from"node:fs/promises";import{existsSync as hu}from"node:fs";import{homedir as Nb}from"node:os";import{join as gu}from"node:path";function mu(){return{config:null,sessions:{},pending_metrics:[]}}async function j(){if(!hu(Ir))return mu();try{let e=await Tb(Ir,"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
+ `),mu()}}async function se(e){hu(je)||await Ab(je,{recursive:!0,mode:448});let t=`${Ir}.tmp`;await Ib(t,JSON.stringify(e,null,2),{mode:384}),await Cb(t,Ir)}function es(e){return e.thresholds??e.config?.thresholds??Pb}var je,Ir,Pb,He=b(()=>{"use strict";je=gu(Nb(),".maind"),Ir=gu(je,"state.json"),Pb={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(mu,"emptyState");s(j,"loadState");s(se,"saveState");s(es,"resolveThresholds")});import{existsSync as Db,realpathSync as Ob,statSync as Mb}from"node:fs";import{dirname as yu,isAbsolute as Fb,join as Lb}from"node:path";function Hb(e,t){let n=e.filter(i=>_u.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 @@ ${m}`:m}var iu,Xo=_(()=>{"use strict";s(ru,"prefixConflict");iu=10*6e4;s(ou,"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 $_(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function j_(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=mu(e);for(;;){try{if(P_(t).isDirectory())return t}catch{}let n=mu(t);if(n===t)return t;t=n}}async function H_(e,t,n){let r=await n.load();if($_(r,e,t))return null;j_(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=>hu.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:M_,metric_value:1},{session_id:e,metric_key:F_,metric_value:o}),await n.save(a),L_(i,t)}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:"";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=D_(r)?r:O_(i,r),a=C_(o)?N_(o):$e(o),c=ae(Zo(a)),l=await H_(n,c,{load:$,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 hu,M_,F_,es=_(()=>{"use strict";Qt();qe();kt();oe();Ar();He();hu=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],M_="repo_health_hook_runs",F_="repo_health_hook_findings";s(L_,"formatRepoHealth");s($_,"alreadySeen");s(j_,"markSeen");s(Zo,"nearestExistingDir");s(H_,"repoHealthForEdit");s(gu,"runOnRepoHealth")});import{existsSync as U_,readFileSync as G_,realpathSync as W_}from"node:fs";import{isAbsolute as bu,join as _u,posix as K_,relative as B_,sep as V_}from"node:path";function yu(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function X_(e,t){return{contracts:t.filter(r=>yu(r.spec)===e||yu(r.impl)===e).map(r=>r.id),theme:J_.test(e),acl:Y_.test(e)}}function Q_(e){return e.contracts.length===0&&!e.theme&&!e.acl}function Z_(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 ew(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 Ub(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function Gb(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 ts(e){let t=yu(e);for(;;){try{if(Mb(t).isDirectory())return t}catch{}let n=yu(t);if(n===t)return t;t=n}}async function Wb(e,t,n){let r=await n.load();if(Ub(r,e,t))return null;Gb(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=>_u.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:$b,metric_value:1},{session_id:e,metric_key:jb,metric_value:o}),await n.save(a),Hb(i,t)}async function bu(){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=Fb(r)?r:Lb(i,r),a=Db(o)?Ob(o):$e(o),c=ae(ts(a)),l=await Wb(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 _u,$b,jb,ns=b(()=>{"use strict";Qt();qe();kt();oe();Tr();He();_u=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],$b="repo_health_hook_runs",jb="repo_health_hook_findings";s(Hb,"formatRepoHealth");s(Ub,"alreadySeen");s(Gb,"markSeen");s(ts,"nearestExistingDir");s(Wb,"repoHealthForEdit");s(bu,"runOnRepoHealth")});import{existsSync as Kb,readFileSync as Bb,realpathSync as Vb}from"node:fs";import{isAbsolute as ku,join as vu,posix as qb,relative as zb,sep as Jb}from"node:path";function wu(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function ew(e,t){return{contracts:t.filter(r=>wu(r.spec)===e||wu(r.impl)===e).map(r=>r.id),theme:Qb.test(e),acl:Zb.test(e)}}function tw(e){return e.contracts.length===0&&!e.theme&&!e.acl}function nw(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 rw(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 tw(e,t){let n=B_(e,t);return!n||n.startsWith("..")||bu(n)?null:n.split(V_).join(K_.sep)}function nw(e){try{let t=G_(_u(e,qn),"utf8"),{manifest:n}=Xn(t);return n?.contracts??[]}catch{return[]}}async function wu(){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=bu(r)?r:_u(i,r),a=U_(o)?W_(o):$e(o),c=ae(Zo(a)),l=tw(c,a);if(l===null)return 0;let p=X_(l,nw(c));if(Q_(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 $(),f=Z_(u,n,c,d);u.pending_metrics.push({session_id:n,metric_key:q_,metric_value:1},{session_id:n,metric_key:z_,metric_value:f.length}),await se(u);let m=ew(f,l);return m!==null&&process.stdout.write(cu(m)),0}catch{return 0}}var q_,z_,J_,Y_,ku=_(()=>{"use strict";Qt();qe();kt();oe();es();Ar();He();q_="write_health_hook_runs",z_="write_health_hook_findings",J_=/\.(tsx?|jsx?|css)$/,Y_=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(yu,"declPath");s(X_,"routesForPath");s(Q_,"routesAreEmpty");s(Z_,"takeUnreported");s(ew,"formatWriteHealth");s(tw,"repoRelative");s(nw,"readContracts");s(wu,"runOnWriteHealth")});var Du={};q(Du,{agentHostPidCandidates:()=>me,closeTrackedSession:()=>Tu,effectiveConfig:()=>Ue,grandparentPid:()=>Cu,recordGuardSignals:()=>Au,runFlush:()=>bw,runHookStatus:()=>_w,runOnFileEdit:()=>hw,runOnFileWrite:()=>mw,runOnRepoHealth:()=>gu,runOnSessionStart:()=>lw,runOnToolUse:()=>pw,runOnWriteHealth:()=>wu,runSessionEndMetrics:()=>ns,runSyncConfig:()=>kw,writeIdentitySideChannel:()=>ts});import{execFileSync as Su}from"node:child_process";import{existsSync as Nr,readFileSync as Eu,realpathSync as rw}from"node:fs";import{writeFile as iw}from"node:fs/promises";import{homedir as xu}from"node:os";import{isAbsolute as Cr,join as sn,relative as Ru}from"node:path";function Au(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 Tu(e,t,n=Date.now()){cw(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 cw(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 Iu(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 lw(){let e=await $();if(Ue(e)===null)return 0;let t=await C(),n=Pu(t);if(n===null)return 0;Iu(e,n),await se(e);try{ts(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=au(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(dw());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 dw(){try{let e=sn(xu(),".claude","settings.json");return Nr(e)?Eu(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 Cu(){try{if(process.platform==="win32")return null;let e=Su("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=Cu();return n!==null&&n>1&&n!==t&&e.push(n),e}async function pw(){let e=await $();if(Ue(e)===null)return 0;let t=await C(),n=Pu(t)??"unknown",r=Iu(e,n);r.tool_call_count+=1;try{let a=me().filter(c=>xd(ht(),c,uw));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),Au(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 yw(e,r))}return await se(e),0}function fw(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 iw(e,t){let n=zb(e,t);return!n||n.startsWith("..")||ku(n)?null:n.split(Jb).join(qb.sep)}function ow(e){try{let t=Bb(vu(e,qn),"utf8"),{manifest:n}=Xn(t);return n?.contracts??[]}catch{return[]}}async function Su(){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=ku(r)?r:vu(i,r),a=Kb(o)?Vb(o):$e(o),c=ae(ts(a)),l=iw(c,a);if(l===null)return 0;let p=ew(l,ow(c));if(tw(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=nw(u,n,c,d);u.pending_metrics.push({session_id:n,metric_key:Yb,metric_value:1},{session_id:n,metric_key:Xb,metric_value:f.length}),await se(u);let m=rw(f,l);return m!==null&&process.stdout.write(uu(m)),0}catch{return 0}}var Yb,Xb,Qb,Zb,Eu=b(()=>{"use strict";Qt();qe();kt();oe();ns();Tr();He();Yb="write_health_hook_runs",Xb="write_health_hook_findings",Qb=/\.(tsx?|jsx?|css)$/,Zb=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(wu,"declPath");s(ew,"routesForPath");s(tw,"routesAreEmpty");s(nw,"takeUnreported");s(rw,"formatWriteHealth");s(iw,"repoRelative");s(ow,"readContracts");s(Su,"runOnWriteHealth")});var Fu={};q(Fu,{agentHostPidCandidates:()=>me,closeTrackedSession:()=>Nu,effectiveConfig:()=>Ue,grandparentPid:()=>Du,recordGuardSignals:()=>Cu,runFlush:()=>kw,runHookStatus:()=>vw,runOnFileEdit:()=>_w,runOnFileWrite:()=>yw,runOnRepoHealth:()=>bu,runOnSessionStart:()=>pw,runOnToolUse:()=>hw,runOnWriteHealth:()=>Su,runSessionEndMetrics:()=>is,runSyncConfig:()=>Ew,writeIdentitySideChannel:()=>rs});import{execFileSync as Ru}from"node:child_process";import{existsSync as Pr,readFileSync as Au,realpathSync as sw}from"node:fs";import{writeFile as aw}from"node:fs/promises";import{homedir as Tu}from"node:os";import{isAbsolute as Nr,join as sn,relative as Iu}from"node:path";function Cu(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 Nu(e,t,n=Date.now()){uw(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 uw(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>Cr&&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>Cr&&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>Cr&&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>Cr&&delete e.sessions[n]}}function Ue(e){if(e.config)return e.config;let t=O();return t===null?null:{api_key:t,endpoint:Ar}}function Pu(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 pw(){let e=await j();if(Ue(e)===null)return 0;let t=await C(),n=Mu(t);if(n===null)return 0;Pu(e,n),await se(e);try{rs(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=bt(i,{hostPids:me(),cwd:o}),c=du(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(fw());if(ti(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 fw(){try{let e=sn(Tu(),".claude","settings.json");return Pr(e)?Au(e,"utf8"):null}catch{return null}}function rs(e,t,n,r=ht()){let i=n??me();if(i.length===0)return;let o=xd(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)Rd({dir:r,agentPid:p,sessionId:t,transcriptStem:o,cwd:a,transcriptPath:c,model:l})}function Du(){try{if(process.platform==="win32")return null;let e=Ru("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=Du();return n!==null&&n>1&&n!==t&&e.push(n),e}async function hw(){let e=await j();if(Ue(e)===null)return 0;let t=await C(),n=Mu(t)??"unknown",r=Pu(e,n);r.tool_call_count+=1;try{let a=me().filter(c=>Ad(ht(),c,mw));n!=="unknown"&&a.length>0&&rs(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),Cu(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 No(r.transcript_path);a&&(r.token_count=a.total_tokens,await ww(e,r))}return await se(e),0}function gw(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 mw(){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=Ru(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(fw(a,a.namespace))),0}catch{return 0}}async function hw(){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),p=Nr(i)?rw(i):$e(i),d=Ru(l,p).replace(/\\/g,"/");if(d.length===0||d.startsWith("..")||Cr(d))return 0;let u=su(c.snap,d,{via:c.via,currentBranch:c.via==="cwd"?gw(r):null,nowMs:Date.now()});return u===null||process.stdout.write(ve(u)),0}catch{return 0}}function gw(e){try{let n=Su("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 yw(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 iw(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 yw(){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=Nr(t)?t:sn(n,t);if(Pr(r))return 0;let i=ae(n),o=Iu(i,$e(r));if(o.length===0||o.startsWith("..")||Nr(o))return 0;let a=await Ce(i,o);return!a.taken||a.namespace===null||process.stdout.write(wt(gw(a,a.namespace))),0}catch{return 0}}async function _w(){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=Nr(n)?n:sn(r,n),o=M();if(o===null)return 0;let a=mt(o);if(a.length===0)return 0;let c=bt(a,{hostPids:me(),cwd:r});if(c===null)return 0;let l=ae(r),p=Pr(i)?sw(i):$e(i),d=Iu(l,p).replace(/\\/g,"/");if(d.length===0||d.startsWith("..")||Nr(d))return 0;let u=lu(c.snap,d,{via:c.via,currentBranch:c.via==="cwd"?bw(r):null,nowMs:Date.now()});return u===null||process.stdout.write(ve(u)),0}catch{return 0}}function bw(e){try{let n=Ru("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 ww(e,t){let n=es(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 aw(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 ns(e){try{let t=await $(),n=Ue(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Tu(t,r),await se(t)),await Nu(n,sw)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
158
- `)}}async function bw(){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 Nu(t,aw);return process.stdout.write(JSON.stringify(n,null,2)+`
159
- `),n.ok?0:1}async function Nu(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=nu(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 _w(){let e=await $(),t=Ue(e),n=ww(),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:vu}:{}}},null,2)+`
157
+ `)}async function is(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]&&(Nu(t,r),await se(t)),await Ou(n,lw)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
158
+ `)}}async function kw(){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 Ou(t,dw);return process.stdout.write(JSON.stringify(n,null,2)+`
159
+ `),n.ok?0:1}async function Ou(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=ou(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 vw(){let e=await j(),t=Ue(e),n=Sw(),r=ti(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:es(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:xu}:{}}},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(` ${vu}
164
- `)}return 0}function ww(){let e=sn(xu(),".claude","settings.json"),t=null;try{Nr(e)&&(t=Eu(e,"utf8"))}catch{}return{settingsPath:e,findings:Dt(t)}}async function kw(){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??ow,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(` ${xu}
164
+ `)}return 0}function Sw(){let e=sn(Tu(),".claude","settings.json"),t=null;try{Pr(e)&&(t=Au(e,"utf8"))}catch{}return{settingsPath:e,findings:Dt(t)}}async function Ew(){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??cw,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 Pu(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var ow,sw,aw,Ir,uw,vu,rs=_(()=>{"use strict";bt();Qt();qe();B();Ot();hr();ge();Yo();Xo();yr();oe();kt();Ar();He();es();ku();ow=process.env.MAIND_THRESHOLDS_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds",sw=1500,aw=1e4,Ir=7*24*60*60*1e3;s(Au,"recordGuardSignals");s(Tu,"closeTrackedSession");s(cw,"gcState");s(Ue,"effectiveConfig");s(Iu,"getOrCreateSession");s(lw,"runOnSessionStart");s(dw,"readSettingsRaw");s(ts,"writeIdentitySideChannel");uw=6e4;s(Cu,"grandparentPid");s(me,"agentHostPidCandidates");s(pw,"runOnToolUse");s(fw,"denyReason");s(mw,"runOnFileWrite");s(hw,"runOnFileEdit");s(gw,"currentGitBranch");s(yw,"maybeEmitAdvisory");s(ns,"runSessionEndMetrics");s(bw,"runFlush");s(Nu,"flushPending");s(_w,"runHookStatus");vu="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(ww,"readHookWiring");s(kw,"runSyncConfig");s(Pu,"sessionIdOf")});function Ou(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Mu=_(()=>{"use strict";s(Ou,"resolveConnection")});function Lu(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 Fu,is=_(()=>{"use strict";bt();Fu=2e3;s(Lu,"buildCostPayload")});function $u(e){if(!e||e.announce_error!=null)return null;let t=e.own_session_id;return typeof t=="string"&&vw.test(t)?t.toLowerCase():null}var vw,ju=_(()=>{"use strict";vw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s($u,"snapshotSessionId")});async function Hu(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=Lu(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 Uu=_(()=>{"use strict";bt();is();s(Hu,"ingestSessionEnd")});var Ku={};q(Ku,{runOnSessionEnd:()=>Nw});import{execFileSync as os}from"node:child_process";function Ew(e,t){try{let n=O(),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 Ou({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function xw(){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=$u(r?.snap);if(i!==null)return i}}catch{}let t=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return e.test(t)?t:null}function Rw(){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 Aw(e){let t=Gu.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 Gu.set(e,n),n}function Tw(e){let t=Wu.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 Wu.set(e,n),n}async function Iw(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:Fu})}catch{return null}}async function Cw(e,t,n,r,i){let o=fetch(Sw,{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 Nw(){try{for(let i of me())Rd(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=xw(),a=O();await Hu({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:o,repoRoot:Rw(),resolveRoot:Aw,projectKeyOf:Tw,fetchContext:s(c=>Iw(e,i,c,o),"fetchContext"),post:s((c,l)=>Cw(e,i,c,1500,l),"post"),connection:Ew})}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 Sw,Gu,Wu,Bu=_(()=>{"use strict";bt();Xe();B();nn();Yo();Xo();oe();rs();Ro();hr();ge();yr();xe();Mu();is();ju();Uu();Sw=Rr;s(Ew,"connectionVerdict");s(xw,"presenceSessionId");s(Rw,"sessionRepoRoot");Gu=new Map;s(Aw,"gitRootOf");Wu=new Map;s(Tw,"projectKeyOfRoot");s(Iw,"fetchCostContext");s(Cw,"postWithTimeout");s(Nw,"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 Pw(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 Vu(e,t,n=process.stdout){let r=Pw(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}`:""}
170
+ `),0)}function Mu(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var cw,lw,dw,Cr,mw,xu,os=b(()=>{"use strict";_t();Qt();qe();B();Ot();gr();ge();Qo();Zo();_r();oe();kt();Tr();He();ns();Eu();cw=process.env.MAIND_THRESHOLDS_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds",lw=1500,dw=1e4,Cr=7*24*60*60*1e3;s(Cu,"recordGuardSignals");s(Nu,"closeTrackedSession");s(uw,"gcState");s(Ue,"effectiveConfig");s(Pu,"getOrCreateSession");s(pw,"runOnSessionStart");s(fw,"readSettingsRaw");s(rs,"writeIdentitySideChannel");mw=6e4;s(Du,"grandparentPid");s(me,"agentHostPidCandidates");s(hw,"runOnToolUse");s(gw,"denyReason");s(yw,"runOnFileWrite");s(_w,"runOnFileEdit");s(bw,"currentGitBranch");s(ww,"maybeEmitAdvisory");s(is,"runSessionEndMetrics");s(kw,"runFlush");s(Ou,"flushPending");s(vw,"runHookStatus");xu="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(Sw,"readHookWiring");s(Ew,"runSyncConfig");s(Mu,"sessionIdOf")});function Lu(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var $u=b(()=>{"use strict";s(Lu,"resolveConnection")});function Hu(e,t,n,r=Date.now()){let i=t===null?null:Go(t),o=Bo(e,i,{repoRoot:n,nowMs:r});return o.length===0?null:{slices:o,context_ok:i!==null}}var ju,ss=b(()=>{"use strict";_t();ju=2e3;s(Hu,"buildCostPayload")});function Uu(e){if(!e||e.announce_error!=null)return null;let t=e.own_session_id;return typeof t=="string"&&xw.test(t)?t.toLowerCase():null}var xw,Gu=b(()=>{"use strict";xw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Uu,"snapshotSessionId")});async function Wu(e){let t=e.now??Date.now,n=e.fetchContext(e.projectKey),{turns:r}=await tn(e.transcriptPath),i=e.resolveRoot?Vo(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([Do(e.transcriptPath,{turns:r}),qo(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=Hu(r,p,d,t()),f=Fo(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 Ku=b(()=>{"use strict";_t();ss();s(Wu,"ingestSessionEnd")});var qu={};q(qu,{runOnSessionEnd:()=>Ow});import{execFileSync as as}from"node:child_process";function Aw(e,t){try{let n=M(),r=n!==null&&!Ro(process.env,ne()),i=null;if(n!==null){let o=bt(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 Lu({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function Tw(){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=bt(mt(n),{hostPids:me(),cwd:process.cwd()}),i=Uu(r?.snap);if(i!==null)return i}}catch{}let t=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return e.test(t)?t:null}function Iw(){try{let e=as("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function Cw(e){let t=Bu.get(e);if(t!==void 0)return t;let n=null;try{let r=as("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 Bu.set(e,n),n}function Nw(e){let t=Vu.get(e);if(t!==void 0)return t;let n=null;try{let r=as("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=Jr(r))}catch{n=null}return Vu.set(e,n),n}async function Pw(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:ju})}catch{return null}}async function Dw(e,t,n,r,i){let o=fetch(Rw,{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=Mo(Oo(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 Ow(){try{for(let i of me())Td(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=Tw(),a=M();await Wu({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:o,repoRoot:Iw(),resolveRoot:Cw,projectKeyOf:Nw,fetchContext:s(c=>Pw(e,i,c,o),"fetchContext"),post:s((c,l)=>Dw(e,i,c,1500,l),"post"),connection:Aw})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
172
+ `)}return await is(n),0}var Rw,Bu,Vu,zu=b(()=>{"use strict";_t();Xe();B();nn();Qo();Zo();oe();os();Ao();gr();ge();_r();xe();$u();ss();Gu();Ku();Rw=Ar;s(Aw,"connectionVerdict");s(Tw,"presenceSessionId");s(Iw,"sessionRepoRoot");Bu=new Map;s(Cw,"gitRootOf");Vu=new Map;s(Nw,"projectKeyOfRoot");s(Pw,"fetchCostContext");s(Dw,"postWithTimeout");s(Ow,"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=b(()=>{"use strict";Xe();ce();s(Q,"resolveGuardConfig");s(vt,"writeGuardConfig")});function Mw(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 Ju(e,t,n=process.stdout){let r=Mw(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 oi(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 qu=_(()=>{"use strict";Ot();oi();Ge();s(Pw,"parseGuardInstallFlags");s(Vu,"runGuardInstall")});import{existsSync as zu}from"node:fs";import{mkdir as Dw,readFile as Ow,readdir as Mw,rename as Fw,stat as Lw,unlink as $w,writeFile as jw}from"node:fs/promises";import{join as Pr}from"node:path";function Ju(e){return Pr(an,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function he(e){try{let t=Ju(e);if(!zu(t))return{};let n=JSON.parse(await Ow(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function J(e,t){await Dw(an,{recursive:!0,mode:448});let n=Ju(e),r=`${n}.tmp`;await jw(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await Fw(r,n)}async function Yu(e=7*24*60*60*1e3,t=Date.now()){try{if(!zu(an))return;for(let n of await Mw(an)){if(!n.endsWith(".json"))continue;let r=Pr(an,n);try{let i=await Lw(r);t-i.mtimeMs>e&&await $w(r)}catch{}}}catch{}}var St,an,Et=_(()=>{"use strict";He();St=Pr(je,"guard"),an=Pr(St,"sessions");s(Ju,"sessionFile");s(he,"loadGuardSession");s(J,"saveGuardSession");s(Yu,"sweepOldGuardSessions")});import{existsSync as Hw}from"node:fs";import{appendFile as Uw,mkdir as Gw,open as Ww}from"node:fs/promises";import{join as Kw}from"node:path";async function V(e){try{await Gw(St,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
185
- `;await Uw(xt,t,{mode:384})}catch{}}async function Xu(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(!Hw(xt))return t;let n=await Ww(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=Kw(St,"events.jsonl");s(V,"appendGuardEvent");s(Xu,"readGuardEventCounts")});var Zu={};q(Zu,{runGuard:()=>Jw});import{existsSync as Bw,readFileSync as Vw}from"node:fs";import{homedir as Qu}from"node:os";import{join as qw}from"node:path";async function Jw(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Vu(n,Qu());case"status":return Xw();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 Yu=b(()=>{"use strict";Ot();si();Ge();s(Mw,"parseGuardInstallFlags");s(Ju,"runGuardInstall")});import{existsSync as Xu}from"node:fs";import{mkdir as Fw,readFile as Lw,readdir as $w,rename as jw,stat as Hw,unlink as Uw,writeFile as Gw}from"node:fs/promises";import{join as Dr}from"node:path";function Qu(e){return Dr(an,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function he(e){try{let t=Qu(e);if(!Xu(t))return{};let n=JSON.parse(await Lw(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function J(e,t){await Fw(an,{recursive:!0,mode:448});let n=Qu(e),r=`${n}.tmp`;await Gw(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await jw(r,n)}async function Zu(e=7*24*60*60*1e3,t=Date.now()){try{if(!Xu(an))return;for(let n of await $w(an)){if(!n.endsWith(".json"))continue;let r=Dr(an,n);try{let i=await Hw(r);t-i.mtimeMs>e&&await Uw(r)}catch{}}}catch{}}var St,an,Et=b(()=>{"use strict";He();St=Dr(je,"guard"),an=Dr(St,"sessions");s(Qu,"sessionFile");s(he,"loadGuardSession");s(J,"saveGuardSession");s(Zu,"sweepOldGuardSessions")});import{existsSync as Ww}from"node:fs";import{appendFile as Kw,mkdir as Bw,open as Vw}from"node:fs/promises";import{join as qw}from"node:path";async function V(e){try{await Bw(St,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
185
+ `;await Kw(xt,t,{mode:384})}catch{}}async function ep(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(!Ww(xt))return t;let n=await Vw(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=b(()=>{"use strict";Et();xt=qw(St,"events.jsonl");s(V,"appendGuardEvent");s(ep,"readGuardEventCounts")});var np={};q(np,{runGuard:()=>Qw});import{existsSync as zw,readFileSync as Jw}from"node:fs";import{homedir as tp}from"node:os";import{join as Yw}from"node:path";async function Qw(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Ju(n,tp());case"status":return ek();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 Yw(n);default:return process.stdout.write(zw),t===void 0||t==="--help"||t==="-h"?0:1}}async function Yw(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 Zw(n);default:return process.stdout.write(Xw),t===void 0||t==="--help"||t==="-h"?0:1}}async function Zw(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 Xw(){let e=Q(),t=qw(Qu(),".claude","settings.json"),n=null;try{Bw(t)&&(n=Vw(t,"utf8"))}catch{}let r=Dt(n,{},Rn),i=await Xu();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 ek(){let e=Q(),t=Yw(tp(),".claude","settings.json"),n=null;try{zw(t)&&(n=Jw(t,"utf8"))}catch{}let r=Dt(n,{},Rn),i=await ep();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 zw,ep=_(()=>{"use strict";Ot();Ge();qu();Rt();Et();zw=["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(Yw,"runGuardSkip");s(Xw,"runGuardStatus")});var op={};q(op,{BRIEFING_CACHE_FILE:()=>np,formatInjection:()=>ip,resolveBriefingInjection:()=>rp,runGuardInject:()=>ak});import{existsSync as Qw}from"node:fs";import{mkdir as Zw,readFile as ek,rename as tk,writeFile as nk}from"node:fs/promises";import{dirname as rk,join as ik}from"node:path";async function rp(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??np,o=n.fetcher??tu,a=await ck(i);if(a!==null&&r-Date.parse(a.fetched_at)<ok&&a.project_key===e)return{text:a.text,via:"cache"};let l=await o({apiKey:t,deviceId:dk(),projectKey:e,bridgeVersion:P,timeoutMs:sk});return l!==null?(await lk(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 ak(){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 Yu();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=D();if(i===null)return 0;let o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=O(),c=await rp(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(ip(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 ip(e,t){let n=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=e;return Buffer.byteLength(r,"utf8")>tp&&(r=r.slice(0,tp)+`
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 Xw,rp=b(()=>{"use strict";Ot();Ge();Yu();Rt();Et();Xw=["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(Qw,"runGuard");s(Zw,"runGuardSkip");s(ek,"runGuardStatus")});var cp={};q(cp,{BRIEFING_CACHE_FILE:()=>op,formatInjection:()=>ap,resolveBriefingInjection:()=>sp,runGuardInject:()=>dk});import{existsSync as tk}from"node:fs";import{mkdir as nk,readFile as rk,rename as ik,writeFile as ok}from"node:fs/promises";import{dirname as sk,join as ak}from"node:path";async function sp(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??op,o=n.fetcher??iu,a=await uk(i);if(a!==null&&r-Date.parse(a.fetched_at)<ck&&a.project_key===e)return{text:a.text,via:"cache"};let l=await o({apiKey:t,deviceId:fk(),projectKey:e,bridgeVersion:P,timeoutMs:lk});return l!==null?(await pk(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 dk(){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 Zu();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 sp(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(ap(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 ap(e,t){let n=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=e;return Buffer.byteLength(r,"utf8")>ip&&(r=r.slice(0,ip)+`
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 ck(e){try{if(!Qw(e))return null;let t=JSON.parse(await ek(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 lk(e,t){try{await Zw(rk(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await nk(n,JSON.stringify(t,null,2),{mode:384}),await tk(n,e)}catch{}}function dk(){try{return U()}catch{return null}}var np,ok,sk,tp,sp=_(()=>{"use strict";B();oe();ge();xe();Ge();Rt();Et();nn();np=ik(St,"briefing-cache.json"),ok=12*60*60*1e3,sk=3e3,tp=10*1024;s(rp,"resolveBriefingInjection");s(ak,"runGuardInject");s(ip,"formatInjection");s(ck,"readCache");s(lk,"writeCache");s(dk,"safeDeviceId")});var dp={};q(dp,{decideGate:()=>lp,runGuardGate:()=>pk});function lp(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:ap(n)}:(n.deny_count??0)>=cp?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. "+ap(n)}:{kind:"deny",reason:uk(e.sessionId,n)}}function ap(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 uk(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 uk(e){try{if(!tk(e))return null;let t=JSON.parse(await rk(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 pk(e,t){try{await nk(sk(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await ok(n,JSON.stringify(t,null,2),{mode:384}),await ik(n,e)}catch{}}function fk(){try{return U()}catch{return null}}var op,ck,lk,ip,lp=b(()=>{"use strict";B();oe();ge();xe();Ge();Rt();Et();nn();op=ak(St,"briefing-cache.json"),ck=12*60*60*1e3,lk=3e3,ip=10*1024;s(sp,"resolveBriefingInjection");s(dk,"runGuardInject");s(ap,"formatInjection");s(uk,"readCache");s(pk,"writeCache");s(fk,"safeDeviceId")});var fp={};q(fp,{decideGate:()=>pp,runGuardGate:()=>hk});function pp(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:dp(n)}:(n.deny_count??0)>=up?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. "+dp(n)}:{kind:"deny",reason:mk(e.sessionId,n)}}function dp(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 mk(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 ${cp} denies this gate downgrades itself to warn.`}async function pk(){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=lp({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 cp,up=_(()=>{"use strict";oe();kt();He();ge();Ge();Rt();Et();cp=3;s(lp,"decideGate");s(ap,"warnText");s(uk,"denyText");s(pk,"runGuardGate")});var fp={};q(fp,{decideStopGate:()=>pp,runGuardStop:()=>mk});function pp(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function mk(){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 pp({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:fk})),await J(n,{...r,stop_blocked:!0}),await V({event:"stop_block",session_id:n})),0}catch{return 0}}var fk,mp=_(()=>{"use strict";oe();He();Ge();Rt();Et();s(pp,"decideStopGate");fk="[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(mk,"runGuardStop")});import{appendFile as hk,mkdir as gk,readFile as gp,rename as yp,writeFile as bp}from"node:fs/promises";import{homedir as _p}from"node:os";import{join as wp}from"node:path";function kp(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 wp(_p(),".maind","gateway","attest-spool.jsonl")}async function ss(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 vp(e){try{await gk(wp(_p(),".maind","gateway"),{recursive:!0}),await hk(We(),JSON.stringify(e)+`
208
- `,{mode:384}),await yk()}catch{}}async function yk(){try{let t=(await gp(We(),"utf8")).split(`
209
- `).filter(r=>r.trim());if(t.length<=hp)return;let n=`${We()}.${process.pid}.tmp`;await bp(n,t.slice(-hp).join(`
207
+ After ${up} denies this gate downgrades itself to warn.`}async function hk(){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=pp({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 up,mp=b(()=>{"use strict";oe();kt();He();ge();Ge();Rt();Et();up=3;s(pp,"decideGate");s(dp,"warnText");s(mk,"denyText");s(hk,"runGuardGate")});var gp={};q(gp,{decideStopGate:()=>hp,runGuardStop:()=>yk});function hp(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function yk(){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 hp({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:gk})),await J(n,{...r,stop_blocked:!0}),await V({event:"stop_block",session_id:n})),0}catch{return 0}}var gk,yp=b(()=>{"use strict";oe();He();Ge();Rt();Et();s(hp,"decideStopGate");gk="[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(yk,"runGuardStop")});import{appendFile as _k,mkdir as bk,readFile as bp,rename as wp,writeFile as kp}from"node:fs/promises";import{homedir as vp}from"node:os";import{join as Sp}from"node:path";function Ep(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 Sp(vp(),".maind","gateway","attest-spool.jsonl")}async function cs(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 xp(e){try{await bk(Sp(vp(),".maind","gateway"),{recursive:!0}),await _k(We(),JSON.stringify(e)+`
208
+ `,{mode:384}),await wk()}catch{}}async function wk(){try{let t=(await bp(We(),"utf8")).split(`
209
+ `).filter(r=>r.trim());if(t.length<=_p)return;let n=`${We()}.${process.pid}.tmp`;await kp(n,t.slice(-_p).join(`
210
210
  `)+`
211
- `,{mode:384}),await yp(n,We())}catch{}}async function Sp(){let e;try{e=(await gp(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 bp(r,t.length>0?t.join(`
211
+ `,{mode:384}),await wp(n,We())}catch{}}async function Rp(){let e;try{e=(await bp(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 cs(i)||(n=!0,t.push(r))}try{let r=`${We()}.${process.pid}.tmp`;await kp(r,t.length>0?t.join(`
213
213
  `)+`
214
- `:"",{mode:384}),await yp(r,We())}catch{}}var hp,Ep=_(()=>{"use strict";B();nn();xe();hp=256;s(kp,"aggregateWindow");s(We,"attestSpoolPath");s(ss,"postAttestation");s(vp,"spoolAttestation");s(yk,"capSpool");s(Sp,"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 xp(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 Rp(e,t=de()){await xp({gateway_mode:e},t)}async function Ap(e,t=de()){await xp({gateway_attest:e},t)}function Tp(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(xp,"writeGatewayConfigPatch");s(Rp,"writeGatewayMode");s(Ap,"writeGatewayAttest");s(Tp,"resolveShaProofMode")});function Cp(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"&&bk.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 _k(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Np(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let o of n)_k(o,e,t)&&(i===null||Ip[o.severity]>Ip[i.severity])&&(i=o);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function Pp(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 bk,Ip,cs=_(()=>{"use strict";bk=new Set(["required","recommended","info"]);s(Cp,"extractGatewayRules");Ip={required:2,recommended:1,info:0};s(_k,"ruleMatches");s(Np,"decideToolCall");s(Pp,"policyDenyText")});import{mkdirSync as wk,readFileSync as kk,renameSync as vk,writeFileSync as Sk}from"node:fs";import{homedir as Ek}from"node:os";import{dirname as xk,join as Rk}from"node:path";function Dp(){return Rk(Ek(),".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=Dp();wk(xk(i),{recursive:!0});let o=`${i}.${process.pid}.tmp`;Sk(o,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),vk(o,i)}catch{}}function Mr(e){try{let t=kk(Dp(),"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(Dp,"policyCachePath");s(Or,"writePolicyCache");s(Mr,"readPolicyCache")});function ln(e=process.env){let t=e.MAIND_MCP_URL??Jo,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 Cp(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 Ak(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 Tk(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"}:Ak(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Op(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 Mp(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 Fp(e){return Object.entries(e).map(([t,n])=>{let r=Tk(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var Lp=_(()=>{"use strict";s(dn,"isGatewayWrapped");s(Ak,"isMaindProxyEntry");s(Tk,"classifyServer");s(Op,"wrapServerEntry");s(Mp,"unwrapServerEntry");s(Fp,"planRewrites")});var Wp={};q(Wp,{runGatewayInstall:()=>Ok,runGatewayUninstall:()=>Mk});import{existsSync as Ik,readFileSync as Ck}from"node:fs";import{homedir as Nk}from"node:os";import{join as $p}from"node:path";import{createInterface as Pk}from"node:readline";function jp(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 Hp(){return[{label:"Claude Code (project .mcp.json)",path:$p(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:$p(Nk(),".claude.json")}]}async function Up(e){let t=Pk({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 Gp(e){let t=Dk(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 Dk(e){try{return Ik(e)?Ck(e,"utf8"):null}catch{return null}}async function Ok(e){let t=jp(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 Hp()){let o=Gp(i.path);if(o===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
217
- `);continue}let a=Fp(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 Up(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
214
+ `:"",{mode:384}),await wp(r,We())}catch{}}var _p,Ap=b(()=>{"use strict";B();nn();xe();_p=256;s(Ep,"aggregateWindow");s(We,"attestSpoolPath");s(cs,"postAttestation");s(xp,"spoolAttestation");s(wk,"capSpool");s(Rp,"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 Or(e=process.env,t=ne()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function Tp(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 Ip(e,t=de()){await Tp({gateway_mode:e},t)}async function Cp(e,t=de()){await Tp({gateway_attest:e},t)}function Np(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 ls=b(()=>{"use strict";Xe();ce();s(cn,"resolveGatewayMode");s(Or,"resolveGatewayAttest");s(Tp,"writeGatewayConfigPatch");s(Ip,"writeGatewayMode");s(Cp,"writeGatewayAttest");s(Np,"resolveShaProofMode")});function Dp(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"&&kk.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 vk(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Op(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let o of n)vk(o,e,t)&&(i===null||Pp[o.severity]>Pp[i.severity])&&(i=o);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function Mp(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 kk,Pp,ds=b(()=>{"use strict";kk=new Set(["required","recommended","info"]);s(Dp,"extractGatewayRules");Pp={required:2,recommended:1,info:0};s(vk,"ruleMatches");s(Op,"decideToolCall");s(Mp,"policyDenyText")});import{mkdirSync as Sk,readFileSync as Ek,renameSync as xk,writeFileSync as Rk}from"node:fs";import{homedir as Ak}from"node:os";import{dirname as Tk,join as Ik}from"node:path";function Fp(){return Ik(Ak(),".maind","gateway","policy-cache.json")}function Mr(e,t,n=new Date().toISOString()){try{let r={version:us,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=Fp();Sk(Tk(i),{recursive:!0});let o=`${i}.${process.pid}.tmp`;Rk(o,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),xk(o,i)}catch{}}function Fr(e){try{let t=Ek(Fp(),"utf8"),n=JSON.parse(t);return n.version!==us||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:us,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var us,ps=b(()=>{"use strict";us=1;s(Fp,"policyCachePath");s(Mr,"writePolicyCache");s(Fr,"readPolicyCache")});function ln(e=process.env){let t=e.MAIND_MCP_URL??Xo,n=O();return{mcpUrl:t,keyFp:n?fn(n):"anon"}}async function Lr(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 Dp(i)}var fs=b(()=>{"use strict";qe();B();nn();ge();xe();ds();s(ln,"policyIdentity");s(Lr,"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 Ck(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 Nk(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"}:Ck(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Lp(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 $p(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 jp(e){return Object.entries(e).map(([t,n])=>{let r=Nk(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var Hp=b(()=>{"use strict";s(dn,"isGatewayWrapped");s(Ck,"isMaindProxyEntry");s(Nk,"classifyServer");s(Lp,"wrapServerEntry");s($p,"unwrapServerEntry");s(jp,"planRewrites")});var Vp={};q(Vp,{runGatewayInstall:()=>Lk,runGatewayUninstall:()=>$k});import{existsSync as Pk,readFileSync as Dk}from"node:fs";import{homedir as Ok}from"node:os";import{join as Up}from"node:path";import{createInterface as Mk}from"node:readline";function Gp(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 Wp(){return[{label:"Claude Code (project .mcp.json)",path:Up(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:Up(Ok(),".claude.json")}]}async function Kp(e){let t=Mk({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 Bp(e){let t=Fk(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 Fk(e){try{return Pk(e)?Dk(e,"utf8"):null}catch{return null}}async function Lk(e){let t=Gp(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 Wp()){let o=Bp(i.path);if(o===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
217
+ `);continue}let a=jp(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 Kp(`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]=Op(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]=Lp(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 Mk(e){let t=jp(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 Hp()){let i=Gp(r.path);if(i===null)continue;let o=!1;for(let[a,c]of Object.entries(i.servers)){if(!dn(c)||!(t.yes||await Up(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let p=Mp(c);if(p===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
227
+ `),0}async function $k(e){let t=Gp(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 Wp()){let i=Bp(r.path);if(i===null)continue;let o=!1;for(let[a,c]of Object.entries(i.servers)){if(!dn(c)||!(t.yes||await Kp(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let p=$p(c);if(p===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
229
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 F(r.path,JSON.stringify(i.raw,null,2)+`
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 Kp=_(()=>{"use strict";ce();Ye();Lp();s(jp,"parseFlags");s(Hp,"targets");s(Up,"confirm");s(Gp,"loadConfig");s(Dk,"readFileSafeSync");s(Ok,"runGatewayInstall");s(Mk,"runGatewayUninstall")});var Bp={};q(Bp,{runGatewayAttest:()=>Lk,runGatewayMode:()=>Fk,runGatewayPolicy:()=>Hk});async function Fk(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 qp=b(()=>{"use strict";ce();Ye();Hp();s(Gp,"parseFlags");s(Wp,"targets");s(Kp,"confirm");s(Bp,"loadConfig");s(Fk,"readFileSafeSync");s(Lk,"runGatewayInstall");s($k,"runGatewayUninstall")});var zp={};q(zp,{runGatewayAttest:()=>Hk,runGatewayMode:()=>jk,runGatewayPolicy:()=>Wk});async function jk(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 Rp(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 Ip(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 Lk(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 Hk(e){let t=e[0];if(t===void 0){let n=Or(),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 Ap(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 Cp(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 $k(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
245
+ `),0)}function Uk(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 jk(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 Hk(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
- `):(Or(r,o),process.stdout.write(`maind: policy refreshed (${o.length} rule(s)).
249
- `))}let i=Mr(r);return process.stdout.write(`maind: gateway mode '${n}'
247
+ `}return t}function Gk(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 Wk(e){let t=e.includes("--refresh"),n=cn(),r=ln();if(t){let o=await Lr();o===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
248
+ `):(Mr(r,o),process.stdout.write(`maind: policy refreshed (${o.length} rule(s)).
249
+ `))}let i=Fr(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 (${jk(i)}, ${r.mcpUrl}):
252
- `),process.stdout.write($k(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 Vp=_(()=>{"use strict";as();ds();us();s(Fk,"runGatewayMode");s(Lk,"runGatewayAttest");s($k,"renderRules");s(jk,"cacheAge");s(Hk,"runGatewayPolicy")});var Xp={};q(Xp,{gatewayEventsFile:()=>Jp,parseGatewayArgs:()=>Yp,runGateway:()=>qk});import{spawn as Uk}from"node:child_process";import{appendFile as Gk,mkdir as Wk}from"node:fs/promises";import{homedir as qp}from"node:os";import{basename as Kk,join as zp}from"node:path";import{createInterface as Bk}from"node:readline";function Jp(){return zp(qp(),".maind","gateway","events.jsonl")}async function Vk(e){try{let t=Jp();await Wk(zp(qp(),".maind","gateway"),{recursive:!0}),await Gk(t,JSON.stringify(e)+`
254
- `,{mode:384})}catch{}}function Yp(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 qk(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:k,runGatewayUninstall:E}=await Promise.resolve().then(()=>(Kp(),Wp));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(()=>(Vp(),Bp));return e[0]==="mode"?E(e.slice(1)):e[0]==="attest"?k(e.slice(1)):R(e.slice(1))}let t=Yp(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 (${Gk(i)}, ${r.mcpUrl}):
252
+ `),process.stdout.write(Uk(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 Jp=b(()=>{"use strict";ls();ps();fs();s(jk,"runGatewayMode");s(Hk,"runGatewayAttest");s(Uk,"renderRules");s(Gk,"cacheAge");s(Wk,"runGatewayPolicy")});var ef={};q(ef,{gatewayEventsFile:()=>Qp,parseGatewayArgs:()=>Zp,runGateway:()=>Yk});import{spawn as Kk}from"node:child_process";import{appendFile as Bk,mkdir as Vk}from"node:fs/promises";import{homedir as Yp}from"node:os";import{basename as qk,join as Xp}from"node:path";import{createInterface as zk}from"node:readline";function Qp(){return Xp(Yp(),".maind","gateway","events.jsonl")}async function Jk(e){try{let t=Qp();await Vk(Xp(Yp(),".maind","gateway"),{recursive:!0}),await Bk(t,JSON.stringify(e)+`
254
+ `,{mode:384})}catch{}}function Zp(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 Yk(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:k,runGatewayUninstall:E}=await Promise.resolve().then(()=>(qp(),Vp));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(()=>(Jp(),zp));return e[0]==="mode"?E(e.slice(1)):e[0]==="attest"?k(e.slice(1)):R(e.slice(1))}let t=Zp(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??Kk(i),c=cn(),l=Tp(),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()&&D()!==null&&c!=="off",m=null;try{m=O()}catch{m=null}let h=s(k=>{Vk(k),f&&u.push(k)},"record"),g=s(async()=>{if(!f)return;let k=kp(u.splice(0),c,a,m);k!==null&&(await ss(k)||await vp(k))},"attestAndReset");f&&Sp().catch(()=>{});let y=setInterval(()=>{g()},30*6e4);y.unref();let b=Uk(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=Bk({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=Np(E.toolName,a,d,c);if(R.kind==="deny"&&E.id!==void 0){process.stdout.write(Be(E.id,E.toolName,Pp(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 j=T??I[0];process.stderr.write(`[maind gateway] ${Ve(j,!1)}
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 Qp=_(()=>{"use strict";Ur();Ep();as();cs();Gr();ds();us();B();ge();s(Jp,"gatewayEventsFile");s(Vk,"logEvent");s(Yp,"parseGatewayArgs");s(qk,"runGateway")});var bs={};q(bs,{MAX_ENTRIES:()=>ps,TTL_MS:()=>hs,crossSessionDir:()=>gs,decideCrossSession:()=>tf,parseSessionDb:()=>ef,pruneDb:()=>ys,runGuardCrossCheck:()=>nv,runGuardCrossObserve:()=>tv,staleReason:()=>fs});import{mkdir as zk,readFile as Jk,readdir as Yk,stat as Zp,unlink as Xk,writeFile as Qk}from"node:fs/promises";import{homedir as Zk}from"node:os";import{join as ms}from"node:path";function gs(){return ms(Zk(),".maind","cross-session")}function ef(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 tf(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 nf(e){let t=gs();return await zk(t,{recursive:!0}),ms(t,`${e}.json`)}async function rf(e,t){try{let n=await Jk(await nf(e),"utf8");return ys(ef(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function of(e,t){try{await Qk(await nf(e),JSON.stringify(t),{mode:384})}catch{}}async function ev(e){try{let t=gs();for(let n of await Yk(t)){if(!n.endsWith(".json"))continue;let r=ms(t,n),i=await Zp(r).catch(()=>null);i&&e-i.mtimeMs>hs&&await Xk(r).catch(()=>{})}}catch{}}async function sf(e){try{return(await Zp(e)).mtimeMs}catch{return}}async function tv(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 sf(o);if(a===void 0)return 0;let c=await rf(i,t);return c.files[o]={m:a,t},delete c.warned[o],await of(i,ys(c,t)),await ev(t),0}catch{return 0}}async function nv(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 rf(i,t),c=tf(a.files[o]?.m,await sf(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 of(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(ef,"parseSessionDb");s(ys,"pruneDb");s(tf,"decideCrossSession");s(fs,"staleReason");s(nf,"dbPath");s(rf,"loadDb");s(of,"saveDb");s(ev,"sweepStaleSessionFiles");s(sf,"fileMtime");s(tv,"runGuardCrossObserve");s(nv,"runGuardCrossCheck")});var ks={};q(ks,{INDEX_REFRESH_WORKER:()=>lf,acquireLock:()=>uf,releaseLock:()=>ws,runIndexRefreshWorker:()=>dv,runOnIndexRefresh:()=>lv});import{spawn as rv}from"node:child_process";import{existsSync as iv,mkdirSync as ov,rmdirSync as af,statSync as sv}from"node:fs";import{join as cf}from"node:path";function df(e){return cf(e,".maind","index-refresh.lock")}function cv(e){return cf(e,".maind","code-index.sqlite")}function uf(e,t=Date.now()){let n=df(e);try{if(t-sv(n).mtimeMs<av)return!1;af(n)}catch{}try{return ov(n,{recursive:!1}),!0}catch{return!1}}function ws(e){try{af(df(e))}catch{}}async function lv(){try{let e=await C(),t=z(typeof e.cwd=="string"?e.cwd:process.cwd());if(!iv(cv(t))||!uf(t))return 0;let n=process.argv[1];if(n===void 0)return ws(t),0;rv(process.execPath,[n,lf,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function dv(){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 av,lf,vs=_(()=>{"use strict";oe();Xt();av=30*6e4,lf="index-refresh-run";s(df,"lockPath");s(cv,"indexDbPath");s(uf,"acquireLock");s(ws,"releaseLock");s(lv,"runOnIndexRefresh");s(dv,"runIndexRefreshWorker")});import{randomUUID as uv}from"node:crypto";import{createInterface as Nf}from"node:readline";var pf=[["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 ff(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of pf)if(t.includes(n))return r;return null}s(ff,"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=ff(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 Pf="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=Df(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=Of(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??Pf}async run(){let t=Nf({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=Lf(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}
264
+ `),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r??qk(i),c=cn(),l=Np(),p=l==="off"?null:un(),d=c==="off"?[]:Fr(ln())?.rules??[];c!=="off"&&Lr().then(k=>{k!==null&&(d=k,Mr(ln(),k))}).catch(()=>{});let u=[],f=Or()&&O()!==null&&c!=="off",m=null;try{m=M()}catch{m=null}let h=s(k=>{Jk(k),f&&u.push(k)},"record"),g=s(async()=>{if(!f)return;let k=Ep(u.splice(0),c,a,m);k!==null&&(await cs(k)||await xp(k))},"attestAndReset");f&&Rp().catch(()=>{});let y=setInterval(()=>{g()},30*6e4);y.unref();let _=Kk(i,o,{stdio:["pipe","pipe","inherit"]});_.stdout.pipe(process.stdout),_.on("error",k=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(k)}
265
+ `),process.exitCode=1});let w=zk({input:process.stdin,terminal:!1});w.on("line",k=>{let E=Ts(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(jr("deny",a,E.toolName,Date.now()));return}let R=Op(E.toolName,a,d,c);if(R.kind==="deny"&&E.id!==void 0){process.stdout.write(Be(E.id,E.toolName,Mp(E.toolName,R.rule))+`
267
+ `),h(Hr("policy_deny",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));return}(R.kind==="warn"||R.kind==="deny")&&h(Hr("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(Ur("sha_deny",a,E.toolName,Date.now()));return}let A=T??I[0];process.stderr.write(`[maind gateway] ${Ve(A,!1)}
269
+ `),h(Ur("sha_warn",a,E.toolName,Date.now()))}h(jr("tool_call",a,E.toolName,Date.now()))}_.stdin.write(k+`
270
+ `)}),w.on("close",()=>{_.stdin.end()});let v=await new Promise(k=>{_.on("exit",(E,R)=>{k(E??(R?1:0))})});return clearInterval(y),await g(),v}var tf=b(()=>{"use strict";Gr();Ap();ls();ds();Wr();ps();fs();B();ge();s(Qp,"gatewayEventsFile");s(Jk,"logEvent");s(Zp,"parseGatewayArgs");s(Yk,"runGateway")});var ws={};q(ws,{MAX_ENTRIES:()=>ms,TTL_MS:()=>ys,crossSessionDir:()=>_s,decideCrossSession:()=>of,parseSessionDb:()=>rf,pruneDb:()=>bs,runGuardCrossCheck:()=>ov,runGuardCrossObserve:()=>iv,staleReason:()=>hs});import{mkdir as Xk,readFile as Qk,readdir as Zk,stat as nf,unlink as ev,writeFile as tv}from"node:fs/promises";import{homedir as nv}from"node:os";import{join as gs}from"node:path";function _s(){return gs(nv(),".maind","cross-session")}function rf(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 bs(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=ys);return n.length>ms&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-ms)),{files:Object.fromEntries(n),warned:e.warned}}function of(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function hs(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 sf(e){let t=_s();return await Xk(t,{recursive:!0}),gs(t,`${e}.json`)}async function af(e,t){try{let n=await Qk(await sf(e),"utf8");return bs(rf(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function cf(e,t){try{await tv(await sf(e),JSON.stringify(t),{mode:384})}catch{}}async function rv(e){try{let t=_s();for(let n of await Zk(t)){if(!n.endsWith(".json"))continue;let r=gs(t,n),i=await nf(r).catch(()=>null);i&&e-i.mtimeMs>ys&&await ev(r).catch(()=>{})}}catch{}}async function lf(e){try{return(await nf(e)).mtimeMs}catch{return}}async function iv(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 lf(o);if(a===void 0)return 0;let c=await af(i,t);return c.files[o]={m:a,t},delete c.warned[o],await cf(i,bs(c,t)),await rv(t),0}catch{return 0}}async function ov(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 af(i,t),c=of(a.files[o]?.m,await lf(o));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(wt(hs(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(hs(o,c))+`
272
+ `),a.warned[o]=c.current,await cf(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 ys,ms,ks=b(()=>{"use strict";oe();kt();Ge();Rt();ys=48*3600*1e3,ms=500;s(_s,"crossSessionDir");s(rf,"parseSessionDb");s(bs,"pruneDb");s(of,"decideCrossSession");s(hs,"staleReason");s(sf,"dbPath");s(af,"loadDb");s(cf,"saveDb");s(rv,"sweepStaleSessionFiles");s(lf,"fileMtime");s(iv,"runGuardCrossObserve");s(ov,"runGuardCrossCheck")});var Ss={};q(Ss,{INDEX_REFRESH_WORKER:()=>pf,acquireLock:()=>mf,releaseLock:()=>vs,runIndexRefreshWorker:()=>fv,runOnIndexRefresh:()=>pv});import{spawn as sv}from"node:child_process";import{existsSync as av,mkdirSync as cv,rmdirSync as df,statSync as lv}from"node:fs";import{join as uf}from"node:path";function ff(e){return uf(e,".maind","index-refresh.lock")}function uv(e){return uf(e,".maind","code-index.sqlite")}function mf(e,t=Date.now()){let n=ff(e);try{if(t-lv(n).mtimeMs<dv)return!1;df(n)}catch{}try{return cv(n,{recursive:!1}),!0}catch{return!1}}function vs(e){try{df(ff(e))}catch{}}async function pv(){try{let e=await C(),t=z(typeof e.cwd=="string"?e.cwd:process.cwd());if(!av(uv(t))||!mf(t))return 0;let n=process.argv[1];if(n===void 0)return vs(t),0;sv(process.execPath,[n,pf,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function fv(){let e=process.argv[3]??z();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(bo(),Tl)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{vs(e)}return 0}var dv,pf,Es=b(()=>{"use strict";oe();Xt();dv=30*6e4,pf="index-refresh-run";s(ff,"lockPath");s(uv,"indexDbPath");s(mf,"acquireLock");s(vs,"releaseLock");s(pv,"runOnIndexRefresh");s(fv,"runIndexRefreshWorker")});import{randomUUID as mv}from"node:crypto";import{createInterface as Of}from"node:readline";var hf=[["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 gf(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of hf)if(t.includes(n))return r;return null}s(gf,"mapClientInfoNameToFamily");function As(e){let t;try{t=JSON.parse(e)}catch{return null}if(!$r(t)||t.method!=="initialize")return null;let n=t.params;if(!$r(n))return null;let r=n.clientInfo;if(!$r(r))return null;let i=r.name,o=gf(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(As,"tryExtractInitializeClient");function $r(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s($r,"isRecord");Gr();Wr();qe();var Mf="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")}},_n=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=Ff(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=Lf(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??Mf}async run(){let t=Of({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=As(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=Hf(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&&Ps(u)&&r.id!==null){let m=Ve(u,!0);process.stderr.write(`[maind] ${m}
273
273
  `);let h=r.params?.name;process.stdout.write(Be(r.id,typeof h=="string"?h:"unknown",m)+`
274
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 u=hn(t);if(this.serveInitializeFromCache(t,u))return;yn(u,-32603,`bridge network error: ${jf(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($f(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=Ff(d,i);u.trim().length>0&&process.stdout.write(u+`
279
- `);return}if(p.startsWith("text/event-stream"))await Mf(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(Hf(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 Uf(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 Df(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(Df,"normalizeClientFamily");function Of(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(Of,"normalizeClientVersion");async function Mf(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: ${Gf(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(Uf(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 Br(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 Br(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 Br(c):await c.text(),u=jf(d,i);u.trim().length>0&&process.stdout.write(u+`
279
+ `);return}if(p.startsWith("text/event-stream"))await $f(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(Wf(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 Kf(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&&Fs(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!gn(t))return!1;let r=Ls(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write($s(n,r)+`
281
+ `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${mn(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Ff(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(Ff,"normalizeClientFamily");function Lf(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(Lf,"normalizeClientVersion");async function $f(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 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(Mf,"pipeSseToStdout");function Ff(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(Ff,"appendNoteToToolResult");function Lf(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(Lf,"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(`
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($f,"pipeSseToStdout");function jf(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(jf,"appendNoteToToolResult");function Hf(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(Hf,"parseRpc");async function Br(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
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
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 $f(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($f,"isSessionLossBody");function jf(e){return e instanceof Error?e.message:String(e)}s(jf,"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 Hf(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(Hf,"extractHint");function Uf(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(Uf,"parsePresenceToolResult");B();B();import{spawn as Xf}from"node:child_process";import{platform as Qf}from"node:os";var Zf="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function em(){let e=process.env.MAIND_FUNCTIONS_ORIGIN;return e&&e.length>0?e.replace(/\/+$/,""):Zf}s(em,"functionsOrigin");async function ze(e,t=process.stderr){let n=em(),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 im(l.verification_uri_complete).catch(()=>{}),rm(l,t);let p=Date.now()+l.expires_in*1e3,d=Math.max(l.interval,3)*1e3;for(;Date.now()<p;){await nm(d);let u=await tm(i,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
287
+ `)}s(Br,"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 Uf(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(Uf,"isSessionLossBody");function Gf(e){return e instanceof Error?e.message:String(e)}s(Gf,"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 Wf(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(Wf,"extractHint");function Kf(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(Kf,"parsePresenceToolResult");B();B();import{spawn as em}from"node:child_process";import{platform as tm}from"node:os";var nm="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function rm(){let e=process.env.MAIND_FUNCTIONS_ORIGIN;return e&&e.length>0?e.replace(/\/+$/,""):nm}s(rm,"functionsOrigin");async function ze(e,t=process.stderr){let n=rm(),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 am(l.verification_uri_complete).catch(()=>{}),sm(l,t);let p=Date.now()+l.expires_in*1e3,d=Math.max(l.interval,3)*1e3;for(;Date.now()<p;){await om(d);let u=await im(i,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
290
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
291
  `),{apiKey:u.api_key,plan:u.plan};if(u.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
292
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 tm(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(tm,"pollOnce");function nm(e){return new Promise(t=>setTimeout(t,e))}s(nm,"sleep");function rm(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(`
294
+ `),null}s(ze,"runDeviceFlow");async function im(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(im,"pollOnce");function om(e){return new Promise(t=>setTimeout(t,e))}s(om,"sleep");function sm(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: ${Ws(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Ws(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(rm,"printAuthInstructions");function Us(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}s(Us,"pad");async function im(e){let t,n;switch(Qf()){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=Xf(t,n,{stdio:"ignore",detached:!0});o.on("error",i),o.unref(),r()}catch(o){i(o)}})}s(im,"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_
296
+ `)}s(sm,"printAuthInstructions");function Ws(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}s(Ws,"pad");async function am(e){let t,n;switch(tm()){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=em(t,n,{stdio:"ignore",detached:!0});o.on("error",i),o.unref(),r()}catch(o){i(o)}})}s(am,"openExternalBrowser");xe();ge();xe();import*as Ul from"node:os";function Ks(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(Ks,"parseInstallFlags");var Z=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function Bs(){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(Bs,"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
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 Ks from"node:fs/promises";import*as ye from"node:path";import*as Bs from"node:readline";var dm=["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 dm)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(`
303
+ `)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as Vs from"node:fs/promises";import*as ye from"node:path";import*as qs from"node:readline";var fm=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function zs(e){let t=ye.resolve(e),n=t;for(;;){if(await Ys(n))return n;let r=ye.dirname(n);if(r===n)return t;n=r}}s(zs,"detectProjectRoot");async function Js(e){let n=ye.resolve(e),r=[];for(;;){await Ys(n)&&r.push(n);let i=ye.dirname(n);if(i===n)break;n=i}return r}s(Js,"findAllProjectRoots");async function Ys(e){for(let t of fm)try{return await Vs.access(ye.join(e,t)),!0}catch{}return!1}s(Ys,"hasAnyMarker");async function Xs(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=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 mm(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(mm,"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:mm(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"&&ym(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 F(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 ym(e){return!("mcpServers"in e||!(Ct in e))}s(ym,"hasRootShape");function sa(e,t){if(!be(e)||e.command!==t.command||!bm(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 bm(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(bm,"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 _m,stringify as wm}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=_m(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)&&km(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=wm(u),f.endsWith(`
307
+ Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=qs.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(Xs,"disambiguateProjectRoot");Ye();import*as Y from"node:path";function ta(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(ta,"buildMaindServerEntry");function ym(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(ym,"claudeDesktopConfigPath");function na(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:ym(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(na,"getClientTargets");function ra(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}s(ra,"filterTargetsByFamily");function ia(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:ea(e.env.XDG_CONFIG_HOME),appData:ea(e.env.APPDATA)}}s(ia,"makeDefaultContext");function ea(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}s(ea,"nonEmpty");Ye();ce();var Ct="maind";async function la(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 Xr(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 Xr(e,"parse",d)}}if(!_e(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"&&wm(i),c,l=!1;if(a){let d=i[Ct];_e(d)&&ca(d,t)&&(l=!0),c={...i,[Ct]:aa(d,t)}}else{let d=_e(i.mcpServers)?i.mcpServers:{},u=d[Ct];_e(u)&&ca(u,t)&&(l=!0),c={...i,mcpServers:{...d,[Ct]:aa(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 Xr(e,"write",d)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(la,"mergeJsonConfig");function aa(e,t){let n=_e(e)&&_e(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(aa,"mergeEntry");function wm(e){return!("mcpServers"in e||!(Ct in e))}s(wm,"hasRootShape");function ca(e,t){if(!_e(e)||e.command!==t.command||!km(e.args,t.args)||!_e(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(ca,"serverEntriesEqual");function km(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(km,"arrayEquals");function _e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(_e,"isObject");function Xr(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(Xr,"failed");ce();import{parse as vm,stringify as Sm}from"smol-toml";async function da(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=vm(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)&&Em(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=Sm(u),f.endsWith(`
310
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 F(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 km(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(km,"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 vm="__STACK__";var Sm="__INTENT__";var Xr="https://mcp.maind.dev/mcp",Em=`?stack=${vm}&intent=${Sm}`;function xm(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(xm,"buildStackAwareEndpoint");var xS=xm(Xr,{stack:["nextjs","supabase"],intent:"mixed"}),Pt=`## maind MCP integration \u2014 Mandatory consultation
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(da,"mergeTomlConfig");function Em(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(Em,"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 xm="__STACK__";var Rm="__INTENT__";var Qr="https://mcp.maind.dev/mcp",Am=`?stack=${xm}&intent=${Rm}`;function Tm(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(Tm,"buildStackAwareEndpoint");var TS=Tm(Qr,{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 Rm(e){return`I want to add the **maind MCP server** to my AI coding agent.
380
+ Full tool set + provenance via \`get_conventions\`.`;function Im(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(Rm,"buildAiPromptBody");function Nt(e,t,n){let r=n?`
576
+ ${Pt}`}s(Im,"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 Am(e){return`#!/usr/bin/env bash
611
+ NODE`}s(Nt,"buildJsonConfigInstaller");function Cm(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(Am,"buildCodexTomlInstaller");function Tm(e=Xr){let t=`${e}${Em}`;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:Rm(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(Cm,"buildCodexTomlInstaller");function Nm(e=Qr){let t=`${e}${Am}`;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:Im(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:Am(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:Cm(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(Tm,"buildSnippetTemplates");var RS=Tm(Xr);ce();var Im="## maind MCP integration";function Cm(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(Cm,"buildPreambleTargets");async function la(e,t=!1){let n=Cm(e),r=[];for(let i of n)r.push(await Nm(i,t));return r}s(la,"writePreambleFiles");async function Nm(e,t){try{if(e.mayNeedParentDir&&!t&&await Jr(le.dirname(e.path)),await ra(e.path,Im))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
- `:Pm(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(Nm,"writeOnePreambleFile");function Pm(e){return e.endsWith(`
801
+ }`}]}s(Nm,"buildSnippetTemplates");var IS=Nm(Qr);ce();var Pm="## maind MCP integration";function Dm(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(Dm,"buildPreambleTargets");async function ua(e,t=!1){let n=Dm(e),r=[];for(let i of n)r.push(await Om(i,t));return r}s(ua,"writePreambleFiles");async function Om(e,t){try{if(e.mayNeedParentDir&&!t&&await Yr(le.dirname(e.path)),await oa(e.path,Pm))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
+ `:Mm(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(Om,"writeOnePreambleFile");function Mm(e){return e.endsWith(`
804
804
 
805
805
  `)?e:e.endsWith(`
806
806
  `)?e+`
807
807
  `:e+`
808
808
 
809
- `}s(Pm,"ensureTrailingBlankLine");oi();Xe();ce();import*as ga from"node:readline";var Ae="config:auto_working_paths",Km=`
809
+ `}s(Mm,"ensureTrailingBlankLine");si();Xe();ce();import*as _a from"node:readline";var Ae="config:auto_working_paths",qm=`
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 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??Bm)(e.out,Km)}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(ya,"applyWorkingPathsConsent");async function Bm(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(Bm,"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=Vm(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=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,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 Vm(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(Vm,"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 qm="https://vsddmiosisvfrairepxv.supabase.co/functions/v1",zm="/install-completed";async function va(e){if(!e.enabled||e.apiKey===null)return;let n=`${(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"")||qm}${zm}`,r={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:Ym(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:Jm(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 Jm(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(Jm,"countStatuses");function Ym(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}s(Ym,"parseNodeMajor");Xt();var dy="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.
818
+ [y/N]: `;async function ba(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??zm)(e.out,qm)}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(ba,"applyWorkingPathsConsent");async function zm(e,t){e.write(t);let n=_a.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(zm,"promptYesNoDefaultNo");B();async function wa(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(wa,"exchangeOneClickToken");async function Sa(e){let t="browser-pair";if(e.token!==null)try{let o=Jm(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:ka(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 wa({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:o.device_id,label:Gs(),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,va(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,va(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:ka(o)}}}}s(Sa,"pairOrUseToken");function Jm(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(Jm,"validateTokenShape");function ka(e){return e instanceof Error?e.message:String(e)}s(ka,"errMessage");function va(e){return e.out??process.stdout}s(va,"out");var Ym="https://vsddmiosisvfrairepxv.supabase.co/functions/v1",Xm="/install-completed";async function Ea(e){if(!e.enabled||e.apiKey===null)return;let n=`${(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"")||Ym}${Xm}`,r={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:Zm(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:Qm(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(Ea,"postInstallTelemetry");function Qm(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(Qm,"countStatuses");function Zm(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}s(Zm,"parseNodeMajor");Xt();var fy="https://mcp.maind.dev/mcp";async function Gl(e){let t=Date.now(),n;try{n=Ks(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 Bs(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,o=Ul.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 Js(process.cwd());if(w.length===0)a=await zs(process.cwd());else if(w.length===1)a=w[0];else{let v=await Xs(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()||dy;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()||fy;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 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(`
828
+ `);let p=await Sa({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
829
  pairing failed: ${p.result.detail??"unknown"}
830
830
  Skipping remaining steps.
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.
831
+ `),c.print(process.stdout),2;let d=ia({projectRoot:a,homeDir:o,platform:process.platform,env:process.env}),u=na(d);if(u=ra(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 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(`
833
+ `),c.print(process.stdout),2;for(let w of u){let v=ta({mcpUrl:l,clientFamily:w.clientFamilyEnv}),k;w.kind==="json"?k=await la(w,v,n.dryRun):k=await da(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 ua({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 ga(f));for(let w of await ya(f))c.add(w);c.add(await ba({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let m=Ml();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 Ea({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
- `);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}
837
+ `);let y=ee({entryPath:te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),_=y.fallbackReason===null?`${Je(y)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${_}
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(Hl,"runInstall");Xt();import{readFileSync as uy}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=uy(e,"utf8");return t.length>Gl?t.slice(0,Gl):t}catch{return""}}s(Wl,"readFileCapped");function py(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(py,"distinctFilePaths");function Kl(e,t,n,r){try{let i=dr(n);if(e==="codebase_search"){let o=py(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 Sy}from"node:crypto";function pr(e){return Sy("sha256").update(e,"utf8").digest("hex")}s(pr,"nodeKeyHash");var Ey=["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:Ey,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 L(e){return typeof e=="string"&&e.length>0?e:void 0}s(L,"str");var xy=10;function Ry(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>=xy&&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(Ry,"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=L(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:L(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=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=nd(L(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: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=nd(L(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:L(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=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=Ry(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: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: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(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 Ay="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function sd(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:Ay}s(sd,"functionsOrigin");var Ty="/mcp-client-metrics-ingest",Iy=4e3,Cy="codebase_search_tokens_saved";async function ad(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${sd()}${Ty}`,n=new AbortController,r=setTimeout(()=>n.abort(),Iy);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:Cy,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 u_}from"node:path";var p_="<synthetic>";function Zd(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:u_(qo,zo(e.cwd),`${e.transcript_stem}.jsonl`)}s(Zd,"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!==p_&&(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 f_}from"node:child_process";var m_=8,h_=32;function g_(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,h_)}s(g_,"parsePorcelain");function y_(e,t=m_){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(y_,"condenseToDirs");async function eu(e=b_){let t=await e();if(t===null)return null;let n=y_(g_(t));return n.length>0?n:null}s(eu,"deriveWorkingPaths");async function b_(){return await new Promise(e=>{f_("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(b_,"defaultGitStatus");var pv=1,fv=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function mv(e){return fv.includes(e)}s(mv,"isHookSubcommand");var hv=6e4;async function gv(){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(gv,"ensureApiKey");async function yv(){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(yv,"reauth");async function bv(){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(()=>(Bu(),Ku));process.exit(await y())}if(e==="guard"){let y=process.argv.indexOf("guard"),{runGuard:b}=await Promise.resolve().then(()=>(ep(),Zu));process.exit(await b(process.argv.slice(y+1)))}if(e==="guard-inject"){let{runGuardInject:y}=await Promise.resolve().then(()=>(sp(),op));process.exit(await y())}if(e==="guard-gate"){let{runGuardGate:y}=await Promise.resolve().then(()=>(up(),dp));process.exit(await y())}if(e==="guard-stop"){let{runGuardStop:y}=await Promise.resolve().then(()=>(mp(),fp));process.exit(await y())}if(e==="gateway"){let y=process.argv.indexOf("gateway"),{runGateway:b}=await Promise.resolve().then(()=>(Qp(),Xp));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&&mv(e)){let y=await Promise.resolve().then(()=>(rs(),Du)),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"))&&(_v(),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 gv(),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-${uv()}`,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()},hv):null;p?.unref();let d=null,u=new gr({projectKey:r}),f=new xr({resolvePath:s(()=>Zd(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(()=>eu(),"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<pv){g+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${b.message}; re-authorizing\u2026
846
- `),n=await yv();continue}throw b}}}finally{p&&clearInterval(p),h&&clearInterval(h),await m.end(),await l()}}s(bv,"main");function _v(){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(_v,"printHelp");bv().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
839
+ `),h}s(Gl,"runInstall");Xt();import{readFileSync as my}from"node:fs";import{join as Wl}from"node:path";function dr(e){return e?Math.ceil(e.length/4):0}s(dr,"estimateTokens");var Kl=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 Bl(e){try{let t=my(e,"utf8");return t.length>Kl?t.slice(0,Kl):t}catch{return""}}s(Bl,"readFileCapped");function hy(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(hy,"distinctFilePaths");function Vl(e,t,n,r){try{let i=dr(n);if(e==="codebase_search"){let o=hy(t);if(o.length===0)return 0;let a=0;for(let c of o)a+=dr(Bl(Wl(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(Bl(Wl(r,o)));return Math.max(0,a-i)}return 0}catch{return 0}}s(Vl,"measureLocalToolSaved");Qt();Xt();import{createHash as xy}from"node:crypto";function fr(e){return xy("sha256").update(e,"utf8").digest("hex")}s(fr,"nodeKeyHash");var Ry=["module","class","interface","function","method","type_alias","enum","variable"],Eo=[{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:Ry,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, a COMMIT on the shared base tree \u2014 one that a branch switch undone by a parallel session redirected there, which no success message reports and which `git push` would make worse, 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."}}}}],sd=new Set(Eo.map(e=>e.name));function $(e){return typeof e=="string"&&e.length>0?e:void 0}s($,"str");var Ay=10;function Ty(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>=Ay&&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(Ty,"aggregateHistoryContext");function Me(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Me,"num");function id(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(id,"anchorRepo");function od(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(od,"dirNotFound");async function ad(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=$l(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"),_=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:_.length,findings:y,preexisting:_.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=id($(n.dir));if(r===null)return od("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=id($(n.dir));if(r===null)return od("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=So(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:fr(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:fr(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:fr(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=Ty(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:rd,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:fr(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(ad,"dispatchLocalTool");var mr=class{constructor(t=Hl,n=null,r=z){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Eo}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&sd.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 ad(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=Fl(a)?`${Ll} (${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=Vl(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};var Iy="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function cd(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:Iy}s(cd,"functionsOrigin");var Cy="/mcp-client-metrics-ingest",Ny=4e3,Py="codebase_search_tokens_saved";async function ld(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${cd()}${Cy}`,n=new AbortController,r=setTimeout(()=>n.abort(),Ny);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:Py,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(ld,"postSavingsMetric");Ao();gr();_r();_t();import{join as mb}from"node:path";var hb="<synthetic>";function nu(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:mb(Jo,Yo(e.cwd),`${e.transcript_stem}.jsonl`)}s(nu,"transcriptPathFromSideChannel");var Rr=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??zo)(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!==hb&&(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 gb}from"node:child_process";var yb=8,_b=32;function bb(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,_b)}s(bb,"parsePorcelain");function wb(e,t=yb){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(wb,"condenseToDirs");async function ru(e=kb){let t=await e();if(t===null)return null;let n=wb(bb(t));return n.length>0?n:null}s(ru,"deriveWorkingPaths");async function kb(){return await new Promise(e=>{gb("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(kb,"defaultGitStatus");var hv=1,gv=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function yv(e){return gv.includes(e)}s(yv,"isHookSubcommand");var _v=6e4;async function bv(){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(bv,"ensureApiKey");async function wv(){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(wv,"reauth");async function kv(){let e=process.argv.slice(2).find(y=>!y.startsWith("-"));if(e==="install"){let y=process.argv.indexOf("install"),_=process.argv.slice(y+1),w=await Gl(_);process.exit(w)}if(e==="on-session-end"){let{runOnSessionEnd:y}=await Promise.resolve().then(()=>(zu(),qu));process.exit(await y())}if(e==="guard"){let y=process.argv.indexOf("guard"),{runGuard:_}=await Promise.resolve().then(()=>(rp(),np));process.exit(await _(process.argv.slice(y+1)))}if(e==="guard-inject"){let{runGuardInject:y}=await Promise.resolve().then(()=>(lp(),cp));process.exit(await y())}if(e==="guard-gate"){let{runGuardGate:y}=await Promise.resolve().then(()=>(mp(),fp));process.exit(await y())}if(e==="guard-stop"){let{runGuardStop:y}=await Promise.resolve().then(()=>(yp(),gp));process.exit(await y())}if(e==="gateway"){let y=process.argv.indexOf("gateway"),{runGateway:_}=await Promise.resolve().then(()=>(tf(),ef));process.exit(await _(process.argv.slice(y+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:y}=await Promise.resolve().then(()=>(ks(),ws));process.exit(await y())}if(e==="guard-cross-check"){let{runGuardCrossCheck:y}=await Promise.resolve().then(()=>(ks(),ws));process.exit(await y())}if(e==="on-index-refresh"){let{runOnIndexRefresh:y}=await Promise.resolve().then(()=>(Es(),Ss));process.exit(await y())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:y}=await Promise.resolve().then(()=>(Es(),Ss));process.exit(await y())}if(e!==void 0&&yv(e)){let y=await Promise.resolve().then(()=>(os(),Fu)),_={"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 _())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(P+`
844
+ `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(vv(),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 bv(),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 mr(void 0,o),c=`bridge-${mv()}`,l=s(async()=>{if(!o)return;let y=o.takePending();y.tokens<=0||await ld({apiKey:n,deviceId:t,sessionId:c,tokensSaved:y.tokens,bridgeVersion:P})},"flushSavings"),p=o?setInterval(()=>{l()},_v):null;p?.unref();let d=null,u=new yr({projectKey:r}),f=new Rr({resolvePath:s(()=>nu(u.sideChannel()),"resolvePath"),fallbackModel:s(()=>u.sideChannel()?.model??null,"fallbackModel")}),m=new hr({projectKey:r,identity:u,sessionMeta:s(()=>f.read(),"sessionMeta"),postToolCall:s((y,_)=>d===null?Promise.reject(new Error("presence: no active forwarder")):d.postPresenceToolCall(y,_),"postToolCall"),deriveWorkingPaths:s(()=>ru(),"deriveWorkingPaths"),snapshot:r!==null?kd({projectKey:r}):void 0}),h=m.isEnabled?setInterval(()=>{m.pollActivity()},pd):null;if(h?.unref(),m.isEnabled){let y=s(_=>{m.end().finally(()=>process.exit(_))},"endAndExit");process.on("SIGTERM",()=>y(143)),process.on("SIGINT",()=>y(130))}let g=0;try{for(;;){let y=new _n({apiKey:n,deviceId:t,bridgeVersion:P,projectKey:r,localRouter:a,presence:m});d=y;try{await y.run();return}catch(_){if(_ instanceof At&&g<hv){g+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${_.message}; re-authorizing\u2026
846
+ `),n=await wv();continue}throw _}}}finally{p&&clearInterval(p),h&&clearInterval(h),await m.end(),await l()}}s(kv,"main");function vv(){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(vv,"printHelp");kv().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
848
848
  `),process.exit(1)});