@maind-dev/mcp-bridge 0.56.0 → 0.58.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 +176 -176
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -1,32 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Yo=Object.defineProperty;var s=(e,t)=>Yo(e,"name",{value:t,configurable:!0});var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var W=(e,t)=>{for(var n in t)Yo(e,n,{get:t[n],enumerable:!0})};function Qo(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 Ue(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 Rr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Ar(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function Tr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Ir=w(()=>{"use strict";s(Qo,"parseFrame");s(Ue,"denyResult");s(Rr,"toolEvent");s(Ar,"policyEvent");s(Tr,"shaEvent")});import{execFileSync as es}from"node:child_process";function ts(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=bp}function wp(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 hp){let a=r[o];typeof a=="string"&&gp.test(a)&&i.push({field:o,sha:a})}return i}function _p(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,Zo);for(let i=Zo;i>=yp;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 Ge(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 nn(e=process.cwd()){try{let n=es("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 kp(e){return t=>{try{let r=es("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 rn(e,t){if(t===null)return[];let n=wp(e);if(n.length===0)return[];let r=kp(t),i=[];for(let{field:o,sha:a}of n){let c=_p(a,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var hp,gp,yp,Zo,bp,Nr=w(()=>{"use strict";hp=["commit_sha","base_sha","head_sha"],gp=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,yp=7,Zo=12,bp=10;s(ts,"isDenyGrade");s(wp,"extractShaArgs");s(_p,"classifySha");s(Ge,"shaFindingText");s(ns,"cleanGitEnv");s(nn,"resolveRepoRootForSha");s(kp,"gitShaResolver");s(rn,"inspectLineForShas")});import{execFileSync as vp}from"node:child_process";import{createHash as Sp}from"node:crypto";import{mkdirSync as Ep,readFileSync as xp,renameSync as Rp,writeFileSync as Ap}from"node:fs";import{dirname as Tp,join as rs}from"node:path";function se(e=process.cwd()){try{let t=vp("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 on(e){return Sp("sha256").update(e).digest("hex").slice(0,16)}function sn(e){return rs(e,Ip)}function is(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function os(e,t,n,r=new Date().toISOString()){try{if(!is(n))return;let i={version:Cr,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},o=sn(e);Ep(Tp(o),{recursive:!0});let a=`${o}.${process.pid}.tmp`;Ap(a,JSON.stringify(i,null,2),"utf8"),Rp(a,o)}catch{}}function ss(e,t){try{let n=xp(sn(e),"utf8"),r=JSON.parse(n);return r.version!==Cr||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!is(r.result)?null:{version:Cr,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function as(e,t,n=new Date){let r=Np(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
|
|
5
|
-
`,{encoding:"utf8",mode:384});try{
|
|
6
|
-
`,{encoding:"utf8",mode:384});try{Mo(n,384)}catch{}}function C(){let e=Er();if(!on(e))return null;let t=Oo(e,"utf8").trim();return t.length>0?t:null}function yt(){let e=Er();on(e)&&Sr(e,"",{encoding:"utf8",mode:384})}function $o(){try{return`mcp-bridge-${yp()}`}catch{return"mcp-bridge"}}function sn(e){return{os:`${vr()} ${wp()}`,ide:"mcp-bridge",ext_version:e,device_id:j()}}var _p,kp,vp,K=b(()=>{"use strict";s(gt,"configDir");s(Fo,"ensureDir");_p="device-id",kp="api-key";s(j,"ensureDeviceId");vp=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(Sp,"isUuid");s(Er,"apiKeyPath");s(ve,"writeApiKey");s(C,"readApiKey");s(yt,"clearApiKey");s($o,"bridgeLabel");s(sn,"clientMeta")});var P,Se=b(()=>{"use strict";P="0.56.0"});import{execFileSync as Pp}from"node:child_process";import{createHash as Dp}from"node:crypto";function Op(e){return Dp("sha256").update(e).digest("hex")}function Mp(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 Fp(e){let t=Mp(e);return t?Op(t):null}function F(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&$p.test(e))return e;let t;try{t=Pp("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Fp(t):null}var $p,fe=b(()=>{"use strict";s(Op,"sha256Hex");s(Mp,"normalizeRemoteUrl");s(Fp,"projectKeyFromRemote");$p=/^[a-f0-9]{64}$/;s(F,"computeProjectKey")});import jp from"node:path";import{fileURLToPath as Hp}from"node:url";function Up(e,t=jp.sep){return e.split(t).includes("_npx")}function Q(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",Jo,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):Up(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 Z(){try{let e=Hp(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Ue(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${qo(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:qo(n)).join(" ")}function cn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Jo)}function ln(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function qo(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Jo,Ke=b(()=>{"use strict";Jo="@maind-dev/mcp-bridge";s(Up,"isEphemeralEntry");s(Q,"resolveBridgeLaunch");s(Z,"currentBridgeEntry");s(Ue,"launchToShellCommand");s(cn,"isNpxForm");s(ln,"isLegacyHookForm");s(qo,"shellQuote")});import*as D from"node:fs/promises";import*as dn from"node:path";async function H(e){try{return await D.readFile(e,"utf8")}catch(t){if(Gp(t))return null;throw t}}async function xr(e){await D.mkdir(e,{recursive:!0})}async function O(e,t,n){let r=dn.dirname(e);await xr(r);let i=dn.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await D.writeFile(i,t,{encoding:"utf8",mode:n});try{await D.rename(i,e)}catch(o){if(Bp(o))try{await D.copyFile(i,e),await D.unlink(i).catch(()=>{}),n!==void 0&&await D.chmod(e,n).catch(()=>{});return}catch(a){throw await D.unlink(i).catch(()=>{}),a}throw await D.unlink(i).catch(()=>{}),o}}async function es(e,t){let n=await H(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function Gp(e){return ts(e)&&e.code==="ENOENT"}function Bp(e){return!ts(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function ts(e){return typeof e=="object"&&e!==null&&"code"in e}var se=b(()=>{"use strict";s(H,"readFileSafe");s(xr,"ensureDir");s(O,"atomicWriteFile");s(es,"hasLinePrefix");s(Gp,"isNoEnt");s(Bp,"isWindowsRenameFailure");s(ts,"isNodeError")});import{existsSync as cf}from"node:fs";import*as as from"node:path";function kt(e,t={},n=Ir){let r=t.fileExists??cf,i=t.expectedCommand??lf,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Ar(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},d=df(o,a.event,a.subcommand);if(d===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let u=` Replace its command with: ${i(a.subcommand)}`;if(ln(d))return{...c,status:"legacy",command:d,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+u};if(cn(d))return{...c,status:"npx",command:d,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+u};let l=uf(d);return l!==null&&!r(l)?{...c,status:"broken",command:d,remedy:"edit-command",detail:`${a.label} points at ${l}, which does not exist \u2014 the hook fails silently on every run.`+u}:{...c,status:"ok",command:d,remedy:"none",detail:`${a.label} is wired.`}})}function Nr(e){return e.some(t=>t.status!=="ok")}function fn(e){return e.some(t=>t.remedy==="run-install")}function lf(e){return Ue(Q({entryPath:Z(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function df(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Ar(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Ar(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function uf(e){for(let t of pf(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return as.isAbsolute(t)?t:null;return null}function pf(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 Ar(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ir,pn,vt=b(()=>{"use strict";Ke();Ir=[{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."}],pn=[{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(kt,"inspectHookWiring");s(Nr,"hasWiringDrift");s(fn,"needsInstallRun");s(lf,"defaultExpectedCommand");s(df,"findCommand");s(uf,"extractScriptPath");s(pf,"tokenize");s(Ar,"isObject")});import*as Dr from"node:path";import*as ls from"node:readline";async function ds(e,t){let n=Dr.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 H(n)}catch(f){return{target:r,action:"merge",status:"failed",detail:`read: ${Cr(f)}`}}let o,a="create";if(i===null||i.trim().length===0)o={};else{a="merge";try{let f=JSON.parse(i);if(!Pr(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: ${Cr(f)}`}}}let c=mf(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 hf(e.out,`
|
|
4
|
+
${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:o})}function Np(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${Cp(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function Cp(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 Cr,Ip,Ke=w(()=>{"use strict";Cr=1,Ip=rs(".maind","conventions-cache.json");s(se,"resolveRepoRoot");s(on,"keyFingerprint");s(sn,"cachePath");s(is,"hasInstructions");s(os,"writeConventionsCache");s(ss,"readConventionsCache");s(as,"buildCachedInitializeResponse");s(Np,"fallbackMarker");s(Cp,"relativeAge")});import{existsSync as un,mkdirSync as Kp,readFileSync as cs,writeFileSync as Or,chmodSync as ls}from"node:fs";import{homedir as Bp,hostname as Wp,platform as Dr,release as Vp}from"node:os";import{randomUUID as qp}from"node:crypto";import{join as ve}from"node:path";function vt(){let e=Bp(),t=process.env;if(Dr()==="darwin")return ve(e,"Library","Application Support","maind");if(Dr()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:ve(e,"AppData","Roaming");return ve(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:ve(e,".config");return ve(n,"maind")}function ds(e){un(e)||Kp(e,{recursive:!0,mode:448})}function j(){let e=vt();ds(e);let t=ve(e,Jp);if(un(t)){let r=cs(t,"utf8").trim();if(Xp(r))return r}let n=qp();Or(t,n+`
|
|
5
|
+
`,{encoding:"utf8",mode:384});try{ls(t,384)}catch{}return n}function Xp(e){return Yp.test(e)}function Mr(){return ve(vt(),zp)}function Se(e){let t=vt();ds(t);let n=Mr();Or(n,e+`
|
|
6
|
+
`,{encoding:"utf8",mode:384});try{ls(n,384)}catch{}}function C(){let e=Mr();if(!un(e))return null;let t=cs(e,"utf8").trim();return t.length>0?t:null}function St(){let e=Mr();un(e)&&Or(e,"",{encoding:"utf8",mode:384})}function us(){try{return`mcp-bridge-${Wp()}`}catch{return"mcp-bridge"}}function pn(e){return{os:`${Dr()} ${Vp()}`,ide:"mcp-bridge",ext_version:e,device_id:j()}}var Jp,zp,Yp,K=w(()=>{"use strict";s(vt,"configDir");s(ds,"ensureDir");Jp="device-id",zp="api-key";s(j,"ensureDeviceId");Yp=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(Xp,"isUuid");s(Mr,"apiKeyPath");s(Se,"writeApiKey");s(C,"readApiKey");s(St,"clearApiKey");s(us,"bridgeLabel");s(pn,"clientMeta")});var P,Ee=w(()=>{"use strict";P="0.58.0"});import{execFileSync as af}from"node:child_process";import{createHash as cf}from"node:crypto";function lf(e){return cf("sha256").update(e).digest("hex")}function df(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 uf(e){let t=df(e);return t?lf(t):null}function L(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&pf.test(e))return e;let t;try{t=af("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?uf(t):null}var pf,me=w(()=>{"use strict";s(lf,"sha256Hex");s(df,"normalizeRemoteUrl");s(uf,"projectKeyFromRemote");pf=/^[a-f0-9]{64}$/;s(L,"computeProjectKey")});import mf from"node:path";import{fileURLToPath as hf}from"node:url";function gf(e,t=mf.sep){return e.split(t).includes("_npx")}function Z(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",vs,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):gf(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 ee(){try{let e=hf(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function We(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${ks(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:ks(n)).join(" ")}function mn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(vs)}function hn(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function ks(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var vs,Ve=w(()=>{"use strict";vs="@maind-dev/mcp-bridge";s(gf,"isEphemeralEntry");s(Z,"resolveBridgeLaunch");s(ee,"currentBridgeEntry");s(We,"launchToShellCommand");s(mn,"isNpxForm");s(hn,"isLegacyHookForm");s(ks,"shellQuote")});import*as D from"node:fs/promises";import*as gn from"node:path";async function H(e){try{return await D.readFile(e,"utf8")}catch(t){if(bf(t))return null;throw t}}async function Fr(e){await D.mkdir(e,{recursive:!0})}async function O(e,t,n){let r=gn.dirname(e);await Fr(r);let i=gn.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await D.writeFile(i,t,{encoding:"utf8",mode:n});try{await D.rename(i,e)}catch(o){if(wf(o))try{await D.copyFile(i,e),await D.unlink(i).catch(()=>{}),n!==void 0&&await D.chmod(e,n).catch(()=>{});return}catch(a){throw await D.unlink(i).catch(()=>{}),a}throw await D.unlink(i).catch(()=>{}),o}}async function Ts(e,t){let n=await H(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function bf(e){return Is(e)&&e.code==="ENOENT"}function wf(e){return!Is(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function Is(e){return typeof e=="object"&&e!==null&&"code"in e}var ae=w(()=>{"use strict";s(H,"readFileSafe");s(Fr,"ensureDir");s(O,"atomicWriteFile");s(Ts,"hasLinePrefix");s(bf,"isNoEnt");s(wf,"isWindowsRenameFailure");s(Is,"isNodeError")});import{existsSync as Ff}from"node:fs";import*as Ms from"node:path";function At(e,t={},n=Hr){let r=t.fileExists??Ff,i=t.expectedCommand??Lf,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);jr(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=$f(o,a.event,a.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let u=` Replace its command with: ${i(a.subcommand)}`;if(hn(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+u};if(mn(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+u};let d=jf(l);return d!==null&&!r(d)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${d}, which does not exist \u2014 the hook fails silently on every run.`+u}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function Ur(e){return e.some(t=>t.status!=="ok")}function wn(e){return e.some(t=>t.remedy==="run-install")}function Lf(e){return We(Z({entryPath:ee(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function $f(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!jr(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!jr(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function jf(e){for(let t of Hf(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Ms.isAbsolute(t)?t:null;return null}function Hf(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 jr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Hr,bn,Tt=w(()=>{"use strict";Ve();Hr=[{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."}],bn=[{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(At,"inspectHookWiring");s(Ur,"hasWiringDrift");s(wn,"needsInstallRun");s(Lf,"defaultExpectedCommand");s($f,"findCommand");s(jf,"extractScriptPath");s(Hf,"tokenize");s(jr,"isObject")});import*as Br from"node:path";import*as Ls from"node:readline";async function $s(e,t){let n=Br.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 H(n)}catch(f){return{target:r,action:"merge",status:"failed",detail:`read: ${Gr(f)}`}}let o,a="create";if(i===null||i.trim().length===0)o={};else{a="merge";try{let f=JSON.parse(i);if(!Kr(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: ${Gr(f)}`}}}let c=Gf(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 Kf(e.out,`
|
|
7
7
|
Merge a ${t.event} hook into ${n}?
|
|
8
8
|
${t.consentDescription}
|
|
9
|
-
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let
|
|
10
|
-
`;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:n};try{await O(n,p,384)}catch(f){return{target:r,action:"merge",status:"failed",detail:`write: ${
|
|
11
|
-
`,1)[0]??"").trim().slice(0,200)}function
|
|
12
|
-
`).slice(0,1e3)}var
|
|
13
|
-
`));let n=[];return
|
|
14
|
-
`)){if(!c.trim())continue;let
|
|
15
|
-
`)){if(
|
|
16
|
-
`)){if(u.length<4||u[0]!=="?")continue;let
|
|
17
|
-
`)){if(
|
|
18
|
-
`),w=aa(g[0]??"");if(!w)continue;let y=g.slice(1).filter(k=>k.trim().length>0).length;h.push({sha:w.sha,dateIso:w.dateIso,authorName:w.authorName,subject:w.subject,filesTouched:y})}u={sinceInput:n.since,sinceResolved:l,commits:h.slice(0,In),truncated:h.length>In}}return{history:d,regression:u,ownershipWindowCommits:o,pathsTruncated:a.length>Kr}}var om,sm,ca,Kr,In,oa,Gr=b(()=>{"use strict";J();om="",sm="\0",ca=200,Kr=50,In=100,oa="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";s(am,"clamp");s(sa,"splitRecords");s(aa,"parseHistoryRecord");s(cm,"aggregateOwnership");s(la,"readFileHistory")});import{execFileSync as lm}from"node:child_process";import{readdirSync as dm,statSync as da}from"node:fs";import{isAbsolute as um,join as Br,relative as pm,resolve as fm}from"node:path";function hm(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function gm(e,t){try{let n=lm("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 ym(e){let t;try{t=dm(e)}catch{return null}for(let n of t.filter(hm))try{let r=da(Br(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function wm(e){try{return da(e).isDirectory()}catch{return!1}}function bm(e,t){let n=pm(e,t);return!n||n.startsWith("..")?t:n}function Wr(e){let t=mm.filter(c=>wm(Br(e,c))),n=gm(e,"core.hooksPath"),r=n?um(n)?n:fm(e,n):Br(e,".git","hooks"),i=bm(e,r),o=ym(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 Vr(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 mm,qr=b(()=>{"use strict";mm=[".githooks",".husky"];s(hm,"isRealHook");s(gm,"gitConfig");s(ym,"hasExecutableHook");s(wm,"isDir");s(bm,"displayPath");s(Wr,"resolveHookState");s(Vr,"describeHookState")});import{posix as ua}from"node:path";function Ve(e){let t=_m.exec(e);return t?t[1]:null}function le(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Te(e,t){let n=_(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=ua.basename(o),c=Ve(a);if(c===null)continue;let d=ua.dirname(o),u=i.get(d)??[];u.push({path:o,name:a,version:c}),i.set(d,u)}return[...i.entries()].map(([o,a])=>({dir:o,files:a.sort((c,d)=>le(c.version,d.version))})).sort((o,a)=>o.dir.localeCompare(a.dir))}function pa(e){let t=_(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(_(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var _m,Rt=b(()=>{"use strict";J();_m=/^(\d+)_.+\.sql$/;s(Ve,"parseMigrationVersion");s(le,"compareVersions");s(Te,"discoverSupabaseProjects");s(pa,"resolveDefaultBranch")});import{execFileSync as km}from"node:child_process";import{existsSync as $,readFileSync as ye,readdirSync as Nn,statSync as zr}from"node:fs";import{posix as x}from"node:path";function xm(e,t){let n=(()=>{let i=_(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($(x.join(r,".git"))){let o=(()=>{let c=_(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&o!=null&&Xr(n,o))){let c=Rm(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=x.dirname(r)}return null}function Rm(e,t){let n=[];for(let r of Sm){let i;try{i=Nn(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),d=x.join(t,a);try{let u=zr(c),l=zr(d);if(!l.isFile())continue;if(u.size!==l.size){n.push(a);continue}if(u.size>Em)continue;ye(c).equals(ye(d))||n.push(a)}catch{continue}}}return n.sort()}function ba(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 ${Qr}.`})}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,d=c.slice(0,3).join(", "),u=c.length>3?` (+${c.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${a} ships ${d}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${c[0]}\` from this repo root), not via a path into ${a}.`})}if(e.stalePackageBuilds.length>0){let a=e.stalePackageBuilds,c=s(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),d=a.every(u=>u.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:a.some(u=>u.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${a.map(c).join(", ")}: src/ is newer than the built ${[...new Set(a.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${d}`,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=Tm(e.hooks);return o&&t.push(o),Am(t)}function Tm(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:Vr(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 Am(e){return[...e].sort((t,n)=>fa[t.status]-fa[n.status]||t.id.localeCompare(n.id))}function _a(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function de(e){let t=e?.trim();return t||null}function Im(e){let t=de(_(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(_(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Nm(e){let t=de(_(e,["rev-parse","--git-dir"]));if(!t)return null;let n=x.isAbsolute(t)?t:x.join(e,t);return $(x.join(n,"rebase-merge"))||$(x.join(n,"rebase-apply"))?"rebase":$(x.join(n,"MERGE_HEAD"))?"merge":$(x.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function Cm(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
|
|
20
|
-
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function
|
|
21
|
-
`).filter(
|
|
22
|
-
`).map(N=>N.trim()).filter(N=>N.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:
|
|
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($(r)){let i=JSON.parse(
|
|
24
|
-
`).filter(Boolean):[]}function
|
|
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
|
|
26
|
-
`:i==="r"?"\r":i==="t"?" ":i)}function
|
|
27
|
-
specification: ${m.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let u of n)c.has(u.key)||o("extra","warn",u.key,`${u.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let u of new Set([...a.keys(),...c.keys()])){if(
|
|
28
|
-
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:
|
|
29
|
-
|
|
9
|
+
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},u=o.hooks?.[t.event]??[],d={...o,hooks:{...o.hooks??{},[t.event]:[...u,l]}},p=JSON.stringify(d,null,2)+`
|
|
10
|
+
`;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:n};try{await O(n,p,384)}catch(f){return{target:r,action:"merge",status:"failed",detail:`write: ${Gr(f)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function js(e){let t=Br.join(e.homeDir,Fs);return $s(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 ${Fs} into every new Claude Code session.`})}function Uf(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function Wr(e,t){let n=e.launch??Z({entryPath:ee(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=We(n);return $s(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:Uf(t),skipDetail:s(i=>{let o=`${t.label} already runs maind ${t.subcommand}`;return hn(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}`:mn(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 Hs(e){let t=[];for(let n of Hr)t.push(await Wr(e,n));return t}function Gf(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Kr(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Kr(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function Kf(e,t){e.write(t);let n=Ls.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 Kr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gr(e){return e instanceof Error?e.message:String(e)}var Fs,Vr=w(()=>{"use strict";ae();Ve();Tt();Fs=".claude/maind-session-start-reminder.md";s($s,"mergeClaudeHook");s(js,"mergeSessionStartHook");s(Uf,"targetKeyFor");s(Wr,"mergeSubcommandHook");s(Hs,"mergeAllSubcommandHooks");s(Gf,"findExistingHookCommand");s(Kf,"promptYesNo");s(Kr,"isObject");s(Gr,"errMessage")});import{existsSync as Bf,readFileSync as Wf}from"node:fs";import{join as Vf}from"node:path";function le(){return Vf(vt(),"config.json")}function te(){try{let e=le();if(!Bf(e))return null;let t=JSON.parse(Wf(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 qe=w(()=>{"use strict";K();s(le,"bridgeConfigPath");s(te,"readBridgeConfig")});import{execFileSync as em}from"node:child_process";import{createHash as tm}from"node:crypto";function qr(e){return tm("sha256").update(e).digest("hex")}function nm(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function rm(e){let t=nm(e);return t?qr(t):null}function om(e){return typeof e=="string"&&im.test(e)}function Js(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(om(t))return t;let n;try{n=em("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?rm(n):null}var im,Jr=w(()=>{"use strict";s(qr,"sha256Hex");s(nm,"normalizeRemoteUrl");s(rm,"projectKeyFromRemote");im=/^[a-f0-9]{64}$/;s(om,"isProjectKey");s(Js,"computeProjectKey")});function _n(e){return`${e}#<module>`}function kn(e,t,n){return`${e}#${t}:${n}`}var It=w(()=>{"use strict";s(_n,"moduleKey");s(kn,"symbolKey")});function vn(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 zr(e){return e.toLowerCase().endsWith(".d.ts")}var Sn=w(()=>{"use strict";s(vn,"languageForPath");s(zr,"isSkippablePath")});function En(){return{nodes:[],edges:[],refs:[],imports:[]}}function ye(e){return e+1}function xn(e){return(e.text.split(`
|
|
11
|
+
`,1)[0]??"").trim().slice(0,200)}function sm(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 am(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=sm(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Je(e,t,n,r){for(let i of am(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}var Rn=w(()=>{"use strict";s(En,"newResult");s(ye,"line1");s(xn,"signatureOf");s(sm,"calleeName");s(am,"collectCallTargets");s(Je,"addCallRefs")});function Ys(e,t){let n=En();for(let r of e.namedChildren)cm(r,t,n);return n}function Xs(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function cm(e,t,n){let r=Xs(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??dm(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=An(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&&Je(n,o.nodeKey,a,zs);return}case"class_definition":lm(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=An(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 lm(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=An(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=Xs(c);if(l.type!=="function_definition")continue;let u=l.childForFieldName("name")?.text;if(!u)continue;let d=`${r}.${u}`,p=An(l,t,u,d,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=l.childForFieldName("body");f&&Je(n,p.nodeKey,f,zs)}}function An(e,t,n,r,i){return{nodeKey:kn(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:ye(e.startPosition.row),endLine:ye(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:xn(e),doc:null}}function dm(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var zs,Qs=w(()=>{"use strict";It();Rn();zs="call";s(Ys,"extractPython");s(Xs,"unwrapDecorated");s(cm,"handleTopLevel");s(lm,"addClass");s(An,"makeNode");s(dm,"firstDottedName")});function ta(e,t){let n=En();for(let r of e.namedChildren)pm(r,t,n);return n}function um(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function pm(e,t,n){let r=um(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:mm(i)});return}case"function_declaration":case"generator_function_declaration":{Zs(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{fm(r,t,n);return}case"interface_declaration":Yr(r,t,n,"interface");return;case"type_alias_declaration":Yr(r,t,n,"type_alias");return;case"enum_declaration":Yr(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";Zs(i,t,n,c?"function":"variable",o,a)}return}default:return}}function Zs(e,t,n,r,i,o){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=Tn(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let u=o??e.childForFieldName("body")??e;r==="function"&&u&&Je(n,l.nodeKey,u,ea)}function Yr(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=Tn(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}function fm(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Tn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let a of e.descendantsOfType("class_heritage"))for(let c of a.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let u of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text});for(let u of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text})}let o=e.childForFieldName("body");if(o)for(let a of o.namedChildren){if(a.type!=="method_definition")continue;let c=a.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,u=Tn(a,t,c,l,"method");n.nodes.push(u),n.edges.push({srcKey:i.nodeKey,dstKey:u.nodeKey,kind:"contains"});let d=a.childForFieldName("body");d&&Je(n,u.nodeKey,d,ea)}}function Tn(e,t,n,r,i){return{nodeKey:kn(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:ye(e.startPosition.row),endLine:ye(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:xn(e),doc:null}}function mm(e){return e.replace(/^["'`]|["'`]$/g,"")}var ea,na=w(()=>{"use strict";It();Rn();ea="call_expression";s(ta,"extractTypescript");s(um,"unwrapExport");s(pm,"handleTopLevel");s(Zs,"addFunctionLike");s(Yr,"addSimpleNamed");s(fm,"addClass");s(Tn,"makeNode");s(mm,"stripQuotes")});import{createRequire as hm}from"node:module";import{join as gm}from"node:path";function oa(e,t){return t?gm(t,ra[e]):hm(import.meta.url).resolve(`tree-sitter-wasms/out/${ra[e]}`)}var ra,ia,sa=w(()=>{"use strict";ra={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},ia="tree-sitter.wasm";s(oa,"grammarPath")});import{join as ym}from"node:path";import Xr from"web-tree-sitter";var bm,In,aa=w(()=>{"use strict";It();Sn();Qs();na();Rn();sa();bm=["typescript","tsx","javascript","python"],In=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await Xr.init(this.assetDir?{locateFile:s(t=>ym(this.assetDir,t||ia),"locateFile")}:void 0),this.parser=new Xr,this.initialized=!0)}supports(t){return bm.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=_n(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:ye(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:c},d=r==="python"?Ys(a,u):ta(a,u);return o.delete(),{filePath:t,language:r,nodes:[l,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await Xr.Language.load(oa(t,this.assetDir)),this.grammars.set(t,n)),n}}});function ca(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
|
|
12
|
+
`).slice(0,1e3)}var la=w(()=>{"use strict";s(ca,"nodeEmbedText")});var Qr,Zr=w(()=>{"use strict";Qr=["function","method","class","interface","enum","type_alias"]});function da(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 ua=w(()=>{"use strict";s(da,"cosineSimilarity")});import{posix as ei}from"node:path";function pa(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!wm.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 fa(e,t){let n=new Set,r=[],i=new Set,o=s((a,c,l)=>{if(a===c)return;let u=`${a}\0${c}\0${l}`;n.has(u)||(n.add(u),r.push({srcKey:a,dstKey:c,kind:l}),i.add(a))},"push");for(let a of e.edges)o(a.srcKey,a.dstKey,a.kind);for(let a of e.nodes)i.add(a.nodeKey);for(let a of e.refs){let c=t.nameToKeys.get(a.targetName);!c||c.length!==1||o(a.fromKey,c[0],a.kind)}for(let a of e.imports){let c=_m(e.filePath,a.specifier,t.files);c&&o(a.fromModuleKey,_n(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}function _m(e,t,n){if(!t.startsWith("."))return null;let r=ei.normalize(ei.join(ei.dirname(e),t)),i=[],o=Nn.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 Nn)i.push(c+l)}if(!o){for(let c of Nn)i.push(r+c);for(let c of Nn)i.push(`${r}/index${c}`)}for(let c of i)if(n.has(c))return c;return null}var wm,Nn,ma=w(()=>{"use strict";It();wm=new Set(["function","method","class","interface","enum","type_alias"]),Nn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];s(pa,"buildResolutionIndex");s(fa,"resolveFileEdges");s(_m,"resolveImportTarget")});import{execFileSync as km}from"node:child_process";import{createHash as vm}from"node:crypto";import{readdirSync as Sm,statSync as Em}from"node:fs";import{posix as ba,sep as ha}from"node:path";function k(e,t){try{return km("git",[...xm,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function Rm(e){return ha==="/"?e:e.split(ha).join("/")}function Cn(e){let t=[];for(let n of e){let r=Rm(n).trim();if(!r||zr(r))continue;let i=vn(r);i&&t.push({path:r,language:i})}return t}function wa(e){return Cn(e)}function _a(e){let t=ze(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Cn(t.split(`
|
|
13
|
+
`));let n=[];return ka(e,"",n),Cn(n)}function ka(e,t,n){let r;try{r=Sm(ba.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&ga.has(i.name)||ga.has(i.name))continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?ka(e,o,n):i.isFile()&&n.push(o)}}function ti(e,t){let r=k(e,["merge-base",t,"HEAD"])?.trim();return r&&r.length>0?r:t}function Pn(e,t={}){if(Nt(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?ti(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let o=ze(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of o.split(`
|
|
14
|
+
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let u=l[0][0],d=ya((l.length>=3?l[l.length-1]:l[1]).trim());d&&(u==="A"||u==="C"?a.set(d,"added"):u==="R"?a.set(d,"renamed"):a.set(d,"modified"))}if(n){let c=ze(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
|
|
15
|
+
`)){if(l.length<4)continue;let u=l[0],d=l[1];if(u==="D"||d==="D")continue;let p=l.slice(3),f=p.indexOf(" -> ");f>=0&&(p=p.slice(f+4)),p=ya(p),!(!p||a.has(p))&&(u==="?"||u==="A"||d==="A"?a.set(p,"added"):u==="R"?a.set(p,"renamed"):a.set(p,"modified"))}}return a}function ya(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function va(e,t={}){let n=Pn(e,t);return n===null?null:Cn(n.keys())}function Sa(e,t){try{let n=Em(ba.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Dn(e){return vm("sha256").update(e).digest("hex")}function Nt(e){return ze(e,["rev-parse","HEAD"])?.trim()??null}function On(e,t){return ze(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function Ea(e){let t=ze(e,["status","--porcelain","-uall"]);return t!==null&&t.trim().length>0}var ga,xm,ze,V=w(()=>{"use strict";Sn();ga=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),xm=["-c","diff.renames=true","-c","core.quotePath=false"];s(k,"runGit");ze=k;s(Rm,"toPosix");s(Cn,"classify");s(wa,"classifyPaths");s(_a,"discoverSourceFiles");s(ka,"walk");s(ti,"resolveDiffBase");s(Pn,"enumerateChangedPaths");s(ya,"unquote");s(va,"changedSourceFiles");s(Sa,"statFile");s(Dn,"hashContent");s(Nt,"headCommit");s(On,"resolveCommitSha");s(Ea,"isWorktreeDirty")});function Ra(e,t={}){if(k(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?ti(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=k(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")>Am?c="none":Cm(o,a,()=>{c="partial"}),n){let l=k(e,["status","--porcelain","-uall"])??"";for(let u of l.split(`
|
|
16
|
+
`)){if(u.length<4||u[0]!=="?")continue;let d=u.slice(3);d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),!(!d||a.has(d))&&a.set(d,{path:d,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:a,coverage:c}}function Cm(e,t,n){let r=null,i=0,o=!1,a=!1,c=s(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
|
|
17
|
+
`)){if(l.startsWith("diff --git ")){c(),o=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){o=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let d=l.slice(4).trim();if(d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),d.startsWith("b/")&&(d=d.slice(2)),d==="/dev/null")continue;r={path:d,status:a?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let u=Nm.exec(l);if(u){if(i++,i>Tm){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let d=Number(u[1]),p=u[2]===void 0?1:Number(u[2]);p>0?r.addedRanges.push({start:d,end:d+p-1}):r.deletionPoints.push(d);continue}l.startsWith("+")&&!l.startsWith("+++")&&!r.degraded&&r.addedLines.length<Im&&r.addedLines.push(l.slice(1))}c()}var Am,Tm,Im,xa,Nm,Aa=w(()=>{"use strict";V();Am=16*1024*1024,Tm=500,Im=4e3,xa=256*1024,Nm=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(Ra,"changedHunks");s(Cm,"parseUnifiedDiff")});function Om(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function Ia(e){return e.split(Pm).filter(t=>t.trim().length>0)}function Na(e){let[t,n,r,i,o]=e.replace(/\n+$/,"").split(Dm);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:o??""}}function Mm(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 Pa(e,t,n={}){let r=Om(n.limit,20,100),i=n.includeOwnership!==!1,o=Math.max(r,Ca),a=t.map(d=>d.trim()).filter(d=>d.length>0&&!d.startsWith(":")),c=a.slice(0,ni),l=[];for(let d of c){let p=k(e,["log","-n",String(o),Ta,"--",d]),f=p===null?[]:Ia(p).map(Na).filter(h=>h!==null);l.push({path:d,lastCommits:f.slice(0,r),ownership:i?{topAuthors:Mm(f),commitsInWindow:f.length}:null})}let u=null;if(n.since){let d=On(e,n.since),p=d!==null?[`${d}..HEAD`]:[`--since=${n.since}`],f=k(e,["log",...p,"-n",String(Mn+1),Ta,"--name-only","--",...c]),h=[];if(f!==null)for(let m of Ia(f)){let g=m.split(`
|
|
18
|
+
`),y=Na(g[0]??"");if(!y)continue;let b=g.slice(1).filter(_=>_.trim().length>0).length;h.push({sha:y.sha,dateIso:y.dateIso,authorName:y.authorName,subject:y.subject,filesTouched:b})}u={sinceInput:n.since,sinceResolved:d,commits:h.slice(0,Mn),truncated:h.length>Mn}}return{history:l,regression:u,ownershipWindowCommits:o,pathsTruncated:a.length>ni}}var Pm,Dm,Ca,ni,Mn,Ta,ri=w(()=>{"use strict";V();Pm="",Dm="\0",Ca=200,ni=50,Mn=100,Ta="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";s(Om,"clamp");s(Ia,"splitRecords");s(Na,"parseHistoryRecord");s(Mm,"aggregateOwnership");s(Pa,"readFileHistory")});import{execFileSync as Fm}from"node:child_process";import{readdirSync as Lm,statSync as Da}from"node:fs";import{isAbsolute as $m,join as ii,relative as jm,resolve as Hm}from"node:path";function Gm(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function Km(e,t){try{let n=Fm("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 Bm(e){let t;try{t=Lm(e)}catch{return null}for(let n of t.filter(Gm))try{let r=Da(ii(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function Wm(e){try{return Da(e).isDirectory()}catch{return!1}}function Vm(e,t){let n=jm(e,t);return!n||n.startsWith("..")?t:n}function oi(e){let t=Um.filter(c=>Wm(ii(e,c))),n=Km(e,"core.hooksPath"),r=n?$m(n)?n:Hm(e,n):ii(e,".git","hooks"),i=Vm(e,r),o=Bm(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 si(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 Um,ai=w(()=>{"use strict";Um=[".githooks",".husky"];s(Gm,"isRealHook");s(Km,"gitConfig");s(Bm,"hasExecutableHook");s(Wm,"isDir");s(Vm,"displayPath");s(oi,"resolveHookState");s(si,"describeHookState")});import{posix as Oa}from"node:path";function Ye(e){let t=qm.exec(e);return t?t[1]:null}function de(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Ae(e,t){let n=k(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=Oa.basename(o),c=Ye(a);if(c===null)continue;let l=Oa.dirname(o),u=i.get(l)??[];u.push({path:o,name:a,version:c}),i.set(l,u)}return[...i.entries()].map(([o,a])=>({dir:o,files:a.sort((c,l)=>de(c.version,l.version))})).sort((o,a)=>o.dir.localeCompare(a.dir))}function Ma(e){let t=k(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(k(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var qm,Ct=w(()=>{"use strict";V();qm=/^(\d+)_.+\.sql$/;s(Ye,"parseMigrationVersion");s(de,"compareVersions");s(Ae,"discoverSupabaseProjects");s(Ma,"resolveDefaultBranch")});import{execFileSync as Jm}from"node:child_process";import{existsSync as $,readFileSync as be,readdirSync as Fn,statSync as li}from"node:fs";import{posix as x}from"node:path";function Qm(e,t){let n=(()=>{let i=k(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($(x.join(r,".git"))){let o=(()=>{let c=k(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&o!=null&&ui(n,o))){let c=Zm(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=x.dirname(r)}return null}function Zm(e,t){let n=[];for(let r of Ym){let i;try{i=Fn(x.join(e,r),{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>o.name)}catch{continue}for(let o of i){let a=`${r}/${o}`,c=x.join(e,a),l=x.join(t,a);try{let u=li(c),d=li(l);if(!d.isFile())continue;if(u.size!==d.size){n.push(a);continue}if(u.size>Xm)continue;be(c).equals(be(l))||n.push(a)}catch{continue}}}return n.sort()}function Ga(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 ${pi}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let a=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${a.map(c=>c.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:a.map(c=>`${c.install} (in ${x.dirname(c.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:a,diverging:c}=e.toolCopyDrift,l=c.slice(0,3).join(", "),u=c.length>3?` (+${c.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${a} ships ${l}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${c[0]}\` from this repo root), not via a path into ${a}.`})}if(e.stalePackageBuilds.length>0){let a=e.stalePackageBuilds,c=s(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),l=a.every(u=>u.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:a.some(u=>u.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${a.map(c).join(", ")}: src/ is newer than the built ${[...new Set(a.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${l}`,hint:`Rebuild: pnpm --filter ./${a[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let o=eh(e.hooks);return o&&t.push(o),th(t)}function eh(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:si(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 th(e){return[...e].sort((t,n)=>Fa[t.status]-Fa[n.status]||t.id.localeCompare(n.id))}function Ka(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function ue(e){let t=e?.trim();return t||null}function nh(e){let t=ue(k(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(k(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function rh(e){let t=ue(k(e,["rev-parse","--git-dir"]));if(!t)return null;let n=x.isAbsolute(t)?t:x.join(e,t);return $(x.join(n,"rebase-merge"))||$(x.join(n,"rebase-apply"))?"rebase":$(x.join(n,"MERGE_HEAD"))?"merge":$(x.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function ih(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 oh(e){let t=x.join(e,pi);if(!$(t))return[];try{return be(t,"utf8").split(`
|
|
20
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function sh(e){try{return Ae(e).map(t=>x.join(x.dirname(t.dir),"config.toml"))}catch{return[]}}function ah(e){let t=k(e,["ls-files","-z","--",...zm]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=Ua[x.basename(r)];if(i===void 0)continue;let o=x.dirname(r);if(!ch(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 ch(e,t){return t==="."?!0:di(e,t)}function di(e,t){if($(x.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(be(x.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Ba(e,t={}){if(ue(k(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=ue(k(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",o=i?null:r,a=nh(e),c=ue(k(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,u=null;if(c){let T=ue(k(e,["rev-parse","HEAD"])),N=ue(k(e,["rev-parse","@{u}"]));l=T!=null&&N!=null?T===N:null,u=k(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let d=null,p=null;if(a){let T=ue(k(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(T){let[N,A]=T.split(/\s+/).map(X=>Number.parseInt(X,10));Number.isFinite(N)&&(p=N),Number.isFinite(A)&&(d=A)}}let h=(k(e,["status","--porcelain"])??"").split(`
|
|
21
|
+
`).filter(T=>T.trim().length>0).length,m=rh(e),g=ue(k(e,["rev-parse","--show-toplevel"]))??e,y=ih(k(e,["worktree","list","--porcelain"])??""),b=y[0]?.path??null,_=b!=null&&ui(b,g),S=Math.max(0,y.length-1),v=null;if(b&&!ui(b,g)){let T=s(A=>$(x.join(b,A))&&!$(x.join(g,A)),"here"),N=[...Ha,...sh(g),...oh(g),...t.probePaths??[]];v={mainWorktreePath:b,currentWorktreePath:g,missing:[...new Set(N.filter(T))],missingDeps:ah(g).filter(A=>T(A.dir))}}let E=Qm(g,e),R=t.includeRelease===!1?null:hh(e,o),G=[];return a&&(G=(k(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
|
|
22
|
+
`).map(N=>N.trim()).filter(N=>N.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:u,ahead:d,behind:p,uncommitted:h,detachedHead:i,inProgressOp:m,isSharedMainTree:_,otherWorktrees:S,worktreeParity:v,toolCopyDrift:E,stalePackageBuilds:Wa(g),release:R,unmergedMigrations:G,hooks:oi(e)}}function ui(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function uh(e){let t=new Set;di(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<$a;){let i=n.pop();if(i===void 0)break;if(i.depth>=dh)continue;let o;try{o=Fn(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>=$a)break;di(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function ph(e){let t=[];try{let n=x.join(e,"pnpm-workspace.yaml");if($(n)){let r=!1;for(let i of be(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($(r)){let i=JSON.parse(be(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 fh(e){let t=[];for(let n of uh(e)){let r=n==="."?e:x.join(e,n),i=s(o=>n==="."?o:x.join(n,o),"prefix");for(let o of ph(r)){if(t.length>=ci)break;if(!(o.startsWith("!")||o.includes("**")))try{if(o.endsWith("/*")){let a=o.slice(0,-2),c=x.join(r,a);if(!$(c))continue;for(let l of Fn(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(x.join(a,l.name))),t.length>=ci)break}else o.includes("*")||t.push(i(o))}catch{}}}return t.slice(0,ci)}function ja(e){let t=null,n=0,r=[e];for(;r.length>0&&n<La;){let i=r.pop();if(i===void 0)break;let o;try{o=Fn(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=li(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=La)break}}}return t}function mh(e,t){let n=new Set;for(let r of t)try{let i=x.join(e,r,"package.json");if(!$(i))continue;let o=JSON.parse(be(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=o[a];if(!(c===null||typeof c!="object"))for(let[l,u]of Object.entries(c))typeof u=="string"&&u.startsWith("workspace:")&&n.add(l)}}catch{}return n}function Wa(e){let t=[],n=fh(e),r=mh(e,n);for(let i of n)try{let o=x.join(e,i,"package.json");if(!$(o))continue;let a=JSON.parse(be(o,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(b=>{if(typeof b!="string")return null;let _=b.replace(/^\.\//,"").split("/")[0];return _==="build"||_==="dist"?_:null},"builtSeg"),l=c(a.types??a.typings),u=c(a.main),d=l??u;if(d===null)continue;let p=l!==null&&u!==null?"both":l!==null?"types":"runtime",f=x.join(e,i,"src"),h=x.join(e,i,d);if(!$(f)||!$(h))continue;let m=ja(f),g=ja(h);if(m===null||g===null)continue;let y=m-g;y>lh&&t.push({packageDir:i,buildDir:d,srcNewerByMs:Math.round(y),impact:p})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}function hh(e,t){if(!t)return null;let n=gh(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 gh(e,t){try{return Jm("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function Pt(e,t={}){let n=await Ba(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=Ga(n),i=Ka(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var Ha,pi,Ua,zm,Ym,Xm,Fa,lh,ci,La,dh,$a,fi=w(()=>{"use strict";ai();V();Ct();Ha=["supabase/config.toml","supabase/.temp",".env"],pi=".maind/worktree-requirements",Ua={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},zm=Object.keys(Ua).flatMap(e=>[e,"*/"+e]),Ym=["scripts"],Xm=512*1024;s(Qm,"gatherToolCopyDrift");s(Zm,"compareToolDirs");s(Ga,"computeDivergence");s(eh,"computeHookFinding");Fa={open:0,warn:1,info:2,passed:3};s(th,"sortFindings");s(Ka,"isHealthy");s(ue,"trimOrNull");s(nh,"resolveDefaultBranch");s(rh,"detectInProgressOp");s(ih,"parseWorktrees");s(oh,"readWorktreeRequirements");s(sh,"discoverSupabaseConfigProbes");s(ah,"discoverDependencyDirs");s(ch,"isWorkspaceRoot");s(di,"hasWorkspaceMarkers");s(Ba,"gatherRepoHealthFacts");s(ui,"samePath");lh=2e3,ci=64,La=4e3,dh=3,$a=400;s(uh,"findWorkspaceRoots");s(ph,"workspacePatternsAt");s(fh,"listWorkspacePackageDirs");s(ja,"newestMtimeUnder");s(mh,"consumedWorkspaceNames");s(Wa,"gatherStalePackageBuilds");s(hh,"gatherReleaseFact");s(gh,"runGh");s(Pt,"checkDivergence")});import{existsSync as mi,readdirSync as Va}from"node:fs";import{posix as ne}from"node:path";function gi(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(hi)}function Ja(e,t={}){let n=t.minFiles??yi;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??qa)}function Qe(e){return`${e.dir}#${e.prefix}`}function Dt(e){let t=yh.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function za(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let o=Qe(i),a=e.sightingsByNamespace.get(o);if(!a)continue;let c=new Set(a.keys());for(let[l,u]of a){let d=[...new Set(u.map(m=>m.path))];if(d.length<2)continue;let p=d.find(m=>n.has(m)),f=d.filter(m=>m!==p),h=`${i.prefix}${l}`;t.push(p?{id:`number.collision:${o}#${l}`,status:"open",namespace:i,number:l,title:`${h} is already taken`,detail:`This branch adds ${p}, but ${h} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${h} stop being unambiguous.`,ownPath:p,sightings:u.filter(m=>m.path!==p),suggestion:`${i.prefix}${bi(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:`${h} is used more than once (pre-existing)`,detail:`${h} is carried by ${d.length} files: ${d.join(", ")}.`,sightings:u,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,o)=>r[i.status]-r[o.status]||i.id.localeCompare(o.id))}function Ya(e){return!e.some(t=>t.status==="open")}function bi(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 wi(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Xa(e,t){let n=wi(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=Dt(ne.basename(n));if(!i)return r;let o=`${ne.dirname(n)}#${i.prefix}`,a=e.namespaces.find(d=>Qe(d)===o)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(o)??new Map,l=new Set,u=[];for(let d of c.get(i.number)??[])d.path===n||l.has(d.path)||(l.add(d.path),u.push(d));return{path:n,namespace:a,number:i.number,taken:u.length>0,sightings:u,suggestion:bi(c.keys(),i.number)}}function Ln(e){let t=e?.trim();return t||null}function Xe(e){return e?e.split(`
|
|
24
|
+
`).filter(Boolean):[]}function bh(e){let t=Ln(k(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(k(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Qa(e,t={}){let n=t.minFiles??yi,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=k(e,r);if(i===null)return[];let o=new Map;for(let a of i.split("\0").filter(Boolean)){let c=ne.dirname(a),l=Dt(ne.basename(a));if(!l)continue;let u=`${c}#${l.prefix}`,d=o.get(u);d?d.numbers.push(l.number):o.set(u,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...o.values()].filter(a=>Ja(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)=>Qe(a).localeCompare(Qe(c)))}async function _i(e,t={}){let n=[];if(Ln(k(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=Qa(e,t),o=new Map(i.map(m=>[Qe(m),m])),a=[...new Set(i.map(m=>m.dir))],c=new Map,l=s((m,g,y)=>{let b=ne.dirname(m),_=Dt(ne.basename(m));if(!_)return;let S=`${b}#${_.prefix}`;if(!o.has(S))return;let v=c.get(S)??new Map,E=v.get(_.number)??[];E.push({kind:g,where:y,path:m}),v.set(_.number,E),c.set(S,v)},"record"),u=s((m,g,y)=>{if(a.length===0)return;let b=k(e,["ls-tree","-r","--name-only",m,"--",...a]);if(b===null){n.push(`could not read ${y}`);return}for(let _ of Xe(b))l(_,g,y)},"scanTree");for(let m of a){let g=ne.join(e,m);if(mi(g))try{for(let y of Va(g))l(`${m}/${y}`,"self","this worktree")}catch{n.push(`could not read ${m}`)}}let d=bh(e),p=t.baseRef??(d?`origin/${d}`:null);p?u(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let f=Ln(k(e,["rev-parse","--abbrev-ref","HEAD"]));for(let m of Xe(k(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))m!==f&&u(m,"branch",`Branch ${m}`);if(t.includeWorktrees!==!1){let m=Ln(k(e,["rev-parse","--show-toplevel"]));for(let g of Xe(k(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===m||!mi(y)))for(let b of a){let _=ne.join(y,b);if(mi(_))try{for(let S of Va(_))l(`${b}/${S}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${b} in ${y}`)}}}}let h=[];if(p&&a.length>0){let m=k(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);m===null?n.push(hi):h=Xe(m);let g=k(e,["ls-files","--others","--exclude-standard","--",...a]);g!==null&&(h=[...h,...Xe(g)]);let y=k(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);y!==null&&(h=[...h,...Xe(y)])}return{isRepo:!0,defaultBranch:d,baseRef:p,namespaces:i,sightingsByNamespace:c,addedPaths:h,skipped:n}}async function Te(e,t={}){let n=await _i(e,t),r=za(n);return{ok:Ya(r),findings:r,facts:n}}async function Ie(e,t,n={}){let r=wi(t);if(!Dt(ne.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await _i(e,{...n,dirs:n.dirs??[ne.dirname(r)]});return Xa(i,r)}var hi,yh,yi,qa,Ot=w(()=>{"use strict";V();hi="could not diff against the base ref \u2014 everything reported as info";s(gi,"isNumberCollisionsGraded");yh=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,yi=3,qa=.8;s(Ja,"isCounterNamespace");s(Qe,"namespaceKey");s(Dt,"parseNumbered");s(za,"computeNumberCollisions");s(Ya,"isCollisionFree");s(bi,"suggestNextNumber");s(wi,"normaliseRepoPath");s(Xa,"checkProposedNumber");s(Ln,"trimOrNull");s(Xe,"lines");s(bh,"resolveDefaultBranch");s(Qa,"detectNamespaces");s(_i,"gatherNumberCollisionFacts");s(Te,"checkNumberCollisions");s(Ie,"checkNumberForPath")});function xi(e){return`spec.${e}`}function Ze(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 wh(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 Za(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(wh)}function Mt(e){return qr(JSON.stringify(Za(e)))}var ki,vi,Si,Ei,Ri=w(()=>{"use strict";Jr();ki={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"]}},vi="number.collision",Si="theme.dead_class",Ei="acl.missing_revoke";s(xi,"specDriftRuleId");s(Ze,"gradeEngineStatus");s(wh,"codePointCompare");s(Za,"normalizeEvidenceForHash");s(Mt,"hashDetectorEvidence")});import{existsSync as _h,readFileSync as ec}from"node:fs";import{posix as kh}from"node:path";function Hn(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 Un(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 Ft(e){return e==='"'||e==="'"||e==="`"}function Gn(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function $n(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(Ft(o)){i=Hn(e,i);continue}if(Gn(e,i)){i=Un(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function vh(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Gn(e,t)){t=Un(e,t);continue}break}return e.slice(t)}function et(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let o=e[i];if(Ft(o)){i=Hn(e,i);continue}if(Gn(e,i)){i=Un(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=>vh(o).trim()).filter(o=>o.length>0)}function ic(e){let t=Hn(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
|
|
26
|
+
`:i==="r"?"\r":i==="t"?" ":i)}function Sh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ti(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${Sh(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(Ft(a)){i=Hn(e,i);continue}if(Gn(e,i)){i=Un(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 $n(e,i);if(a===";")return null;i++}return null}function Ii(e){let t={};if(!e.startsWith("{"))return t;for(let n of et(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();Ft(o[0]??"")&&(t[i]=ic(o))}return t}function Eh(e,t){if(!e.startsWith("{"))return null;for(let n of et(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 sc(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function ac(e,t){let n=Ti(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=sc(),i=[],o=0;for(let a of et(n.slice(1,-1))){if(!a.startsWith("{")){o++;continue}let c=Ii(a),l=c[t.key_field];if(!l){o++;continue}let u=(t.partition_by??[]).map(d=>c[d]??"");i.push({key:l,fields:oc(c,t.fields),orderPath:u,ordinal:r(u)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function cc(e,t){let n=Ti(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=sc(),i=[],o=0,a=s((c,l,u)=>{let d=t.levels[l],p=l===t.levels.length-1;for(let f of et(c.slice(1,-1))){let h={...u},m=null;if(d.shape==="object"){if(!f.startsWith("{")){o++;continue}let g=Ii(f);for(let[y,b]of Object.entries(d.fields??{}))h[y]=g[String(b)]??"";if(!p&&typeof d.children=="string"){let y=Eh(f,d.children);m=y&&y.startsWith("[")?$n(y,0):null}}else{if(!f.startsWith("[")){o++;continue}let g=et(f.slice(1,-1));for(let[y,b]of Object.entries(d.fields??{})){let _=g[Number(b)];h[y]=_!==void 0&&Ft(_[0]??"")?ic(_):""}if(!p&&typeof d.children=="number"){let y=g[d.children];m=y!==void 0&&y.startsWith("[")?$n(y,0):null}}if(p){let g=h[t.key_field];if(!g){o++;continue}let y=(t.partition_by??[]).map(b=>h[b]??"");i.push({key:g,fields:oc(h,t.fields),orderPath:y,ordinal:r(y)});continue}m!==null&&a(m,l+1,h)}},"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 tc(e,t){return t.extractor==="object-array"?ac(e,t):cc(e,t)}function lc(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 dc(e,t,n){return`spec.drift:${e}#${t}:${n}`}function xh(e){return e.orderPath.join(" / ")||"(flat)"}function uc(e,t,n,r){let i=[],o=s((u,d,p,f,h,m)=>{i.push({id:dc(e.id,u,p),contract:e.id,dimension:u,status:d,key:p,title:f,detail:h,hint:m})},"push"),a=new Map(n.map(u=>[u.key,u])),c=new Map(t.map(u=>[u.key,u]));for(let u of t){let d=a.get(u.key);if(!d){o("coverage","open",u.key,`${u.key} is declared by the specification but missing from the implementation`,`Partition ${xh(u)}, position ${u.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let f=u.fields[p]??"",h=d.fields[p]??"";f!==h&&o("fields","open",`${u.key}.${p}`,`${u.key}: ${p} is "${h||"\u2014"}", the specification says "${f||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let u of t){let d=u.orderPath.join("\0"),p=l.get(d);p?p.push(u):l.set(d,[u])}for(let[u,d]of l){let p=d.filter(g=>a.has(g.key)).map(g=>g.key),f=n.filter(g=>g.orderPath.join("\0")===u).filter(g=>c.has(g.key)).map(g=>g.key),h=new Set(f),m=p.filter(g=>h.has(g));if(f.join("|")!==m.join("|")){let g=u.split("\0").join(" / ")||"(flat)";o("order","open",g,`Partition ${g}: sequence differs from the specification`,`implementation: ${f.join(" \u2192 ")}
|
|
27
|
+
specification: ${m.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let u of n)c.has(u.key)||o("extra","warn",u.key,`${u.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let u of new Set([...a.keys(),...c.keys()])){if(lc(u,e.grounding,r))continue;let d=a.has(u);o("unrealized",d?"open":"warn",u,d?`${u} is referenced by the implementation but has no artefact`:`${u} is declared by the specification but not built yet`,d?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}function Rh(e,t,n){let r=[];for(let i of e.assertions??[]){let o=n.get(i.path);if(!o)continue;let a=o.indexOf(i.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(o.slice(a+i.prefix.length));if(!c)continue;let l=Number(c[1]),u=t[i.counts];l!==u&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${u}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function 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 pc(e,t={}){let n=s(d=>({ok:!1,verdict:"no_opinion",reason:d,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(d=>t.contracts.includes(d.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(d=>`"${d}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=s(d=>{let p=[],f=[];for(let h of r){let m=d.get(h.spec.path),g=d.get(h.impl.path);if(m==null||g==null){let S=m==null?h.spec.path:h.impl.path;p.push(nc(h.id,`Declared file could not be read: ${S}`)),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let y=tc(m,h.spec),b=tc(g,h.impl);if(y.error||b.error){p.push(nc(h.id,y.error??b.error??"unknown")),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=y.dropped>0||b.dropped>0;f.push({id:h.id,measured:!0,specRecords:y.records.length,implRecords:b.records.length,partial:_}),_&&p.push({id:`contract.partial:${h.id}`,contract:h.id,dimension:"contract",status:"warn",key:null,title:`Contract "${h.id}" was measured incompletely`,detail:`${y.dropped} specification and ${b.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),p.push(...uc(h,y.records,b.records,e.files)),p.push(...Rh(h,{spec:y.records.length,impl:b.records.length},d))}return{findings:p,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 p of d.exceptions??[])c.set(dc(d.id,p.dimension,p.key),p);let l=o.findings.map(d=>{let p=c.get(d.id);return p?{...d,status:"info",exceptionReason:p.reason}:a.has(d.id)?{...d,status:"info",detail:`${d.detail}
|
|
28
|
+
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:d});l.sort((d,p)=>rc[d.status]-rc[p.status]||d.id.localeCompare(p.id));let u=l.some(d=>d.status==="open");return{ok:!u,verdict:u?"drifted":"aligned",reason:null,findings:l,contracts:o.contracts}}function Ai(e){let t=e?.trim();return t||null}function Kn(e){let t;try{t=JSON.parse(e)}catch(a){return{manifest:null,error:`manifest is not valid JSON: ${a.message}`}}let n=s(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,"obj"),r=s(a=>typeof a=="string"?a:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let o=s(a=>({manifest:null,error:a}),"bad");for(let[a,c]of i.contracts.entries()){let l=n(c),u=r(l?.id),d=u?`contract "${u}"`:`contract #${a+1}`;if(!l)return o(`${d}: not an object`);if(!u)return o(`${d}: \`id\` is missing`);if(!r(l.reason))return o(`${d}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let p of["spec","impl"]){let f=n(l[p]);if(!f)return o(`${d}: \`${p}\` is missing`);let h=r(f.extractor);if(!h)return o(`${d}: \`${p}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return o(`${d}: unknown \`${p}.extractor\` "${h}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return o(`${d}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(f.levels))return o(`${d}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(l.exceptions)?l.exceptions:[]){let f=n(p);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 Ah(e){let t=Ai(k(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(k(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Th(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 fc(e,t={}){let n=s((m,g)=>kh.join(m,g),"join"),r=t.manifestPath??jn,i=[],o={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(Ai(k(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...o,manifestError:"not a git work tree"};let a=n(e,r);if(!_h(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}=Kn(ec(a,"utf8")))}catch(m){l=`manifest at ${r} could not be read: ${m.message}`}if(!c)return{...o,isRepo:!0,manifestError:l};let u=new Map;for(let m of Th(c))try{u.set(m,ec(n(e,m),"utf8"))}catch{u.set(m,null),i.push(`declared file unreadable in the working tree: ${m}`)}let d=new Set,p=k(e,["ls-files","-z"]);if(p===null)i.push("could not list tracked files \u2014 grounding is skipped");else for(let m of p.split("\0"))m&&d.add(m);let f=null,h=new Map;if(t.includeBaseline!==!1){let m=t.baseRef?null:Ah(e),g=t.baseRef??(m?`origin/${m}`:null);if(!g)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(f=Ai(k(e,["merge-base",g,"HEAD"])),!f)i.push(`no merge-base with ${g} \u2014 every finding reported as new`);else for(let y of u.keys())h.set(y,k(e,["show",`${f}:${y}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:u,baselineSources:h,baseRef:f,files:d,skipped:i}}async function Ne(e,t={}){let n=await fc(e,t);return{...pc(n,t),facts:n}}function Ni(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var jn,rc,Lt=w(()=>{"use strict";V();jn=".maind/spec-contracts.json";s(Hn,"endOfString");s(Un,"skipComment");s(Ft,"isQuote");s(Gn,"isCommentStart");s($n,"sliceBalanced");s(vh,"stripLeadingTrivia");s(et,"splitTopLevel");s(ic,"readStringLiteral");s(Sh,"escapeRe");s(Ti,"findSymbolArray");s(Ii,"parseObjectFields");s(Eh,"objectFieldRaw");s(oc,"pickFields");s(sc,"makeOrdinals");s(ac,"extractObjectArray");s(cc,"extractNestedList");s(tc,"extractRecords");s(lc,"isGrounded");s(dc,"findingId");s(xh,"partitionOf");s(uc,"compareContract");s(Rh,"checkAssertions");s(nc,"unreadable");rc={open:0,warn:1,info:2,passed:3};s(pc,"computeSpecDrift");s(Ai,"trimOrNull");s(Kn,"parseManifest");s(Ah,"resolveDefaultBranch");s(Th,"declaredPaths");s(fc,"gatherSpecDriftFacts");s(Ne,"checkSpecDrift");s(Ni,"isSpecDriftGraded")});import{readFileSync as Ih}from"node:fs";import{join as Nh,posix as Ch}from"node:path";function mc(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],o=e[n+1];if(i==="-"&&o==="-"){for(;n<r&&e[n]!==`
|
|
29
|
+
`;)n++;continue}if(i==="/"&&o==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],u=e.indexOf(l,n+l.length);n=u===-1?r:u+l.length,t+=" ";continue}}let a=(i==="E"||i==="e")&&o==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||a){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function we(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 $t(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 hc(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(Ph.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!$t(l[1]).map(f=>we(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),f=$t(p).map(h=>we(h)).filter(h=>h!==null).filter(h=>h.schema==="public").map(h=>h.name);if(f.length===0)return null;c=f}let u=$t(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>we(p)?.name??"").filter(p=>p.length>0&&p!=="public"),d=[];for(let p of $t(r)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let h=f[1].toUpperCase(),m=f[2]==="(";if(h==="ALL")return{tables:c,roles:u,writePrivs:[...Ci]};!m&&Ci.includes(h)&&d.push(h)}return{tables:c,roles:u,writePrivs:d}}function Di(e){let t=new Map,n=[...e].sort((r,i)=>de(r.version,i.version));for(let r of n){let i=mc(r.content);for(let o of i.split(";")){let a=o.trim();if(!a)continue;let c=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(a);if(c){if(/\bTEMP(?:ORARY)?\b/i.test(c[1]??""))continue;let d=we(c[2]);if(!d||d.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(a)&&t.has(d.name))continue;t.set(d.name,{createdIn:r.version,anonAddressed:!1,authWritesRevoked:new Set});continue}let l=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(a);if(l){let d=l[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let p of $t(d)){let f=we(p);f&&f.schema==="public"&&t.delete(f.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(a);if(u){let d=we(u[1]),p=we(u[2]);if(d&&p&&d.schema==="public"){let f=t.get(d.name);f&&(t.delete(d.name),t.set(p.name,f))}continue}if(/^REVOKE\b/i.test(a)){let d=hc(a);if(!d)continue;let p=d.tables==="all_in_public"?[...t.keys()]:d.tables,f=d.roles.includes("anon"),h=d.roles.includes("authenticated");if(!f&&!h)continue;for(let m of p){let g=t.get(m);if(g&&(f&&(g.anonAddressed=!0),h))for(let y of d.writePrivs)g.authWritesRevoked.add(y)}continue}}}return t}function Pi(e){let t=[];for(let[n,r]of Di(e)){let i=[];r.anonAddressed||i.push("anon"),Ci.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 gc(e){let t=Pi(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Pi(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).`}})}function yc(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function Mi(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(Bn)||t.endsWith(Oi))}function Oh(e,t){try{let n=Ih(e,"utf8");return n.length>t?null:n}catch{return null}}function Mh(e,t,n,r,i){let o=k(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(o===null)return i.push(`could not diff ${t} against ${r} ${Bn}`),null;let a=new Set,c=[];for(let d of o.split(`
|
|
30
|
+
`).filter(Boolean)){let[p,...f]=d.split(" ");p.startsWith("A")?a.add(f[0]):p.startsWith("R")?(c.push(f[0]),a.add(f[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(f[0])}let l=[],u=new Set(c);for(let{ref:d,content:p}of n)!a.has(d.path)&&!u.has(d.path)&&l.push({name:d.name,version:d.version,content:p});for(let d of c){let p=Ch.basename(d),f=Ye(p);if(f===null)continue;let h=k(e,["show",`${r}:${d}`]);if(h===null)return i.push(`could not read ${d} at ${r} ${Oi}`),null;l.push({name:p,version:f,content:h})}return l}function Ce(e,t={}){let n=t.maxFileBytes??Dh,r=[],i=Ae(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=Ma(e);a=f?`origin/${f}`:null,a===null&&r.push(`no default branch resolvable ${Bn}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let f of i){let h=[];for(let y of f.files){let b=Oh(Nh(e,y.path),n);if(b===null){r.push(`could not read ${y.path} \u2014 excluded from the fold`);continue}h.push({ref:y,content:b})}let m=h.map(({ref:y,content:b})=>({name:y.name,version:y.version,content:b})),g=a===null?null:Mh(e,f.dir,h,a,r);c.push(...gc({dir:f.dir,files:m,baseFiles:g})),l.push({dir:f.dir,migrationCount:m.length,tableCount:Di(m).size})}let u=l.reduce((f,h)=>f+h.migrationCount,0),d=yc(u,c.length),p={open:0,info:1};return c.sort((f,h)=>p[f.status]-p[h.status]||f.id.localeCompare(h.id)),{ok:d!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:d,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var Ci,Ph,Dh,Bn,Oi,Wn=w(()=>{"use strict";V();Ct();s(mc,"stripSql");s(we,"normalizeQualifiedIdent");s($t,"splitTopLevel");Ci=["INSERT","UPDATE","DELETE"],Ph=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(hc,"parseTableRevoke");s(Di,"foldTableAcl");s(Pi,"evaluateTableAcl");s(gc,"computeTableAclFindings");s(yc,"deriveTableAclVerdict");Dh=5e6,Bn="\u2014 findings reported ungraded (open)",Oi="\u2014 baseline degraded";s(Mi,"isTableAclGraded");s(Oh,"safeRead");s(Mh,"baseFilesFor");s(Ce,"checkTableAclLint")});import{readFileSync as Fh}from"node:fs";import{join as Fi}from"node:path";function $i(e){return e.verdict!=="no_opinion"&&e.graded}function ji(e){let t=new Set;for(let n of e.matchAll(Lh))t.add(n[1]);return t}function Hi(e){return new Set([...e].map(t=>t.split("-")[0]))}function Sc(e){return e.split(`
|
|
31
|
+
`).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
|
|
32
|
+
`)}function Ui(e){let t=Hi(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let o=Sc(i),a=new Set;for(let c of o.matchAll($h)){let l=c[2],u=l.split("-")[0];if(!t.has(u)||e.tokens.has(l))continue;let d=`${c[1]}-${l}`;a.has(d)||(a.add(d),n.push({file:r,klass:d,token:l,namespace:u}))}}return n}function bc(e){return`${e.file} ${e.klass}`}function jh(e,t){let n=t===null?null:new Set(t.map(bc));return e.map(r=>({...r,status:n!==null&&n.has(bc(r))?"info":"open"}))}function Ec(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function Gi(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function _c(e,t){let n=k(e,["ls-files","--",...t]);return n===null?[]:n.split(`
|
|
33
|
+
`).filter(Boolean)}function Pe(e,t={}){let n=t.maxFileBytes??Hh,r=new Set;for(let d of _c(e,["*.css"])){let p=Li(Fi(e,d),n);if(p!==null)for(let f of ji(p))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=>wc.map(p=>`${d.replace(/\/+$/,"")}/**/${p}`)):wc,o=[];for(let d of _c(e,i)){if(!Gi(d))continue;let p=Li(Fi(e,d),n);p!==null&&o.push({path:d,content:p})}let a=Ui({tokens:r,sources:o}),c=t.includeBaseline===!1?null:Uh(e,i,n,t.baseRef),l=jh(a,c?.findings??null),u=Ec(r.size,l.length);return{ok:u!=="no_opinion"&&!l.some(d=>d.status==="open"),verdict:u,tokenCount:r.size,namespaceCount:Hi(r).size,findings:l,scannedFiles:o.length,graded:c!==null,baseRef:c?.mergeBase??null}}function Uh(e,t,n,r){let i=r??Kh(e);if(i===null)return null;let o=k(e,["merge-base",i,"HEAD"])?.trim();if(!o)return null;let a=k(e,["diff","--name-only","--no-renames",o]);if(a===null)return null;let c=new Set(a.split(`
|
|
34
|
+
`).filter(Boolean)),l=s(p=>c.has(p)?k(e,["show",`${o}:${p}`]):Li(Fi(e,p),n),"atBase"),u=new Set;for(let p of kc(e,o,["*.css"])){let f=l(p);if(f!==null)for(let h of ji(f))u.add(h)}if(u.size===0)return{findings:[],mergeBase:o};let d=[];for(let p of kc(e,o,t)){if(!Gi(p))continue;let f=l(p);f===null||f.length>n||d.push({path:p,content:f})}return{findings:Ui({tokens:u,sources:d}),mergeBase:o}}function kc(e,t,n){let r=k(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
|
|
35
|
+
`).filter(i=>i.length>0&&n.some(o=>Gh(i,o)))}function Gh(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 Kh(e){let t=k(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>k(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function Li(e,t){try{let n=Fh(e,"utf8");return n.length>t?null:n}catch{return null}}var vc,Lh,$h,wc,Hh,Vn=w(()=>{"use strict";V();s($i,"isThemeClassDriftGraded");vc=["bg","text","border","border-x","border-y","border-t","border-r","border-b","border-l","divide","outline","ring","ring-offset","fill","stroke","accent","caret","decoration","placeholder","shadow","from","via","to"],Lh=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,$h=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+vc.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(ji,"extractTokens");s(Hi,"deriveNamespaces");s(Sc,"stripCommentLines");s(Ui,"evaluateThemeClasses");s(bc,"findingKey");s(jh,"gradeAgainstBaseline");s(Ec,"deriveThemeClassVerdict");wc=["*.ts","*.tsx","*.js","*.jsx"],Hh=15e5;s(Gi,"isScannableSource");s(_c,"listTracked");s(Pe,"checkThemeClassDrift");s(Uh,"baselineFindings");s(kc,"listTrackedAt");s(Gh,"matchesSourcePattern");s(Kh,"resolveBaseRef");s(Li,"safeRead")});function Ki(e){return ki[e].version}function Ht(e,t,n,r){return{detector_id:e,detector_version:Ki(e),state:t,finding_count:n,...r?{reason:r}:{}}}function U(e,t,n){return{summary:Ht(e,t,0,n),findings:[]}}function Ic(e){return e==="open"||e==="warn"||e==="info"}function Wh(e){let t="det_number_collisions";if(!e.ok)return U(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return U(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return U(t,"not_applicable","no numbered namespaces");if(!gi(n))return U(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let o of r){if(!Ic(o.status))continue;let{level:a,baseline:c}=Ze(o.status);i.push({detector_id:t,rule_id:vi,level:a,baseline:c,evidence:[...o.ownPath?[o.ownPath]:[],...o.sightings.map(l=>l.path)],title:o.title})}return{summary:Ht(t,"ran",i.length),findings:i}}function Vh(e){let t="det_spec_drift";if(!e.ok)return U(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return U(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return U(t,"not_applicable",n.reason??"no opinion");if(!Ni(n))return U(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!Ic(i.status))continue;let{level:o,baseline:a}=Ze(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:xi(i.dimension),level:o,baseline:a,evidence:[i.id],title:i.title})}return{summary:Ht(t,"ran",r.length),findings:r}}function qh(e){let t="det_theme_class_drift";if(!e.ok)return U(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return U(t,"not_applicable","no theme tokens");if(!$i(n))return U(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=Ze(i.status);r.push({detector_id:t,rule_id:Si,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:Ht(t,"ran",r.length),findings:r}}function Jh(e){let t="det_table_acl_lint";if(!e.ok)return U(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return U(t,"not_applicable","no supabase migrations");if(!Mi(n))return U(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}=Ze(i.status);r.push({detector_id:t,rule_id:Ei,level:o,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:Ht(t,"ran",r.length),findings:r}}function Bi(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||Jn[e.level]-Jn[t.level]||Rc[e.baseline]-Rc[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Ac(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function zh(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let o=Mt(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:Ki(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,Jn[i.level]<Jn[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:Ki(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Mt(i.evidence),count:i.count});return r.sort(Bi)}function Yh(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 tt(e){let t={det_number_collisions:Wh(e.number),det_spec_drift:Vh(e.spec),det_theme_class_drift:qh(e.theme),det_table_acl_lint:Jh(e.acl)},n=xc.map(l=>t[l].summary),r=xc.flatMap(l=>t[l].findings),i=zh(r),o=[...i].sort((l,u)=>Ac(l)-Ac(u)||Bi(l,u)).slice(0,Tc).sort(Bi),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:Mt(l.evidence),title:l.title}));return{findings:o,coverage:Yh(n,a),engines:n,local:c,truncated:a}}function jt(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e}}}function Nc(e){return e instanceof Error?e.message:String(e)}async function qn(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:Nc(t)}}}async function Wi(e,t={}){let n={...Bh,...t.engines};try{if(k(e,["rev-parse","--is-inside-work-tree"])?.trim()!=="true")return tt(jt("not a git work tree"));let i=t.baseRef,o={number:await qn(()=>n.number(e,{...i?{baseRef:i}:{},...t.includeWorktrees===void 0?{}:{includeWorktrees:t.includeWorktrees}})),spec:await qn(()=>n.spec(e,i?{baseRef:i}:{})),theme:await qn(()=>n.theme(e,i?{baseRef:i}:{})),acl:await qn(()=>n.acl(e,i?{baseRef:i}:{}))};return tt(o)}catch(r){return tt(jt(`detector adapter failed: ${Nc(r)}`))}}var Tc,Bh,xc,Jn,Rc,Vi=w(()=>{"use strict";V();Ri();Ot();Lt();Wn();Vn();Tc=64,Bh={number:s((e,t)=>Te(e,t),"number"),spec:s((e,t)=>Ne(e,t),"spec"),theme:s((e,t)=>Pe(e,t),"theme"),acl:s((e,t)=>Ce(e,t),"acl")},xc=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint"];s(Ki,"versionOf");s(Ht,"summary");s(U,"noFindings");s(Ic,"isFindingStatus");s(Wh,"adaptNumber");s(Vh,"adaptSpec");s(qh,"adaptTheme");s(Jh,"adaptAcl");Jn={open:0,warn:1,info:2},Rc={introduced:0,pre_existing:1};s(Bi,"compareWire");s(Ac,"capPriority");s(zh,"buildWire");s(Yh,"deriveCoverage");s(tt,"adaptDetectorReports");s(jt,"unavailableDetectorReports");s(Nc,"errorText");s(qn,"attempt");s(Wi,"runRepoHealthDetectors")});var Cc,qi=w(()=>{"use strict";Cc=[{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 Pc(e){let t=new Set;for(let[n,r]of e.paths)for(let i of Cc){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let o=Xh(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function Xh(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
36
|
+
`):t.readUntracked(e)}var Dc=w(()=>{"use strict";qi();s(Pc,"scanRiskFlags");s(Xh,"contentForPath")});var nt,Oc,rt,it,Ji,zn,Yn,Xn,zi,Mc,Ut=w(()=>{"use strict";nt="1",Oc=`
|
|
30
37
|
CREATE TABLE IF NOT EXISTS meta (
|
|
31
38
|
key TEXT PRIMARY KEY,
|
|
32
39
|
value TEXT NOT NULL
|
|
@@ -85,20 +92,20 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
85
92
|
vec BLOB NOT NULL,
|
|
86
93
|
content_hash TEXT NOT NULL
|
|
87
94
|
);
|
|
88
|
-
`,Xe="schema_version",Qe="last_index_commit",ui="last_indexed_at",Ln="embed_recipe_version",jn="embed_model",Hn="embed_dim",pi="last_synced_at",Ja="last_synced_commit"});function fi(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 za(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of fi(e.name))t.add(i);for(let i of fi(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function Ya(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 fi(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var mi=b(()=>{"use strict";s(fi,"splitIdentifier");s(za,"buildSearchText");s(Ya,"toFtsMatchQuery")});import{readFileSync as Xa}from"node:fs";import{posix as Qa}from"node:path";function Za(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 Ie(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function ec(e){return e==="added"?0:e==="modified"?1:2}function nh(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),d=Math.min(a.end,e.endLine);d>=c&&(i+=d-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 Dt,hi=b(()=>{"use strict";Hs();jr();Ks();Ws();J();ia();Gr();Zr();oi();li();Va();Pt();mi();Dt=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(Xe),i=await this.store.countFiles()>0;(t.full||i&&r!==Ye)&&await this.wipe();let o=Xs(this.repoRoot),a=new Set(o.map(m=>m.path)),c=await this.store.getAllFiles(),d=new Map(c.map(m=>[m.path,m])),u=c.length>0&&!t.full,l={filesScanned:o.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u};for(let m of c)a.has(m.path)||(await this.store.deleteFile(m.path),l.filesDeleted++);let p=[],f=0;for(let m of o){f++;let g=ea(this.repoRoot,m.path);if(!g){l.filesSkipped++;continue}let w=d.get(m.path);if(w&&w.mtimeMs===g.mtimeMs&&w.size===g.size){l.filesSkipped++;continue}let y=this.readRepoFile(m.path);if(y===null){l.filesSkipped++;continue}let k=Tn(y);if(w&&w.contentHash===k){await this.store.upsertFile({...w,mtimeMs:g.mtimeMs,indexedAt:n}),l.filesSkipped++;continue}let S=await this.parser.parse(m.path,y,m.language),v=new Map;for(let R of S.nodes)v.set(R.nodeKey,za(R));let E={path:m.path,language:m.language,contentHash:k,mtimeMs:g.mtimeMs,size:g.size,indexedAt:n};await this.store.replaceFileNodes(E,S.nodes,v),p.push(S),l.filesParsed++,t.onProgress?.({path:m.path,done:f,total:o.length})}if(p.length>0){let m=await this.store.getNameIndex(),g=Gs(m);for(let w of p){let y=Bs(w,g);await this.store.replaceOutgoingEdges(y.srcKeys,y.edges)}}if(this.embedder&&t.embed){let m=await this.store.getNodesByKinds([...Lr]),g=await this.store.getEmbeddingContentHashes(),w=[];for(let k of m){let S=js(k),v=Tn(`${this.embedder.recipeVersion}\0${S}`);g.get(k.nodeKey)!==v&&w.push({nodeKey:k.nodeKey,text:S,hash:v})}let y=64;for(let k=0;k<w.length;k+=y){let S=w.slice(k,k+y),v=await this.embedder.embedDocuments(S.map(R=>R.text));await this.store.upsertEmbeddings(S.map((R,U)=>({nodeKey:R.nodeKey,dim:this.embedder.dim,vec:v[U],contentHash:R.hash})));let E=Math.min(k+y,w.length);t.onProgress?.({path:"embedding symbols",done:E,total:w.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Ln,this.embedder.recipeVersion),await this.store.setMeta(jn,this.embedder.model),await this.store.setMeta(Hn,String(this.embedder.dim))}await this.store.setMeta(Xe,Ye),await this.store.setMeta(ui,String(n));let h=xt(this.repoRoot);return h&&await this.store.setMeta(Qe,h),l.nodeCount=await this.store.countNodes(),l.edgeCount=await this.store.countEdges(),l.durationMs=(t.now??Date.now())-n,l}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(ui);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(Qe),schemaVersion:await this.store.getMeta(Xe),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Ie(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({...Za(c),score:a.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Ie(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(d=>({nodeKey:d.nodeKey,score:Us(i,d.vec)})).sort((d,u)=>u.score-d.score).slice(0,r),c=[];for(let d of a){let u=await this.store.getNode(d.nodeKey);u&&c.push({...Za(u),score:d.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Ie(n.maxDepth,3,5),o=Ie(n.limit,100,1e3),a=n.kinds??null,c=[],d=new Set,u=new Set([t]),l=[t];for(let p=0;p<i&&l.length>0;p++){let f=[];for(let h of l){let m=await this.store.neighbors(h,r,a,o);for(let g of m){let w=`${g.srcKey} ${g.dstKey} ${g.kind}`;if(d.has(w))continue;if(d.add(w),c.push({srcKey:g.srcKey,dstKey:g.dstKey,kind:g.kind}),c.length>=o)return c;let y=r==="out"?g.dstKey:g.srcKey;u.has(y)||(u.add(y),f.push(y))}}l=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=Xa(Qa.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(Ie(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Zs(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Ie(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=Rn(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(xt(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return la(this.repoRoot,n,t)}async checkDivergence(t={}){return Tt(this.repoRoot,t)}async checkNumberCollisions(t={}){return It(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Ae(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Ct(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Rn(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=ra(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=Wa({paths:n,hunks:i,readUntracked:s(f=>this.readRepoFileHead(f,na),"readUntracked")}),c=Ys(n.keys()),d=Ie(t.limit,64,200),u=[],l=0,p=0;for(let f of c){let h=await this.store.getNodesByFile(f.path);if(h.length===0)continue;l++;let m=await this.store.getFile(f.path),g=this.readRepoFile(f.path),w=m!==null&&g!==null&&Tn(g)!==m.contentHash;w&&(p++,o==="full"&&(o="partial"));let y=n.get(f.path)??"modified",k=i.get(f.path);for(let S of h)u.push(nh(S,y,k,w))}return u.sort((f,h)=>ec(f.change)-ec(h.change)||f.filePath.localeCompare(h.filePath)||f.startLine-h.startLine),{changedFiles:c.length,indexedFiles:l,staleFiles:p,symbols:u.slice(0,d),truncated:u.length>d,riskFlags:a,hunkCoverage:o,baseKind:t.since?"ref":"uncommitted",headSha:xt(this.repoRoot),dirty:ta(this.repoRoot),baseSha:t.since?An(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 Xa(Qa.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(Za,"toHit");s(Ie,"clampLimit");s(ec,"changeRank");s(nh,"classifyReviewSymbol")});import{createRequire as rh}from"node:module";function nc(){return tc("node:sqlite")}function Ze(){if(Ot)return Ot;try{let{DatabaseSync:e}=nc(),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(),Ot={ok:!0}}finally{t.close()}}catch(e){Ot={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Ot}function ih(e){let{DatabaseSync:t}=nc(),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 oh(e){let t=tc("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 sh(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Un(e){let t=sh(),n=s(i=>{let o=i==="node:sqlite"?ih(e):oh(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=Ze();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=Ze();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 tc,Ot,gi=b(()=>{"use strict";tc=rh(import.meta.url);s(nc,"loadBuiltin");Ot=null;s(Ze,"probeBuiltinSqlite");s(ih,"openBuiltin");s(oh,"openBetter");s(sh,"backendOverride");s(Un,"openSqliteDatabase")});function Kn(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 rc,Mt,ic=b(()=>{"use strict";gi();Pt();mi();s(Kn,"toNodeRow");rc=400,Mt=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Un(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(qa)}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?Kn(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Kn)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Kn)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Kn)}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=Ya(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
95
|
+
`,rt="schema_version",it="last_index_commit",Ji="last_indexed_at",zn="embed_recipe_version",Yn="embed_model",Xn="embed_dim",zi="last_synced_at",Mc="last_synced_commit"});function Yi(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 Fc(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of Yi(e.name))t.add(i);for(let i of Yi(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function Lc(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 Yi(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var Xi=w(()=>{"use strict";s(Yi,"splitIdentifier");s(Fc,"buildSearchText");s(Lc,"toFtsMatchQuery")});import{readFileSync as $c}from"node:fs";import{posix as jc}from"node:path";function Hc(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 De(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function Uc(e){return e==="added"?0:e==="modified"?1:2}function Qh(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 Gt,Qi=w(()=>{"use strict";la();Zr();ua();ma();V();Aa();ri();fi();Ot();Vi();Lt();Dc();Ut();Xi();Gt=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(rt),i=await this.store.countFiles()>0;(t.full||i&&r!==nt)&&await this.wipe();let o=_a(this.repoRoot),a=new Set(o.map(m=>m.path)),c=await this.store.getAllFiles(),l=new Map(c.map(m=>[m.path,m])),u=c.length>0&&!t.full,d={filesScanned:o.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u};for(let m of c)a.has(m.path)||(await this.store.deleteFile(m.path),d.filesDeleted++);let p=[],f=0;for(let m of o){f++;let g=Sa(this.repoRoot,m.path);if(!g){d.filesSkipped++;continue}let y=l.get(m.path);if(y&&y.mtimeMs===g.mtimeMs&&y.size===g.size){d.filesSkipped++;continue}let b=this.readRepoFile(m.path);if(b===null){d.filesSkipped++;continue}let _=Dn(b);if(y&&y.contentHash===_){await this.store.upsertFile({...y,mtimeMs:g.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let S=await this.parser.parse(m.path,b,m.language),v=new Map;for(let R of S.nodes)v.set(R.nodeKey,Fc(R));let E={path:m.path,language:m.language,contentHash:_,mtimeMs:g.mtimeMs,size:g.size,indexedAt:n};await this.store.replaceFileNodes(E,S.nodes,v),p.push(S),d.filesParsed++,t.onProgress?.({path:m.path,done:f,total:o.length})}if(p.length>0){let m=await this.store.getNameIndex(),g=pa(m);for(let y of p){let b=fa(y,g);await this.store.replaceOutgoingEdges(b.srcKeys,b.edges)}}if(this.embedder&&t.embed){let m=await this.store.getNodesByKinds([...Qr]),g=await this.store.getEmbeddingContentHashes(),y=[];for(let _ of m){let S=ca(_),v=Dn(`${this.embedder.recipeVersion}\0${S}`);g.get(_.nodeKey)!==v&&y.push({nodeKey:_.nodeKey,text:S,hash:v})}let b=64;for(let _=0;_<y.length;_+=b){let S=y.slice(_,_+b),v=await this.embedder.embedDocuments(S.map(R=>R.text));await this.store.upsertEmbeddings(S.map((R,G)=>({nodeKey:R.nodeKey,dim:this.embedder.dim,vec:v[G],contentHash:R.hash})));let E=Math.min(_+b,y.length);t.onProgress?.({path:"embedding symbols",done:E,total:y.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(zn,this.embedder.recipeVersion),await this.store.setMeta(Yn,this.embedder.model),await this.store.setMeta(Xn,String(this.embedder.dim))}await this.store.setMeta(rt,nt),await this.store.setMeta(Ji,String(n));let h=Nt(this.repoRoot);return h&&await this.store.setMeta(it,h),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(Ji);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(it),schemaVersion:await this.store.getMeta(rt),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=De(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({...Hc(c),score:a.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=De(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:da(i,l.vec)})).sort((l,u)=>u.score-l.score).slice(0,r),c=[];for(let l of a){let u=await this.store.getNode(l.nodeKey);u&&c.push({...Hc(u),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=De(n.maxDepth,3,5),o=De(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,u=new Set([t]),d=[t];for(let p=0;p<i&&d.length>0;p++){let f=[];for(let h of d){let m=await this.store.neighbors(h,r,a,o);for(let g of m){let y=`${g.srcKey} ${g.dstKey} ${g.kind}`;if(l.has(y))continue;if(l.add(y),c.push({srcKey:g.srcKey,dstKey:g.dstKey,kind:g.kind}),c.length>=o)return c;let b=r==="out"?g.dstKey:g.srcKey;u.has(b)||(u.add(b),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=$c(jc.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(De(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=va(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=De(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=Pn(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(Nt(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Pa(this.repoRoot,n,t)}async checkDivergence(t={}){return Pt(this.repoRoot,t)}async checkNumberCollisions(t={}){return Te(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Ie(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Ne(this.repoRoot,t)}async reviewDetectors(t={}){return Wi(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Pn(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Ra(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=Pc({paths:n,hunks:i,readUntracked:s(f=>this.readRepoFileHead(f,xa),"readUntracked")}),c=wa(n.keys()),l=De(t.limit,64,200),u=[],d=0,p=0;for(let f of c){let h=await this.store.getNodesByFile(f.path);if(h.length===0)continue;d++;let m=await this.store.getFile(f.path),g=this.readRepoFile(f.path),y=m!==null&&g!==null&&Dn(g)!==m.contentHash;y&&(p++,o==="full"&&(o="partial"));let b=n.get(f.path)??"modified",_=i.get(f.path);for(let S of h)u.push(Qh(S,b,_,y))}return u.sort((f,h)=>Uc(f.change)-Uc(h.change)||f.filePath.localeCompare(h.filePath)||f.startLine-h.startLine),{changedFiles:c.length,indexedFiles:d,staleFiles:p,symbols:u.slice(0,l),truncated:u.length>l,riskFlags:a,hunkCoverage:o,baseKind:t.since?"ref":"uncommitted",headSha:Nt(this.repoRoot),dirty:Ea(this.repoRoot),baseSha:t.since?On(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 $c(jc.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(Hc,"toHit");s(De,"clampLimit");s(Uc,"changeRank");s(Qh,"classifyReviewSymbol")});import{createRequire as Zh}from"node:module";function Kc(){return Gc("node:sqlite")}function ot(){if(Kt)return Kt;try{let{DatabaseSync:e}=Kc(),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(),Kt={ok:!0}}finally{t.close()}}catch(e){Kt={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Kt}function eg(e){let{DatabaseSync:t}=Kc(),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 tg(e){let t=Gc("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 ng(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Qn(e){let t=ng(),n=s(i=>{let o=i==="node:sqlite"?eg(e):tg(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=ot();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=ot();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 Gc,Kt,Zi=w(()=>{"use strict";Gc=Zh(import.meta.url);s(Kc,"loadBuiltin");Kt=null;s(ot,"probeBuiltinSqlite");s(eg,"openBuiltin");s(tg,"openBetter");s(ng,"backendOverride");s(Qn,"openSqliteDatabase")});function Zn(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 Bc,Bt,Wc=w(()=>{"use strict";Zi();Ut();Xi();s(Zn,"toNodeRow");Bc=400,Bt=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Qn(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Oc)}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?Zn(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Zn)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Zn)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Zn)}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=Lc(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
89
96
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
90
97
|
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
91
98
|
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
92
99
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
93
100
|
WHERE nodes_fts MATCH ?
|
|
94
|
-
ORDER BY score LIMIT ?`,a=this.db.prepare(o);return(n?a.all(i,n,r):a.all(i,r)).map(
|
|
101
|
+
ORDER BY score LIMIT ?`,a=this.db.prepare(o);return(n?a.all(i,n,r):a.all(i,r)).map(l=>({nodeKey:l.node_key,score:-l.score}))}async neighbors(t,n,r,i){let a=`SELECT src_key, dst_key, kind FROM edges WHERE ${n==="out"?"src_key":"dst_key"} = ?`,c=[t];return r&&r.length>0&&(a+=` AND kind IN (${r.map(()=>"?").join(",")})`,c.push(...r)),a+=" LIMIT ?",c.push(i),this.db.prepare(a).all(...c).map(u=>({srcKey:u.src_key,dstKey:u.dst_key,kind:u.kind}))}async countFiles(){return this.db.prepare("SELECT COUNT(*) AS c FROM files").get().c}async countNodes(){return this.db.prepare("SELECT COUNT(*) AS c FROM nodes").get().c}async countEdges(){return this.db.prepare("SELECT COUNT(*) AS c FROM edges").get().c}async kindDistribution(){return this.db.prepare("SELECT kind, COUNT(*) AS c FROM nodes GROUP BY kind ORDER BY c DESC").all().map(n=>({kind:n.kind,count:n.c}))}async languageDistribution(){return this.db.prepare("SELECT language, COUNT(*) AS c FROM files GROUP BY language ORDER BY c DESC").all().map(n=>({language:n.language,count:n.c}))}async topModulesByFanIn(t){return this.db.prepare(`SELECT n.file_path AS file_path, n.language AS language,
|
|
95
102
|
(SELECT COUNT(*) FROM nodes n2 WHERE n2.file_path = n.file_path) AS symbol_count,
|
|
96
103
|
(SELECT COUNT(*) FROM edges e WHERE e.src_key = n.node_key AND e.kind = 'imports') AS imports_out,
|
|
97
104
|
(SELECT COUNT(*) FROM edges e WHERE e.dst_key = n.node_key AND e.kind = 'imports') AS imports_in
|
|
98
105
|
FROM nodes n
|
|
99
106
|
WHERE n.kind = 'module'
|
|
100
107
|
ORDER BY imports_in DESC, symbol_count DESC
|
|
101
|
-
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+=
|
|
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+=Bc)for(let a of n.slice(o,o+Bc))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(
|
|
102
109
|
node_key, kind, name, qualified_name, file_path, language,
|
|
103
110
|
start_line, end_line, start_byte, end_byte, signature, doc
|
|
104
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)
|
|
@@ -108,26 +115,19 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
108
115
|
content_hash = excluded.content_hash,
|
|
109
116
|
mtime_ms = excluded.mtime_ms,
|
|
110
117
|
size = excluded.size,
|
|
111
|
-
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as ah}from"node:crypto";function et(e){return ah("sha256").update(e,"utf8").digest("hex")}function oc(e){return{node_key_hash:et(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:et(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?et(e.signature):null}}function sc(e){return{src_key_hash:et(e.srcKey),dst_key_hash:et(e.dstKey),kind:e.kind}}function ac(e,t,n){return{node_key_hash:et(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var cc=b(()=>{"use strict";s(et,"sha256");s(oc,"toCloudNode");s(sc,"toCloudEdge");s(ac,"toCloudEmbedding")});function yi(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function lc(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function lh(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var tt,nt,ch,wi=b(()=>{"use strict";Pt();cc();tt=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},nt=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(Qe),lastSyncedAt:lc(await this.store.getMeta(pi))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(oc),n=(await this.store.getAllEdges()).map(sc),r=await this.store.getMeta(Xe)??Ye,i=await this.store.getMeta(Qe),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},d=0,u=yi(t,this.chunk),l=yi(n,this.chunk*2),p=Math.max(1,u.length+l.length);for(let g of u)await this.post("/api/codebase/push",{...c,nodes:g,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:p});for(let g of l)await this.post("/api/codebase/push",{...c,nodes:[],edges:g}),this.cfg.onProgress?.({phase:"edges",done:++d,total:p});u.length===0&&l.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let f=t.map(g=>g.node_key_hash),h=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:f});this.cfg.onProgress?.({phase:"prune",done:p,total:p});let m=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(pi,String(Date.now())),i&&await this.store.setMeta(Ja,i),{nodes:t.length,edges:n.length,pruned:lh(h.nodes_deleted),embeddings:m,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),o=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(u=>ac(u,t.get(u.nodeKey)??"",n)).filter(u=>u.content_hash!==""&&o[u.node_key_hash]!==u.content_hash);if(a.length===0)return 0;let c=yi(a,ch),d=0;for(let u of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:u}),this.cfg.onProgress?.({phase:"embeddings",done:++d,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(Ln),n=await this.store.getMeta(jn),r=lc(await this.store.getMeta(Hn));if(!t||!n||!r)throw new tt("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 tt(`${n} failed (HTTP ${t.status})${o?`: ${o}`:""}`,t.status,o)}return i}},ch=250;s(yi,"chunkArray");s(lc,"numOrNull");s(lh,"numOr0")});var dc={};B(dc,{CodeIndexSync:()=>nt,DEFAULT_DB_RELPATH:()=>_i,SyncError:()=>tt,createCodeIndexSync:()=>uh,createNodeCodeIndex:()=>ki,openSqliteDatabase:()=>Un,probeBuiltinSqlite:()=>Ze});import{mkdirSync as dh}from"node:fs";import{posix as bi}from"node:path";function ki(e){let t=e.dbPath??bi.join(e.repoRoot,_i);dh(bi.dirname(t),{recursive:!0});let n=new Mt(t),r=new Sn;return new Dt({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function uh(e){let t=e.dbPath??bi.join(e.repoRoot,_i),n=e.projectKey??Es(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 Mt(t);return new nt(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var _i,vi=b(()=>{"use strict";xs();Ls();hi();ic();wi();wi();gi();_i=".maind/code-index.sqlite";s(ki,"createNodeCodeIndex");s(uh,"createCodeIndexSync")});import{execFileSync as uc}from"node:child_process";import{existsSync as pc,realpathSync as fc}from"node:fs";import{createRequire as ph}from"node:module";import{basename as fh,dirname as mh,isAbsolute as mc,join as hh,relative as hc,resolve as Gn,sep as gc}from"node:path";function yc(){let e=Ze();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return ph(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 wc(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 W(e=process.cwd()){try{let t=uc("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 _c(e,t=W(),n=process.cwd()){let r=mc(e)?[e]:[Gn(t,e),Gn(n,e)];for(let i of r){let o=mh(i);if(!pc(o))continue;let a;try{a=fc(o)}catch{continue}let c=kc(a);if(c===null)continue;let d=hc(c,hh(a,fh(i)));if(!d.startsWith(".."))return{repoRoot:c,repoRelPath:d.split(gc).join("/")}}return null}function Bn(e,t=W(),n=process.cwd()){let r=mc(e)?[e]:[Gn(t,e),Gn(n,e)];for(let i of r){if(!pc(i))continue;let o;try{o=fc(i)}catch{continue}let a=kc(o);if(a===null)continue;let c=hc(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(gc).join("/")}}return null}function kc(e){try{let t=uc("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 vc(){return ki({repoRoot:W()})}var bc,Ft=b(()=>{"use strict";vi();s(yc,"probeNativeStore");s(wc,"isNativeStoreUnavailable");bc="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(W,"resolveRepoRoot");s(_c,"resolveRepoRootForPath");s(Bn,"resolveRepoRootForDir");s(kc,"gitToplevelOf");s(vc,"defaultEngineFactory")});var Ic=b(()=>{"use strict"});import{readFileSync as bh}from"node:fs";import{join as Si}from"node:path";function xi(e){let t=new Set;for(let n of e.matchAll(_h))t.add(n[1]);return t}function Ri(e){return new Set([...e].map(t=>t.split("-")[0]))}function Mc(e){return e.split(`
|
|
112
|
-
`).
|
|
113
|
-
`)
|
|
114
|
-
`).
|
|
115
|
-
`).
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
`)
|
|
119
|
-
|
|
120
|
-
`).map(i=>i.trim()).filter(Boolean)}}function Jc(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 Hh(e){let t=_(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=$h(t);return n===e?null:n}function Uh(e,t,n){let r=Lh.dirname(t),o=[{path:Di(e,r,"config.toml"),source:"worktree"}],a=Hh(e);a&&o.push({path:Di(a,r,"config.toml"),source:"main_worktree"});for(let c of o)if(Pi(c.path))try{let d=Jc(Mh(c.path,"utf8"));if(d===null){n.push(`${c.path}: kein [db].port lesbar \u2014 Kandidat \xFCbersprungen`);continue}return{source:c.source,port:d}}catch{n.push(`${c.path}: nicht lesbar \u2014 Kandidat \xFCbersprungen`)}return{source:"missing"}}function Kh(e,t){let n=new Map,r=_(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=_(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||!Pi(a))continue;let c=Di(a,t);if(Pi(c))try{for(let d of Oh(c)){let u=Ve(d);u!==null&&!n.has(u)&&n.set(u,a)}}catch{}}return n}function Mi(e,t={}){let n=t.runPsql??Vc,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=[],d=[];for(let p of o){let f=Uh(e,p.dir,i),h=f.source==="missing"?null:Gc(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),m=t.remoteDbUrl!==void 0?Gc(n,t.remoteDbUrl,r):null,g=Bc({dir:p.dir,fileVersions:p.files.map(w=>w.version),config:f,ledger:h,siblingVersions:Kh(e,p.dir),remote:m});a.push(...g.findings),d.push(g.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:g.verdict,db:g.db})}let u=Wc(d),l={open:0,warn:1,info:2};return a.sort((p,f)=>l[p.status]-l[f.status]||p.id.localeCompare(f.id)),{ok:u==="in_sync",verdict:u,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var Oi,Vc,jh,zc=b(()=>{"use strict";J();Rt();Oi=54322;s(Bc,"evaluateLedgerProject");s(Wc,"deriveLedgerVerdict");Vc=s((e,t,n)=>{let r=Fh("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"),jh="select version from supabase_migrations.schema_migrations order by version";s(qc,"classifyLedgerError");s(Gc,"readLedger");s(Jc,"parseDbPort");s(Hh,"mainWorktreeRoot");s(Uh,"resolveConfig");s(Kh,"gatherSiblingVersions");s(Mi,"checkMigrationLedgerDrift")});var Yc,Ht=b(()=>{"use strict";Ic();hi();Gr();di();Zr();qr();oi();$c();li();Rt();Kc();zc();yn();jr();Pt();Yc="0.1.0"});import{execFile as il}from"node:child_process";import{randomUUID as Xh}from"node:crypto";function rg(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return $i.test(t)?t:Xh()}function Li(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function ig(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 og(e){return await new Promise(t=>{il("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(sg(r))})})}function sg(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 ag(){return await new Promise(e=>{il("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 cg(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function lg(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=$i.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(o=>{$i.test(o)&&(n=o.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var rl,ol,Qh,Zh,eg,tg,ng,$i,zn,ji=b(()=>{"use strict";Ge();rl=45e3,ol=3e4,Qh=5,Zh=120,eg=3e4,tg=15*6e4,ng=1500,$i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(rg,"resolveClientSessionId");s(Li,"autoAnnounceDisabled");s(ig,"autoWorkingPathsEnabled");zn=class{static{s(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;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??ee)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??ag,this.gitBranchObject=t.gitBranchObject??og,this.log=t.log??(i=>process.stderr.write(i+`
|
|
122
|
-
`)),this.machineLabel=cg(r?.machine_label),this.enabled=this.projectKey!==null&&!Li(n,r),this.workingPathsEnabled=ig(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??lg(n,rg(n))}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<rl||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<rl||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<Qh||(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,ng).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(eg*2**(this.consecutiveFailures-1),tg);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:Zh,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.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(og,"defaultGitBranchObject");s(sg,"normalizeObjectId");s(ag,"defaultGitBranch");s(cg,"normalizeMachineLabel");s(lg,"staticIdentity")});import{mkdirSync as sl,readdirSync as dl,readFileSync as dg,renameSync as al,statSync as ug,unlinkSync as ul,writeFileSync as cl}from"node:fs";import{homedir as pg}from"node:os";import{join as rt}from"node:path";function pl(){return rt(pg(),".maind","presence")}function fl(e,t){return rt(e,t)}function ml(e){let t=e.baseDir??pl(),n=fl(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(d,u){try{if(typeof d!="object"||d===null)return;let l=d;if(l.ok!==!0)return;let p={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:Array.isArray(l.peers)?l.peers:[],conflicts:Array.isArray(l.conflicts)?l.conflicts:[]};sl(n,{recursive:!0,mode:448}),c=rt(n,`${u.sessionId}.json`);let f=`${c}.tmp-${r}`;cl(f,JSON.stringify(p),{mode:384}),al(f,c),ll(n,a(),c)}catch{}},endSession(){try{c&&ul(c)}catch{}},markFailed(d,u){try{let l={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:[],conflicts:[],announce_error:d};sl(n,{recursive:!0,mode:448}),c=rt(n,`${u.sessionId}.json`);let p=`${c}.tmp-${r}`;cl(p,JSON.stringify(l),{mode:384}),al(p,c),ll(n,a(),c)}catch{}}}}function ll(e,t,n){try{for(let r of dl(e)){if(!r.endsWith(".json"))continue;let i=rt(e,r);if(i!==n)try{t-ug(i).mtimeMs>fg&&ul(i)}catch{}}}catch{}}function it(e,t=pl()){try{let n=fl(t,e),r=[];for(let i of dl(n))if(i.endsWith(".json"))try{let o=JSON.parse(dg(rt(n,i),"utf8")),a=mg(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function mg(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 fg,Yn=b(()=>{"use strict";fg=120*6e4;s(pl,"presenceSnapshotBaseDir");s(fl,"projectDir");s(ml,"createSnapshotStore");s(ll,"pruneStale");s(it,"readSnapshots");s(mg,"parseSnapshot")});import{execFileSync as hg}from"node:child_process";import{createHash as gg,randomUUID as yg}from"node:crypto";import{existsSync as wg,mkdirSync as bg,readdirSync as _g,readFileSync as kg,renameSync as vg,statSync as Hi,unlinkSync as gl,writeFileSync as Sg}from"node:fs";import{homedir as Eg}from"node:os";import{basename as xg,join as be}from"node:path";function ot(e){return be(e??be(Eg(),".maind","presence"),"identity")}function yl(e,t){if(e){let n=xg(e).replace(/\.jsonl$/i,"");if(Ut.test(n))return n.toLowerCase()}return t&&Ut.test(t)?t.toLowerCase():null}function wl(e){let t=e.nowMs??Date.now();bg(e.dir,{recursive:!0,mode:448});let n=be(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString()};Sg(r,JSON.stringify(i,null,2)+`
|
|
123
|
-
`,{mode:384}),vg(r,n),Ng(e.dir,t)}function bl(e,t,n,r=Date.now()){try{let i=Hi(be(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function _l(e,t){try{gl(be(e,`${t}.json`))}catch{}}function Ng(e,t){try{for(let n of _g(e))if(n.endsWith(".json"))try{let r=Hi(be(e,n));t-r.mtimeMs>Tg&&gl(be(e,n))}catch{}}catch{}}function Cg(e){return kl(e)?.file??null}function kl(e){let t=be(e.dir,`${e.agentPid}.json`);try{if(!wg(t))return null;let n=Hi(t);if(n.mtimeMs<e.bridgeStartMs-Ag)return null;let r=JSON.parse(kg(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Ut.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!Pg(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function hl(e){return e.replace(/\/+$/,"")}function Pg(e,t){let n=hl(e),r=hl(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function Dg(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=gg("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 Og(e){if(process.platform==="win32")return null;try{let t=hg("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function Mg(){try{return j()}catch{return null}}var Ut,Rg,Tg,Ag,Ig,Xn,Qn=b(()=>{"use strict";K();Ut=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Rg=8,Tg=48*60*6e4,Ag=6e4,Ig="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(ot,"identityDirPath");s(yl,"transcriptStemOf");s(wl,"writeAgentIdentityFile");s(bl,"identityFileStale");s(_l,"deleteAgentIdentityFile");s(Ng,"pruneIdentityDir");s(Cg,"readAgentIdentityFile");s(kl,"readAgentIdentityEntry");s(hl,"normDir");s(Pg,"sameSessionTree");s(Dg,"uuidV5");s(Og,"processStartTime");Xn=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??ot(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Ut.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??Mg)(),o=(t.ppidStart??Og)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=Dg(`${i}|${this.agentPid}|${o}|${t.projectKey}`,Ig),this.source="derived";return}this.id=yg(),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(!Ut.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>Rg&&this.aliases.shift())}activityAtMs(){return kl({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let t=Cg({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()});return t===null?null:t.transcript_stem.toLowerCase()}};s(Mg,"defaultDeviceId")});var Ui=b(()=>{"use strict"});import{createReadStream as Kg,existsSync as Gg}from"node:fs";import{stat as Bg}from"node:fs/promises";import{createInterface as Wg}from"node:readline";async function Ki(e){if(!e||!Gg(e))return null;let t;try{t=await Bg(e)}catch{return null}let n=0,r=0,i=0;return await new Promise(o=>{let a=Kg(e,{encoding:"utf-8"}),c=Wg({input:a});c.on("line",d=>{let u=d.trim();if(u){i++;try{let p=JSON.parse(u).message?.usage;if(!p)return;typeof p.input_tokens=="number"&&(n+=p.input_tokens),typeof p.output_tokens=="number"&&(r+=p.output_tokens)}catch{}}}),c.on("close",()=>{o({input_tokens:n,output_tokens:r,total_tokens:n+r,lines_seen:i,last_modified_ms:t.mtimeMs})}),c.on("error",()=>o(null)),a.on("error",()=>o(null))})}var Sl=b(()=>{"use strict";s(Ki,"summariseTranscript")});var El=b(()=>{"use strict"});function Zn(e){if(!e)return null;let t=null;for(let n of e.matchAll(qg)){let r=n[1].toLowerCase();Vg.has(r)&&(t=r)}return t}var Vg,qg,er=b(()=>{"use strict";Vg=new Set(["low","medium","high","xhigh","max"]),qg=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(Zn,"detectEffortLevel")});import{createReadStream as Jg,existsSync as zg}from"node:fs";import{createInterface as Yg}from"node:readline";function Kt(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function iy(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 Gi(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function oy(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
124
|
-
`)}function sy(e,t){let n=s(d=>new Set(d.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[o,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let d of o)a.has(d)&&c++;return c/o.size>=.8}function ay(e,t,n){return Xg.test(e)?{polarity:-1,magnitude:st.rework,kind:"rework"}:n&&Qg.test(e)?{polarity:-1,magnitude:st.correction,kind:"correction"}:Zg.test(e)?{polarity:1,magnitude:st.acceptance,kind:"acceptance"}:t!==null&&sy(t,e)?{polarity:-1,magnitude:st.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function cy(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:Rl}}async function Bi(e){let t=cy("");if(!e||!zg(e))return t;let n=[],r=new Map,i=null,o=!1,a=null;await new Promise(p=>{let f=Jg(e,{encoding:"utf-8"}),h=Yg({input:f}),m=s(g=>{let w=g.trim();if(!w)return;let y;try{y=JSON.parse(w)}catch{return}if(t.lines_seen++,!t.session_id){let T=y.sessionId??y.session_id;typeof T=="string"&&T&&(t.session_id=T)}y.type==="ai-title"&&typeof y.aiTitle=="string"&&y.aiTitle&&(t.ai_title=y.aiTitle),typeof y.slug=="string"&&y.slug&&(t.session_slug=y.slug);let k=y.message?.role,S=y.isSidechain===!0,v=y.message?.usage;if(k==="assistant"&&v&&(t.input_tokens+=Kt(v.input_tokens),t.output_tokens+=Kt(v.output_tokens),t.cache_read_tokens+=Kt(v.cache_read_input_tokens),t.cache_creation_tokens+=Kt(v.cache_creation_input_tokens)),k==="assistant"&&typeof y.message?.model=="string"&&y.message.model&&y.message.model!==ny){let T=y.timestamp?Date.parse(y.timestamp):Number.NaN;iy(r,y.message.model,S,Kt(v?.output_tokens),Number.isFinite(T)?T:0)}if(k==="assistant")for(let T of Gi(y.message?.content)){if(T.type!=="tool_use"||typeof T.name!="string"||!T.name.startsWith(xl))continue;let Y=T.name.slice(xl.length);Y&&(t.maind_tool_calls[Y]=(t.maind_tool_calls[Y]??0)+1)}if(S)return;if(k==="assistant"){t.assistant_turns++;let T=Gi(y.message?.content),Y=!1;for(let ko of T)ko.type==="tool_use"&&(t.tool_calls++,Y=!0,ko.name==="AskUserQuestion"&&t.agent_questions++);o=Y;return}if(k!=="user")return;let E=Gi(y.message?.content),R=oy(E);if(R.includes(ey)){t.interrupts++,n.push({polarity:-1,magnitude:st.interrupt,kind:"interrupt"});return}if(E.some(T=>T.type==="tool_result"&&T.is_error===!0&&typeof T.content=="string"&&T.content.includes(ty))){t.tool_denials++,n.push({polarity:-1,magnitude:st.denial,kind:"denial"});return}if(E.some(T=>T.type==="tool_result")||!R.trim())return;t.user_turns++,t.user_chars+=R.length;let A=Zn(R);A&&(i=A);let N=ay(R,a,o);a=R,N.kind==="correction"?t.corrections++:N.kind==="rework"?t.reworks++:N.kind==="repeat"?t.repeated_instructions++:N.kind==="acceptance"&&t.acceptances++,N.polarity!==0&&n.push(N),o=!1},"processLine");h.on("line",g=>{try{m(g)}catch{}}),h.on("close",()=>p()),h.on("error",()=>p()),f.on("error",()=>p())}),t.effort_at_end=i,t.model_mix=[...r.values()].sort((p,f)=>p.first_ts-f.first_ts||p.model.localeCompare(f.model)),t.user_token_estimate=Math.round(t.user_chars/4);let c=t.user_token_estimate+t.output_tokens;t.human_share=c>0?Number((t.user_token_estimate/c).toFixed(4)):0;let d=0,u=0,l=[];return n.forEach((p,f)=>{p.polarity>0?t.reactions_pos++:p.polarity<0&&t.reactions_neg++,d=d*ry+p.polarity*p.magnitude;let h=Number(d.toFixed(3));l.push({t:f,value:h,...p.kind!=="neutral"?{kind:p.kind}:{}}),u+=h,f>0&&n[f-1].polarity<0&&p.polarity>0&&t.recovery_events++}),t.net_sentiment=t.reactions_pos-t.reactions_neg,t.momentum_series=l,t.momentum_final=l.length?l[l.length-1].value:0,t.momentum_auc=Number(u.toFixed(3)),t.ended_positive=t.momentum_final>0,Object.keys(t.maind_tool_calls).length>0&&(t.maind_connected="connected"),t}var xl,Rl,Xg,Qg,Zg,ey,ty,ny,ry,st,Tl=b(()=>{"use strict";er();xl="mcp__maind__",Rl="2026-08-16",Xg=/(\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,Qg=/(\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,Zg=/(\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,ey="[Request interrupted by user",ty="The user doesn't want to proceed with this tool use",ny="<synthetic>",ry=.7,st={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(Kt,"num");s(iy,"bumpModel");s(Gi,"asBlocks");s(oy,"textOf");s(sy,"isRepeat");s(ay,"classifyGenuine");s(cy,"emptyAnalysis");s(Bi,"analyzeSession")});function Wi(e,t,n,r="unknown"){let i={session_analytics:{...e,ingest_source:r}};return t&&t.started_at&&(i.session_span=n?{...t,...n}:t),i}var Al=b(()=>{"use strict";s(Wi,"ingestBody")});import{createReadStream as ly,existsSync as dy}from"node:fs";import{createInterface as uy}from"node:readline";function Il(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function my(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
125
|
-
`)}function Pl(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 hy(e){let t=e.message?.role;if(t==="assistant")return{holder:Il(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Il(e.message?.content),r=my(n);return r.includes(py)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(fy))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Vi(e){let t=Pl("");if(!e||!dy(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(d=>{let u=ly(e,{encoding:"utf-8"}),l=uy({input:u}),p=s(f=>{let h=f.trim();if(!h)return;let m;try{m=JSON.parse(h)}catch{return}if(!t.session_id){let y=m.sessionId??m.session_id;typeof y=="string"&&y&&(t.session_id=y)}if(m.isSidechain===!0)return;let g=typeof m.timestamp=="string"?Date.parse(m.timestamp):NaN;if(!Number.isFinite(g)||o!==null&&g<o)return;let w=hy(m);if(w!==null){if(t.event_count++,w.genuine&&t.turn_count++,n===null&&(n=g),r=g,o!==null){let y=g-o;a==="agent"?i+=y:y>=Nl*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(y/1e3),c.length<Cl&&c.push({offset_seconds:Math.round((o-n)/1e3),duration_seconds:Math.round(y/1e3)}))}o=g,a=w.holder}},"processLine");l.on("line",f=>{try{p(f)}catch{}}),l.on("close",()=>d()),l.on("error",()=>d()),u.on("error",()=>d())}),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 py,fy,Nl,Cl,Dl=b(()=>{"use strict";py="[Request interrupted by user",fy="The user doesn't want to proceed with this tool use",Nl=60,Cl=200;s(Il,"asBlocks");s(my,"textOf");s(Pl,"emptySpan");s(hy,"classify");s(Vi,"analyzeSpan")});var Ol=b(()=>{"use strict";er();Ui()});var Ml=b(()=>{"use strict"});import{homedir as gy}from"node:os";import{join as yy}from"node:path";var wy,by,Fl=b(()=>{"use strict";wy=gy(),by=yy(wy,".claude","projects")});var qi=b(()=>{"use strict";Ui();Sl();El();Tl();Al();Dl();Ol();er();Ml();Fl()});function _y(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":j()}}async function $l(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:_y(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 tr,Ji=b(()=>{"use strict";K();tr=process.env.MAIND_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";s(_y,"ingestHeaders");s($l,"postMetrics")});function Ll(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function Hl(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 d=c;if(typeof d.path_prefix!="string")continue;let l=(typeof d.expires_in_seconds=="number"?d.expires_in_seconds:0)-t;l<=0||a.push({path_prefix:d.path_prefix,note:typeof d.note=="string"?d.note:null,remaining_seconds:Math.round(l)})}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 at(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 Gt(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function Ul(e,t,n){let r=n.maxAgeMs??jl,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,a=Hl(e,o),c=[];for(let d of a)if(!(n.via==="cwd"&&(n.currentBranch===null||d.branch===null||d.branch===n.currentBranch))){for(let u of d.claims)Ll(t,u.path_prefix)&&c.push(`'${u.path_prefix}' is CLAIMED by peer session ${d.session_id_short}${d.branch?` (branch ${d.branch}`:" ("}${d.machine_label?`, ${d.machine_label}`:""}${d.focus?`, focus: "${d.focus}"`:""}, last seen ${Gt(d.last_seen_seconds+o)} ago)${u.note?` \u2014 note: "${u.note}"`:""}, claim expires in ${Gt(u.remaining_seconds)}`);if(n.via==="ppid"&&d.is_own_user){for(let u of d.working_paths)if(Ll(t,u)){c.push(`'${u}' has recent changes by your own peer session ${d.session_id_short}${d.branch?` (branch ${d.branch})`:""}, last seen ${Gt(d.last_seen_seconds+o)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${Gt(o)} ago, advisory \u2014 never a lock):
|
|
126
|
-
`+c.map(d=>` \u2022 ${d}`).join(`
|
|
118
|
+
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as rg}from"node:crypto";function st(e){return rg("sha256").update(e,"utf8").digest("hex")}function Vc(e){return{node_key_hash:st(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:st(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?st(e.signature):null}}function qc(e){return{src_key_hash:st(e.srcKey),dst_key_hash:st(e.dstKey),kind:e.kind}}function Jc(e,t,n){return{node_key_hash:st(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var zc=w(()=>{"use strict";s(st,"sha256");s(Vc,"toCloudNode");s(qc,"toCloudEdge");s(Jc,"toCloudEmbedding")});function eo(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Yc(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function og(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var at,ct,ig,to=w(()=>{"use strict";Ut();zc();at=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},ct=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(it),lastSyncedAt:Yc(await this.store.getMeta(zi))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Vc),n=(await this.store.getAllEdges()).map(qc),r=await this.store.getMeta(rt)??nt,i=await this.store.getMeta(it),o=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(g=>[g.language,g.count])),c={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:o,lang_dist:a},l=0,u=eo(t,this.chunk),d=eo(n,this.chunk*2),p=Math.max(1,u.length+d.length);for(let g of u)await this.post("/api/codebase/push",{...c,nodes:g,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:p});for(let g of d)await this.post("/api/codebase/push",{...c,nodes:[],edges:g}),this.cfg.onProgress?.({phase:"edges",done:++l,total:p});u.length===0&&d.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let f=t.map(g=>g.node_key_hash),h=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:f});this.cfg.onProgress?.({phase:"prune",done:p,total:p});let m=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(zi,String(Date.now())),i&&await this.store.setMeta(Mc,i),{nodes:t.length,edges:n.length,pruned:og(h.nodes_deleted),embeddings:m,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),o=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(u=>Jc(u,t.get(u.nodeKey)??"",n)).filter(u=>u.content_hash!==""&&o[u.node_key_hash]!==u.content_hash);if(a.length===0)return 0;let c=eo(a,ig),l=0;for(let u of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:u}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(zn),n=await this.store.getMeta(Yn),r=Yc(await this.store.getMeta(Xn));if(!t||!n||!r)throw new at("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 at(`${n} failed (HTTP ${t.status})${o?`: ${o}`:""}`,t.status,o)}return i}},ig=250;s(eo,"chunkArray");s(Yc,"numOrNull");s(og,"numOr0")});var Xc={};W(Xc,{CodeIndexSync:()=>ct,DEFAULT_DB_RELPATH:()=>ro,SyncError:()=>at,createCodeIndexSync:()=>ag,createNodeCodeIndex:()=>io,openSqliteDatabase:()=>Qn,probeBuiltinSqlite:()=>ot});import{mkdirSync as sg}from"node:fs";import{posix as no}from"node:path";function io(e){let t=e.dbPath??no.join(e.repoRoot,ro);sg(no.dirname(t),{recursive:!0});let n=new Bt(t),r=new In;return new Gt({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function ag(e){let t=e.dbPath??no.join(e.repoRoot,ro),n=e.projectKey??Js(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 Bt(t);return new ct(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var ro,oo=w(()=>{"use strict";Jr();aa();Qi();Wc();to();to();Zi();ro=".maind/code-index.sqlite";s(io,"createNodeCodeIndex");s(ag,"createCodeIndexSync")});import{execFileSync as Qc}from"node:child_process";import{existsSync as Zc,realpathSync as el}from"node:fs";import{createRequire as cg}from"node:module";import{basename as lg,dirname as dg,isAbsolute as tl,join as ug,relative as nl,resolve as er,sep as rl}from"node:path";function il(){let e=ot();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return cg(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 q(e=process.cwd()){try{let t=Qc("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 al(e,t=q(),n=process.cwd()){let r=tl(e)?[e]:[er(t,e),er(n,e)];for(let i of r){let o=dg(i);if(!Zc(o))continue;let a;try{a=el(o)}catch{continue}let c=cl(a);if(c===null)continue;let l=nl(c,ug(a,lg(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(rl).join("/")}}return null}function tr(e,t=q(),n=process.cwd()){let r=tl(e)?[e]:[er(t,e),er(n,e)];for(let i of r){if(!Zc(i))continue;let o;try{o=el(i)}catch{continue}let a=cl(o);if(a===null)continue;let c=nl(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(rl).join("/")}}return null}function cl(e){try{let t=Qc("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 ll(){return io({repoRoot:q()})}var sl,Wt=w(()=>{"use strict";oo();s(il,"probeNativeStore");s(ol,"isNativeStoreUnavailable");sl="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(q,"resolveRepoRoot");s(al,"resolveRepoRootForPath");s(tr,"resolveRepoRootForDir");s(cl,"gitToplevelOf");s(ll,"defaultEngineFactory")});var gl=w(()=>{"use strict"});import{existsSync as so,readdirSync as hg,readFileSync as gg}from"node:fs";import{spawnSync as yg}from"node:child_process";import{dirname as bg,join as ao,posix as wg}from"node:path";function bl(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 ${co} 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 ${co} aus \u2014 die Silent-Redirect-Falle vom 2026-08-26.`,hint:"config.toml aus dem Haupt-Checkout in diesen Worktree kopieren, bevor irgendein `supabase \u2026`-Kommando l\xE4uft."});let r=e.ledger;if(r===null||r.ok===!1){n.reachable=r===null?null:!1;let p=r===null?"unreachable":r.reason,f=r!==null&&r.ok===!1?r.detail:void 0,m={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."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:m.title,detail:m.detailText,hint:m.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),o=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!i.has(p)).sort(de);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:"`npx supabase migration up` im Projektverzeichnis (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen.",versions:a});let c=r.versions.filter(p=>!o.has(p)).sort(de),l=new Map,u=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let h=l.get(f)??[];h.push(p),l.set(f,h)}else u.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(u.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${u.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${u.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:u}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),f=e.fileVersions.filter(m=>!p.has(m)).sort(de),h=e.remote.versions.filter(m=>!o.has(m)).sort(de);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}),h.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${h.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${h.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:h})}let d=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:d,findings:t,db:n}}function wl(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function kl(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,_g,n);return r.ok===!1?kl(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
|
|
120
|
+
`).map(i=>i.trim()).filter(Boolean)}}function vl(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 kg(e){let t=k(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=bg(t);return n===e?null:n}function vg(e,t,n){let r=wg.dirname(t),o=[{path:ao(e,r,"config.toml"),source:"worktree"}],a=kg(e);a&&o.push({path:ao(a,r,"config.toml"),source:"main_worktree"});for(let c of o)if(so(c.path))try{let l=vl(gg(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 Sg(e,t){let n=new Map,r=k(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=k(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||!so(a))continue;let c=ao(a,t);if(so(c))try{for(let l of hg(c)){let u=Ye(l);u!==null&&!n.has(u)&&n.set(u,a)}}catch{}}return n}function lo(e,t={}){let n=t.runPsql??_l,r=t.timeoutMs??15e3,i=[],o=Ae(e,t.dirs);if(o.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let a=[],c=[],l=[];for(let p of o){let f=vg(e,p.dir,i),h=f.source==="missing"?null:yl(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),m=t.remoteDbUrl!==void 0?yl(n,t.remoteDbUrl,r):null,g=bl({dir:p.dir,fileVersions:p.files.map(y=>y.version),config:f,ledger:h,siblingVersions:Sg(e,p.dir),remote:m});a.push(...g.findings),l.push(g.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:g.verdict,db:g.db})}let u=wl(l),d={open:0,warn:1,info:2};return a.sort((p,f)=>d[p.status]-d[f.status]||p.id.localeCompare(f.id)),{ok:u==="in_sync",verdict:u,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var co,_l,_g,Sl=w(()=>{"use strict";V();Ct();co=54322;s(bl,"evaluateLedgerProject");s(wl,"deriveLedgerVerdict");_l=s((e,t,n)=>{let r=yg("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"),_g="select version from supabase_migrations.schema_migrations order by version";s(kl,"classifyLedgerError");s(yl,"readLedger");s(vl,"parseDbPort");s(kg,"mainWorktreeRoot");s(vg,"resolveConfig");s(Sg,"gatherSiblingVersions");s(lo,"checkMigrationLedgerDrift")});var El,Vt=w(()=>{"use strict";gl();Qi();ri();qi();fi();ai();Ot();Vn();Lt();Ct();Wn();Sl();Ri();Vi();Ot();Lt();Vn();Wn();Sn();Zr();Ut();El="0.1.0"});import{execFile as Pl}from"node:child_process";import{randomUUID as Pg}from"node:crypto";function $g(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return po.test(t)?t:Pg()}function fo(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function jg(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 Hg(e){return await new Promise(t=>{Pl("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(Ug(r))})})}function Ug(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 Gg(){return await new Promise(e=>{Pl("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 Kg(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function Bg(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=po.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(o=>{po.test(o)&&(n=o.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var Cl,Dl,Dg,Og,Mg,Fg,Lg,po,sr,mo=w(()=>{"use strict";qe();Cl=45e3,Dl=3e4,Dg=5,Og=120,Mg=3e4,Fg=15*6e4,Lg=1500,po=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s($g,"resolveClientSessionId");s(fo,"autoAnnounceDisabled");s(jg,"autoWorkingPathsEnabled");sr=class{static{s(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;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??te)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??Gg,this.gitBranchObject=t.gitBranchObject??Hg,this.log=t.log??(i=>process.stderr.write(i+`
|
|
122
|
+
`)),this.machineLabel=Kg(r?.machine_label),this.enabled=this.projectKey!==null&&!fo(n,r),this.workingPathsEnabled=jg(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??Bg(n,$g(n))}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<Cl||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<Cl||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<Dg||(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,Lg).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(Mg*2**(this.consecutiveFailures-1),Fg);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:Og,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.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(Hg,"defaultGitBranchObject");s(Ug,"normalizeObjectId");s(Gg,"defaultGitBranch");s(Kg,"normalizeMachineLabel");s(Bg,"staticIdentity")});import{mkdirSync as Ol,readdirSync as $l,readFileSync as Wg,renameSync as Ml,statSync as Vg,unlinkSync as jl,writeFileSync as Fl}from"node:fs";import{homedir as qg}from"node:os";import{join as lt}from"node:path";function Hl(){return lt(qg(),".maind","presence")}function Ul(e,t){return lt(e,t)}function Gl(e){let t=e.baseDir??Hl(),n=Ul(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,o=e.cwd??process.cwd(),a=e.now??Date.now,c=null;return{write(l,u){try{if(typeof l!="object"||l===null)return;let d=l;if(d.ok!==!0)return;let p={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:Array.isArray(d.peers)?d.peers:[],conflicts:Array.isArray(d.conflicts)?d.conflicts:[]};Ol(n,{recursive:!0,mode:448}),c=lt(n,`${u.sessionId}.json`);let f=`${c}.tmp-${r}`;Fl(f,JSON.stringify(p),{mode:384}),Ml(f,c),Ll(n,a(),c)}catch{}},endSession(){try{c&&jl(c)}catch{}},markFailed(l,u){try{let d={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:[],conflicts:[],announce_error:l};Ol(n,{recursive:!0,mode:448}),c=lt(n,`${u.sessionId}.json`);let p=`${c}.tmp-${r}`;Fl(p,JSON.stringify(d),{mode:384}),Ml(p,c),Ll(n,a(),c)}catch{}}}}function Ll(e,t,n){try{for(let r of $l(e)){if(!r.endsWith(".json"))continue;let i=lt(e,r);if(i!==n)try{t-Vg(i).mtimeMs>Jg&&jl(i)}catch{}}}catch{}}function dt(e,t=Hl()){try{let n=Ul(t,e),r=[];for(let i of $l(n))if(i.endsWith(".json"))try{let o=JSON.parse(Wg(lt(n,i),"utf8")),a=zg(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function zg(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 Jg,ar=w(()=>{"use strict";Jg=120*6e4;s(Hl,"presenceSnapshotBaseDir");s(Ul,"projectDir");s(Gl,"createSnapshotStore");s(Ll,"pruneStale");s(dt,"readSnapshots");s(zg,"parseSnapshot")});import{execFileSync as Yg}from"node:child_process";import{createHash as Xg,randomUUID as Qg}from"node:crypto";import{existsSync as Zg,mkdirSync as ey,readdirSync as ty,readFileSync as ny,renameSync as ry,statSync as ho,unlinkSync as Bl,writeFileSync as iy}from"node:fs";import{homedir as oy}from"node:os";import{basename as sy,join as _e}from"node:path";function ut(e){return _e(e??_e(oy(),".maind","presence"),"identity")}function Wl(e,t){if(e){let n=sy(e).replace(/\.jsonl$/i,"");if(qt.test(n))return n.toLowerCase()}return t&&qt.test(t)?t.toLowerCase():null}function Vl(e){let t=e.nowMs??Date.now();ey(e.dir,{recursive:!0,mode:448});let n=_e(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString()};iy(r,JSON.stringify(i,null,2)+`
|
|
123
|
+
`,{mode:384}),ry(r,n),uy(e.dir,t)}function ql(e,t,n,r=Date.now()){try{let i=ho(_e(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function Jl(e,t){try{Bl(_e(e,`${t}.json`))}catch{}}function uy(e,t){try{for(let n of ty(e))if(n.endsWith(".json"))try{let r=ho(_e(e,n));t-r.mtimeMs>cy&&Bl(_e(e,n))}catch{}}catch{}}function py(e){return zl(e)?.file??null}function zl(e){let t=_e(e.dir,`${e.agentPid}.json`);try{if(!Zg(t))return null;let n=ho(t);if(n.mtimeMs<e.bridgeStartMs-ly)return null;let r=JSON.parse(ny(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!qt.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!fy(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function Kl(e){return e.replace(/\/+$/,"")}function fy(e,t){let n=Kl(e),r=Kl(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function my(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=Xg("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 hy(e){if(process.platform==="win32")return null;try{let t=Yg("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function gy(){try{return j()}catch{return null}}var qt,ay,cy,ly,dy,cr,lr=w(()=>{"use strict";K();qt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ay=8,cy=48*60*6e4,ly=6e4,dy="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(ut,"identityDirPath");s(Wl,"transcriptStemOf");s(Vl,"writeAgentIdentityFile");s(ql,"identityFileStale");s(Jl,"deleteAgentIdentityFile");s(uy,"pruneIdentityDir");s(py,"readAgentIdentityFile");s(zl,"readAgentIdentityEntry");s(Kl,"normDir");s(fy,"sameSessionTree");s(my,"uuidV5");s(hy,"processStartTime");cr=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??ut(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=qt.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??gy)(),o=(t.ppidStart??hy)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=my(`${i}|${this.agentPid}|${o}|${t.projectKey}`,dy),this.source="derived";return}this.id=Qg(),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(!qt.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>ay&&this.aliases.shift())}activityAtMs(){return zl({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let t=py({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()});return t===null?null:t.transcript_stem.toLowerCase()}};s(gy,"defaultDeviceId")});var go=w(()=>{"use strict"});import{createReadStream as Sy,existsSync as Ey}from"node:fs";import{stat as xy}from"node:fs/promises";import{createInterface as Ry}from"node:readline";async function yo(e){if(!e||!Ey(e))return null;let t;try{t=await xy(e)}catch{return null}let n=0,r=0,i=0;return await new Promise(o=>{let a=Sy(e,{encoding:"utf-8"}),c=Ry({input:a});c.on("line",l=>{let u=l.trim();if(u){i++;try{let p=JSON.parse(u).message?.usage;if(!p)return;typeof p.input_tokens=="number"&&(n+=p.input_tokens),typeof p.output_tokens=="number"&&(r+=p.output_tokens)}catch{}}}),c.on("close",()=>{o({input_tokens:n,output_tokens:r,total_tokens:n+r,lines_seen:i,last_modified_ms:t.mtimeMs})}),c.on("error",()=>o(null)),a.on("error",()=>o(null))})}var Xl=w(()=>{"use strict";s(yo,"summariseTranscript")});var Ql=w(()=>{"use strict"});function dr(e){if(!e)return null;let t=null;for(let n of e.matchAll(Ty)){let r=n[1].toLowerCase();Ay.has(r)&&(t=r)}return t}var Ay,Ty,ur=w(()=>{"use strict";Ay=new Set(["low","medium","high","xhigh","max"]),Ty=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(dr,"detectEffortLevel")});import{createReadStream as Iy,existsSync as Ny}from"node:fs";import{createInterface as Cy}from"node:readline";function Jt(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function jy(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 bo(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function Hy(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
124
|
+
`)}function Uy(e,t){let n=s(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[o,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of o)a.has(l)&&c++;return c/o.size>=.8}function Gy(e,t,n){return Py.test(e)?{polarity:-1,magnitude:pt.rework,kind:"rework"}:n&&Dy.test(e)?{polarity:-1,magnitude:pt.correction,kind:"correction"}:Oy.test(e)?{polarity:1,magnitude:pt.acceptance,kind:"acceptance"}:t!==null&&Uy(t,e)?{polarity:-1,magnitude:pt.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function Ky(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:ed}}async function wo(e){let t=Ky("");if(!e||!Ny(e))return t;let n=[],r=new Map,i=null,o=!1,a=null;await new Promise(p=>{let f=Iy(e,{encoding:"utf-8"}),h=Cy({input:f}),m=s(g=>{let y=g.trim();if(!y)return;let b;try{b=JSON.parse(y)}catch{return}if(t.lines_seen++,!t.session_id){let A=b.sessionId??b.session_id;typeof A=="string"&&A&&(t.session_id=A)}b.type==="ai-title"&&typeof b.aiTitle=="string"&&b.aiTitle&&(t.ai_title=b.aiTitle),typeof b.slug=="string"&&b.slug&&(t.session_slug=b.slug);let _=b.message?.role,S=b.isSidechain===!0,v=b.message?.usage;if(_==="assistant"&&v&&(t.input_tokens+=Jt(v.input_tokens),t.output_tokens+=Jt(v.output_tokens),t.cache_read_tokens+=Jt(v.cache_read_input_tokens),t.cache_creation_tokens+=Jt(v.cache_creation_input_tokens)),_==="assistant"&&typeof b.message?.model=="string"&&b.message.model&&b.message.model!==Ly){let A=b.timestamp?Date.parse(b.timestamp):Number.NaN;jy(r,b.message.model,S,Jt(v?.output_tokens),Number.isFinite(A)?A:0)}if(_==="assistant")for(let A of bo(b.message?.content)){if(A.type!=="tool_use"||typeof A.name!="string"||!A.name.startsWith(Zl))continue;let X=A.name.slice(Zl.length);X&&(t.maind_tool_calls[X]=(t.maind_tool_calls[X]??0)+1)}if(S)return;if(_==="assistant"){t.assistant_turns++;let A=bo(b.message?.content),X=!1;for(let zo of A)zo.type==="tool_use"&&(t.tool_calls++,X=!0,zo.name==="AskUserQuestion"&&t.agent_questions++);o=X;return}if(_!=="user")return;let E=bo(b.message?.content),R=Hy(E);if(R.includes(My)){t.interrupts++,n.push({polarity:-1,magnitude:pt.interrupt,kind:"interrupt"});return}if(E.some(A=>A.type==="tool_result"&&A.is_error===!0&&typeof A.content=="string"&&A.content.includes(Fy))){t.tool_denials++,n.push({polarity:-1,magnitude:pt.denial,kind:"denial"});return}if(E.some(A=>A.type==="tool_result")||!R.trim())return;t.user_turns++,t.user_chars+=R.length;let T=dr(R);T&&(i=T);let N=Gy(R,a,o);a=R,N.kind==="correction"?t.corrections++:N.kind==="rework"?t.reworks++:N.kind==="repeat"?t.repeated_instructions++:N.kind==="acceptance"&&t.acceptances++,N.polarity!==0&&n.push(N),o=!1},"processLine");h.on("line",g=>{try{m(g)}catch{}}),h.on("close",()=>p()),h.on("error",()=>p()),f.on("error",()=>p())}),t.effort_at_end=i,t.model_mix=[...r.values()].sort((p,f)=>p.first_ts-f.first_ts||p.model.localeCompare(f.model)),t.user_token_estimate=Math.round(t.user_chars/4);let c=t.user_token_estimate+t.output_tokens;t.human_share=c>0?Number((t.user_token_estimate/c).toFixed(4)):0;let l=0,u=0,d=[];return n.forEach((p,f)=>{p.polarity>0?t.reactions_pos++:p.polarity<0&&t.reactions_neg++,l=l*$y+p.polarity*p.magnitude;let h=Number(l.toFixed(3));d.push({t:f,value:h,...p.kind!=="neutral"?{kind:p.kind}:{}}),u+=h,f>0&&n[f-1].polarity<0&&p.polarity>0&&t.recovery_events++}),t.net_sentiment=t.reactions_pos-t.reactions_neg,t.momentum_series=d,t.momentum_final=d.length?d[d.length-1].value:0,t.momentum_auc=Number(u.toFixed(3)),t.ended_positive=t.momentum_final>0,Object.keys(t.maind_tool_calls).length>0&&(t.maind_connected="connected"),t}var Zl,ed,Py,Dy,Oy,My,Fy,Ly,$y,pt,td=w(()=>{"use strict";ur();Zl="mcp__maind__",ed="2026-08-16",Py=/(\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,Dy=/(\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,Oy=/(\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,My="[Request interrupted by user",Fy="The user doesn't want to proceed with this tool use",Ly="<synthetic>",$y=.7,pt={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(Jt,"num");s(jy,"bumpModel");s(bo,"asBlocks");s(Hy,"textOf");s(Uy,"isRepeat");s(Gy,"classifyGenuine");s(Ky,"emptyAnalysis");s(wo,"analyzeSession")});function _o(e,t,n,r="unknown"){let i={session_analytics:{...e,ingest_source:r}};return t&&t.started_at&&(i.session_span=n?{...t,...n}:t),i}var nd=w(()=>{"use strict";s(_o,"ingestBody")});import{createReadStream as By,existsSync as Wy}from"node:fs";import{createInterface as Vy}from"node:readline";function rd(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function zy(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
125
|
+
`)}function sd(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 Yy(e){let t=e.message?.role;if(t==="assistant")return{holder:rd(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=rd(e.message?.content),r=zy(n);return r.includes(qy)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(Jy))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function ko(e){let t=sd("");if(!e||!Wy(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(l=>{let u=By(e,{encoding:"utf-8"}),d=Vy({input:u}),p=s(f=>{let h=f.trim();if(!h)return;let m;try{m=JSON.parse(h)}catch{return}if(!t.session_id){let b=m.sessionId??m.session_id;typeof b=="string"&&b&&(t.session_id=b)}if(m.isSidechain===!0)return;let g=typeof m.timestamp=="string"?Date.parse(m.timestamp):NaN;if(!Number.isFinite(g)||o!==null&&g<o)return;let y=Yy(m);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>=id*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<od&&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{p(f)}catch{}}),d.on("close",()=>l()),d.on("error",()=>l()),u.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var qy,Jy,id,od,ad=w(()=>{"use strict";qy="[Request interrupted by user",Jy="The user doesn't want to proceed with this tool use",id=60,od=200;s(rd,"asBlocks");s(zy,"textOf");s(sd,"emptySpan");s(Yy,"classify");s(ko,"analyzeSpan")});var cd=w(()=>{"use strict";ur();go()});var ld=w(()=>{"use strict"});import{homedir as Xy}from"node:os";import{join as Qy}from"node:path";var Zy,eb,dd=w(()=>{"use strict";Zy=Xy(),eb=Qy(Zy,".claude","projects")});var vo=w(()=>{"use strict";go();Xl();Ql();td();nd();ad();cd();ur();ld();dd()});function tb(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":j()}}async function ud(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:tb(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 pr,So=w(()=>{"use strict";K();pr=process.env.MAIND_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";s(tb,"ingestHeaders");s(ud,"postMetrics")});function pd(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function md(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 ft(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 zt(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function hd(e,t,n){let r=n.maxAgeMs??fd,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,a=md(e,o),c=[];for(let l of a)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let u of l.claims)pd(t,u.path_prefix)&&c.push(`'${u.path_prefix}' is CLAIMED by peer session ${l.session_id_short}${l.branch?` (branch ${l.branch}`:" ("}${l.machine_label?`, ${l.machine_label}`:""}${l.focus?`, focus: "${l.focus}"`:""}, last seen ${zt(l.last_seen_seconds+o)} ago)${u.note?` \u2014 note: "${u.note}"`:""}, claim expires in ${zt(u.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let u of l.working_paths)if(pd(t,u)){c.push(`'${u}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${zt(l.last_seen_seconds+o)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${zt(o)} ago, advisory \u2014 never a lock):
|
|
126
|
+
`+c.map(l=>` \u2022 ${l}`).join(`
|
|
127
127
|
`)+`
|
|
128
|
-
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
|
|
129
|
-
${h}`:h}var
|
|
130
|
-
`),
|
|
128
|
+
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 gd(e,t,n,r=fd,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=md(e,a),l=i!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${i}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let u=c.reduce((m,g)=>m+g.claims.length,0),d=c.filter(m=>m.focus===null&&m.working_paths.length===0&&m.claims.length===0).length,p=u>0?`${u} active claim${u===1?"":"s"}`:"no active claims",f=d>0?`, ${d} presence-only`:"",h=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${zt(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
|
|
129
|
+
${h}`:h}var fd,Eo=w(()=>{"use strict";s(pd,"prefixConflict");fd=10*6e4;s(md,"parsePeers");s(ft,"selectOwnSnapshot");s(zt,"ageDisplay");s(hd,"adviseOnPath");s(gd,"sessionStartSummary")});async function I(){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 fr(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function re(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var ie=w(()=>{"use strict";s(I,"readHookInput");s(fr,"transcriptPathOf");s(re,"toolFilePathOf")});function mt(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function ke(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function yd(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}var ht=w(()=>{"use strict";s(mt,"denyPayload");s(ke,"advisoryPayload");s(yd,"postAdvisoryPayload")});import{realpathSync as nb}from"node:fs";import{basename as bd,dirname as wd,join as rb}from"node:path";function Me(e){let t=wd(e),n=[bd(e)];for(;;)try{let r=nb(t);return rb(r,...n.reverse())}catch{let r=wd(t);if(r===t)return e;n.push(bd(t)),t=r}}var mr=w(()=>{"use strict";s(Me,"realpathOfUnwritten")});import{mkdir as ib,readFile as ob,writeFile as sb,rename as ab}from"node:fs/promises";import{existsSync as kd}from"node:fs";import{homedir as cb}from"node:os";import{join as vd}from"node:path";function _d(){return{config:null,sessions:{},pending_metrics:[]}}async function F(){if(!kd(hr))return _d();try{let e=await ob(hr,"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)}
|
|
130
|
+
`),_d()}}async function oe(e){kd(Fe)||await ib(Fe,{recursive:!0,mode:448});let t=`${hr}.tmp`;await sb(t,JSON.stringify(e,null,2),{mode:384}),await ab(t,hr)}function xo(e){return e.thresholds??e.config?.thresholds??lb}var Fe,hr,lb,Le=w(()=>{"use strict";Fe=vd(cb(),".maind"),hr=vd(Fe,"state.json"),lb={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(_d,"emptyState");s(F,"loadState");s(oe,"saveState");s(xo,"resolveThresholds")});import{existsSync as db,realpathSync as ub,statSync as pb}from"node:fs";import{dirname as Sd,isAbsolute as fb,join as mb}from"node:path";function yb(e,t){let n=e.filter(i=>Ed.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let o=i.hint?`
|
|
131
131
|
\u2192 ${i.hint}`:"";return` \u2022 ${i.title}
|
|
132
132
|
${i.detail}${o}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
|
|
133
133
|
|
|
@@ -135,121 +135,121 @@ ${h}`:h}var jl,zi=b(()=>{"use strict";s(Ll,"prefixConflict");jl=10*6e4;s(Hl,"par
|
|
|
135
135
|
|
|
136
136
|
`)+`
|
|
137
137
|
|
|
138
|
-
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
|
|
138
|
+
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 bb(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function wb(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 Ro(e){let t=Sd(e);for(;;){try{if(pb(t).isDirectory())return t}catch{}let n=Sd(t);if(n===t)return t;t=n}}async function _b(e,t,n){let r=await n.load();if(bb(r,e,t))return null;wb(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=>Ed.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:hb,metric_value:1},{session_id:e,metric_key:gb,metric_value:o}),await n.save(a),yb(i,t)}async function xd(){try{let e=await I(),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=re(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=fb(r)?r:mb(i,r),a=db(o)?ub(o):Me(o),c=se(Ro(a)),l=await _b(n,c,{load:F,save:oe,check:s(async u=>(await Pt(u,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(ke(l)),0}catch{return 0}}var Ed,hb,gb,Ao=w(()=>{"use strict";Vt();Ke();ht();ie();mr();Le();Ed=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],hb="repo_health_hook_runs",gb="repo_health_hook_findings";s(yb,"formatRepoHealth");s(bb,"alreadySeen");s(wb,"markSeen");s(Ro,"nearestExistingDir");s(_b,"repoHealthForEdit");s(xd,"runOnRepoHealth")});import{existsSync as kb,readFileSync as vb,realpathSync as Sb}from"node:fs";import{isAbsolute as Ad,join as Td,posix as Eb,relative as xb,sep as Rb}from"node:path";function Rd(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function Cb(e,t){return{contracts:t.filter(r=>Rd(r.spec)===e||Rd(r.impl)===e).map(r=>r.id),theme:Ib.test(e),acl:Nb.test(e)}}function Pb(e){return e.contracts.length===0&&!e.theme&&!e.acl}function Db(e,t,n,r,i=Date.now()){let o=e.write_health_seen??{},a=o[t]??{},c=new Set(a[n]?.keys??[]),l=r.filter(u=>!c.has(u.key));if(l.length>0){for(let u of l)c.add(u.key);a[n]={at:new Date(i).toISOString(),keys:[...c]},o[t]=a,e.write_health_seen=o}return l}function Ob(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:
|
|
139
139
|
|
|
140
140
|
`+e.map(n=>` \u2022 ${n.line}`).join(`
|
|
141
141
|
`)+`
|
|
142
142
|
|
|
143
|
-
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
|
|
144
|
-
`)}}catch{}try{let r=
|
|
145
|
-
`)}}catch{}return 0}function
|
|
143
|
+
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 Mb(e,t){let n=xb(e,t);return!n||n.startsWith("..")||Ad(n)?null:n.split(Rb).join(Eb.sep)}function Fb(e){try{let t=vb(Td(e,jn),"utf8"),{manifest:n}=Kn(t);return n?.contracts??[]}catch{return[]}}async function Id(){try{let e=await I(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=re(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=Ad(r)?r:Td(i,r),a=kb(o)?Sb(o):Me(o),c=se(Ro(a)),l=Mb(c,a);if(l===null)return 0;let u=Cb(l,Fb(c));if(Pb(u))return 0;let d=[];if(u.contracts.length>0)try{let m=await Ne(c,{contracts:u.contracts});for(let g of m.findings)g.status==="open"&&d.push({key:`spec:${g.id}`,line:`spec-drift (${g.contract}): ${g.detail}`})}catch{}if(u.theme)try{let m=Pe(c);for(let g of m.findings)g.status==="open"&&d.push({key:`theme:${g.file}:${g.klass}`,line:`theme-class-drift: \`${g.klass}\` in ${g.file} \u2014 no token \`--color-${g.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(u.acl)try{let m=Ce(c);for(let g of m.findings)g.status==="open"&&d.push({key:`acl:${g.id}`,line:`table-acl-lint: \`${g.table}\` (created in ${g.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let p=await F(),f=Db(p,n,c,d);p.pending_metrics.push({session_id:n,metric_key:Ab,metric_value:1},{session_id:n,metric_key:Tb,metric_value:f.length}),await oe(p);let h=Ob(f,l);return h!==null&&process.stdout.write(yd(h)),0}catch{return 0}}var Ab,Tb,Ib,Nb,Nd=w(()=>{"use strict";Vt();Ke();ht();ie();Ao();mr();Le();Ab="write_health_hook_runs",Tb="write_health_hook_findings",Ib=/\.(tsx?|jsx?|css)$/,Nb=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(Rd,"declPath");s(Cb,"routesForPath");s(Pb,"routesAreEmpty");s(Db,"takeUnreported");s(Ob,"formatWriteHealth");s(Mb,"repoRelative");s(Fb,"readContracts");s(Id,"runOnWriteHealth")});var Gd={};W(Gd,{agentHostPidCandidates:()=>pe,closeTrackedSession:()=>Ld,effectiveConfig:()=>$e,grandparentPid:()=>jd,recordGuardSignals:()=>Fd,runFlush:()=>Qb,runHookStatus:()=>Zb,runOnFileEdit:()=>zb,runOnFileWrite:()=>Jb,runOnRepoHealth:()=>xd,runOnSessionStart:()=>Kb,runOnToolUse:()=>Vb,runOnWriteHealth:()=>Id,runSessionEndMetrics:()=>Io,runSyncConfig:()=>tw,writeIdentitySideChannel:()=>To});import{execFileSync as Pd}from"node:child_process";import{existsSync as br,readFileSync as Dd,realpathSync as Lb}from"node:fs";import{writeFile as $b}from"node:fs/promises";import{homedir as Od}from"node:os";import{isAbsolute as yr,join as Yt,relative as Md}from"node:path";function Fd(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 Ld(e,t,n=Date.now()){Gb(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 Gb(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>gr&&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>gr&&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>gr&&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>gr&&delete e.sessions[n]}}function $e(e){if(e.config)return e.config;let t=C();return t===null?null:{api_key:t,endpoint:pr}}function $d(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 Kb(){let e=await F();if($e(e)===null)return 0;let t=await I(),n=Ud(t);if(n===null)return 0;$d(e,n),await oe(e);try{To(t,n)}catch{}try{let r=L();if(r!==null){let i=dt(r),o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=ft(i,{hostPids:pe(),cwd:o}),c=gd(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+`
|
|
144
|
+
`)}}catch{}try{let r=At(Bb());if(Ur(r)&&wn(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).
|
|
145
|
+
`)}}catch{}return 0}function Bb(){try{let e=Yt(Od(),".claude","settings.json");return br(e)?Dd(e,"utf8"):null}catch{return null}}function To(e,t,n,r=ut()){let i=n??pe();if(i.length===0)return;let o=Wl(fr(e)||null,t);if(o===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd();for(let c of i)Vl({dir:r,agentPid:c,sessionId:t,transcriptStem:o,cwd:a})}function jd(){try{if(process.platform==="win32")return null;let e=Pd("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 pe(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=jd();return n!==null&&n>1&&n!==t&&e.push(n),e}async function Vb(){let e=await F();if($e(e)===null)return 0;let t=await I(),n=Ud(t)??"unknown",r=$d(e,n);r.tool_call_count+=1;try{let a=pe().filter(c=>ql(ut(),c,Wb));n!=="unknown"&&a.length>0&&To(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),Fd(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 yo(r.transcript_path);a&&(r.token_count=a.total_tokens,await Xb(e,r))}return await oe(e),0}function qb(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
|
|
146
146
|
`);return`${t.prefix}${e.number} is already taken:
|
|
147
147
|
${n}
|
|
148
148
|
|
|
149
149
|
Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
|
|
150
150
|
|
|
151
|
-
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
|
|
151
|
+
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 Jb(){try{let e=await I();if((e.tool_name??"")!=="Write")return 0;let t=re(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=yr(t)?t:Yt(n,t);if(br(r))return 0;let i=se(n),o=Md(i,Me(r));if(o.length===0||o.startsWith("..")||yr(o))return 0;let a=await Ie(i,o);return!a.taken||a.namespace===null||process.stdout.write(mt(qb(a,a.namespace))),0}catch{return 0}}async function zb(){try{let e=await I(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=re(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=yr(n)?n:Yt(r,n),o=L();if(o===null)return 0;let a=dt(o);if(a.length===0)return 0;let c=ft(a,{hostPids:pe(),cwd:r});if(c===null)return 0;let l=se(r),u=br(i)?Lb(i):Me(i),d=Md(l,u).replace(/\\/g,"/");if(d.length===0||d.startsWith("..")||yr(d))return 0;let p=hd(c.snap,d,{via:c.via,currentBranch:c.via==="cwd"?Yb(r):null,nowMs:Date.now()});return p===null||process.stdout.write(ke(p)),0}catch{return 0}}function Yb(e){try{let n=Pd("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 Xb(e,t){let n=xo(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 $b(Yt(Fe,`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)}
|
|
152
152
|
`)}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.
|
|
153
153
|
`):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.
|
|
154
|
-
`)}async function
|
|
155
|
-
`)}}async function
|
|
156
|
-
`),n.ok?0:1}async function
|
|
154
|
+
`)}async function Io(e){try{let t=await F(),n=$e(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Ld(t,r),await oe(t)),await Hd(n,Hb)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
|
|
155
|
+
`)}}async function Qb(){let e=await F(),t=$e(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 Hd(t,Ub);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
156
|
+
`),n.ok?0:1}async function Hd(e,t){let n=await F();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=ud(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 F();return c.pending_metrics=c.pending_metrics.slice(r.length),await oe(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 Zb(){let e=await F(),t=$e(e),n=ew(),r=Ur(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:xo(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})),...wn(n.findings)?{remedy:Cd}:{}}},null,2)+`
|
|
157
157
|
`),r){process.stderr.write(`
|
|
158
158
|
[maind] Claude Code hook wiring is incomplete:
|
|
159
159
|
`);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
|
|
160
|
-
`);
|
|
161
|
-
`)}return 0}function
|
|
160
|
+
`);wn(n.findings)&&process.stderr.write(` ${Cd}
|
|
161
|
+
`)}return 0}function ew(){let e=Yt(Od(),".claude","settings.json"),t=null;try{br(e)&&(t=Dd(e,"utf8"))}catch{}return{settingsPath:e,findings:At(t)}}async function tw(){let e=await F(),t=$e(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??jb,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)}
|
|
162
162
|
`),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
|
|
163
163
|
`);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
|
|
164
164
|
`),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
|
|
165
165
|
`),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
|
|
166
|
-
`),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
|
|
167
|
-
`),0)}function
|
|
168
|
-
`)}return await
|
|
169
|
-
`,384)}var
|
|
170
|
-
`),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},o=[];for(let
|
|
171
|
-
`);let a=o.some(
|
|
166
|
+
`),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 oe(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
|
|
167
|
+
`),0)}function Ud(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var jb,Hb,Ub,gr,Wb,Cd,No=w(()=>{"use strict";vo();Vt();Ke();K();Tt();ar();me();So();Eo();lr();ie();ht();mr();Le();Ao();Nd();jb=process.env.MAIND_THRESHOLDS_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds",Hb=1500,Ub=1e4,gr=7*24*60*60*1e3;s(Fd,"recordGuardSignals");s(Ld,"closeTrackedSession");s(Gb,"gcState");s($e,"effectiveConfig");s($d,"getOrCreateSession");s(Kb,"runOnSessionStart");s(Bb,"readSettingsRaw");s(To,"writeIdentitySideChannel");Wb=6e4;s(jd,"grandparentPid");s(pe,"agentHostPidCandidates");s(Vb,"runOnToolUse");s(qb,"denyReason");s(Jb,"runOnFileWrite");s(zb,"runOnFileEdit");s(Yb,"currentGitBranch");s(Xb,"maybeEmitAdvisory");s(Io,"runSessionEndMetrics");s(Qb,"runFlush");s(Hd,"flushPending");s(Zb,"runHookStatus");Cd="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(ew,"readHookWiring");s(tw,"runSyncConfig");s(Ud,"sessionIdOf")});function Kd(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Bd=w(()=>{"use strict";s(Kd,"resolveConnection")});var Wd={};W(Wd,{runOnSessionEnd:()=>sw});function rw(e,t){try{let n=L(),r=n!==null&&!fo(process.env,te()),i=null;if(n!==null){let o=ft(dt(n),{hostPids:pe(),cwd:process.cwd()});if(o){let a=Date.parse(o.snap.written_at);i=Number.isFinite(a)?Math.max(0,t-a):null}}return Kd({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function iw(){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=L();if(n!==null){let i=ft(dt(n),{hostPids:pe(),cwd:process.cwd()})?.snap.own_session_id??null;if(i!==null&&e.test(i))return i.toLowerCase()}}catch{}let t=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return e.test(t)?t:null}async function ow(e,t,n,r){let i=fetch(nw,{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(()=>{}).catch(()=>{}),o=new Promise(a=>setTimeout(a,r));await Promise.race([i,o])}async function sw(){try{for(let i of pe())Jl(ut(),i)}catch{}let e=C();if(!e)return 0;let t=await I(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=fr(t);if(r)try{let[i,o]=await Promise.all([wo(r),ko(r)]);if(n&&(i.session_id=n,o.session_id=n),i.maind_connected=rw(i.maind_connected==="connected",Date.now()),i.session_id){let a=_o(i,o,{client_session_id:iw(),client:"claude-code"},"live_bridge");await ow(e,j(),a,1500)}}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
|
|
168
|
+
`)}return await Io(n),0}var nw,Vd=w(()=>{"use strict";vo();qe();K();So();Eo();ie();No();mo();ar();me();lr();Ee();Bd();nw=pr;s(rw,"connectionVerdict");s(iw,"presenceSessionId");s(ow,"postWithTimeout");s(sw,"runOnSessionEnd")});function Y(e=process.env,t=te()){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 gt(e,t=le()){let n={};try{let i=await H(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 O(t,JSON.stringify(r,null,2)+`
|
|
169
|
+
`,384)}var je=w(()=>{"use strict";qe();ae();s(Y,"resolveGuardConfig");s(gt,"writeGuardConfig")});function aw(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 qd(e,t,n=process.stdout){let r=aw(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
|
|
170
|
+
`),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 bn)o.push(await Wr(i,l));for(let l of o)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
|
|
171
|
+
`);let a=o.some(l=>l.detail==="user declined"),c=o.some(l=>l.status==="failed");return r.dryRun?(n.write(`
|
|
172
172
|
[dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
|
|
173
|
-
`),0):(await
|
|
173
|
+
`),0):(await gt({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
|
|
174
174
|
Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
|
|
175
175
|
flip: maind-mcp-bridge guard mode <warn|block>
|
|
176
176
|
disable: maind-mcp-bridge guard off (hooks stay wired, become no-ops)
|
|
177
177
|
check: maind-mcp-bridge guard status
|
|
178
178
|
Takes effect for NEW Claude Code sessions (hooks are read at session start).
|
|
179
179
|
`),a&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
|
|
180
|
-
`),c?1:0)}var
|
|
181
|
-
`;await
|
|
182
|
-
`);for(let
|
|
183
|
-
`),1):(await
|
|
184
|
-
`),0)}case"off":return await
|
|
180
|
+
`),c?1:0)}var Jd=w(()=>{"use strict";Tt();Vr();je();s(aw,"parseGuardInstallFlags");s(qd,"runGuardInstall")});import{existsSync as zd}from"node:fs";import{mkdir as cw,readFile as lw,readdir as dw,rename as uw,stat as pw,unlink as fw,writeFile as mw}from"node:fs/promises";import{join as wr}from"node:path";function Yd(e){return wr(Xt,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function fe(e){try{let t=Yd(e);if(!zd(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 cw(Xt,{recursive:!0,mode:448});let n=Yd(e),r=`${n}.tmp`;await mw(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await uw(r,n)}async function Xd(e=7*24*60*60*1e3,t=Date.now()){try{if(!zd(Xt))return;for(let n of await dw(Xt)){if(!n.endsWith(".json"))continue;let r=wr(Xt,n);try{let i=await pw(r);t-i.mtimeMs>e&&await fw(r)}catch{}}}catch{}}var yt,Xt,bt=w(()=>{"use strict";Le();yt=wr(Fe,"guard"),Xt=wr(yt,"sessions");s(Yd,"sessionFile");s(fe,"loadGuardSession");s(J,"saveGuardSession");s(Xd,"sweepOldGuardSessions")});import{existsSync as hw}from"node:fs";import{appendFile as gw,mkdir as yw,open as bw}from"node:fs/promises";import{join as ww}from"node:path";async function B(e){try{await yw(yt,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
|
|
181
|
+
`;await gw(wt,t,{mode:384})}catch{}}async function Qd(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(wt))return t;let n=await bw(wt,"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(`
|
|
182
|
+
`);for(let l of i>0?c.slice(1):c)if(l.trim())try{let u=JSON.parse(l);typeof u.event=="string"&&u.event in t&&(t[u.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var wt,_t=w(()=>{"use strict";bt();wt=ww(yt,"events.jsonl");s(B,"appendGuardEvent");s(Qd,"readGuardEventCounts")});var eu={};W(eu,{runGuard:()=>Ew});import{existsSync as _w,readFileSync as kw}from"node:fs";import{homedir as Zd}from"node:os";import{join as vw}from"node:path";async function Ew(e){let t=e[0],n=e.slice(1);switch(t){case"install":return qd(n,Zd());case"status":return Rw();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
|
|
183
|
+
`),1):(await gt({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
184
|
+
`),0)}case"off":return await gt({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
|
|
185
185
|
`),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>
|
|
186
|
-
`),1):(await
|
|
187
|
-
`),0)}case"skip":return
|
|
188
|
-
`),1;let r=n.trim().slice(0,500),i=await
|
|
189
|
-
logged (auditable) in ${
|
|
190
|
-
`),0}async function
|
|
186
|
+
`),1):(await gt({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
187
|
+
`),0)}case"skip":return xw(n);default:return process.stdout.write(Sw),t===void 0||t==="--help"||t==="-h"?0:1}}async function xw(e){let t=null,n=null;for(let o=0;o<e.length;o++)e[o]==="--session"?t=e[++o]??null:e[o]==="--reason"&&(n=e[++o]??null);if(!t||!n||n.trim().length===0)return process.stdout.write(`usage: maind-mcp-bridge guard skip --session <id> --reason "<why consultation is unnecessary here>"
|
|
188
|
+
`),1;let r=n.trim().slice(0,500),i=await fe(t);return await J(t,{...i,override_reason:r}),await B({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.
|
|
189
|
+
logged (auditable) in ${wt}
|
|
190
|
+
`),0}async function Rw(){let e=Y(),t=vw(Zd(),".claude","settings.json"),n=null;try{_w(t)&&(n=kw(t,"utf8"))}catch{}let r=At(n,{},bn),i=await Qd();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:wt},null,2)+`
|
|
191
191
|
`);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(`
|
|
192
192
|
[maind] guard hook wiring is incomplete:
|
|
193
193
|
`);for(let a of o)process.stderr.write(` \u2022 ${a.detail}
|
|
194
|
-
`);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
|
|
195
|
-
`);s(
|
|
196
|
-
`).trim();i=[],c.length>0&&(o=c)},"flush");for(;;){let{value:c,done:
|
|
197
|
-
`))!==-1;){let
|
|
198
|
-
`),0):(process.stdout.write(
|
|
194
|
+
`);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 Sw,tu=w(()=>{"use strict";Tt();je();Jd();_t();bt();Sw=["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(`
|
|
195
|
+
`);s(Ew,"runGuard");s(xw,"runGuardSkip");s(Rw,"runGuardStatus")});async function nu(e){return Qt("get_session_briefing",{tools:["claude-code"]},e)}async function Qt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??Co,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:Aw,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),l=c.headers.get("mcp-session-id");if(await c.text().catch(()=>""),!c.ok||!l)return null;let u={...a,"mcp-session-id":l};await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(g=>g.text().catch(()=>"")).catch(()=>"");let d=await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!d.ok)return null;let f=(d.headers.get("content-type")??"").startsWith("text/event-stream")?await Tw(d):await d.text();if(f.trim().length===0)return null;let h=JSON.parse(f);if(h.error||h.result?.isError)return null;let m=h.result?.content?.find(g=>g.type==="text"&&typeof g.text=="string")?.text;return typeof m=="string"&&m.trim().length>0?m:null}catch{return null}finally{clearTimeout(o)}}async function Tw(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(`
|
|
196
|
+
`).trim();i=[],c.length>0&&(o=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let u;for(;(u=r.indexOf(`
|
|
197
|
+
`))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let p=d.endsWith("\r")?d.slice(0,-1):d;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return a(),o}var Co,Aw,_r=w(()=>{"use strict";Co="https://mcp.maind.dev/mcp",Aw="2025-06-18";s(nu,"fetchSessionBriefing");s(Qt,"fetchToolText");s(Tw,"readSseMessage")});var au={};W(au,{BRIEFING_CACHE_FILE:()=>iu,formatInjection:()=>su,resolveBriefingInjection:()=>ou,runGuardInject:()=>$w});import{existsSync as Iw}from"node:fs";import{mkdir as Nw,readFile as Cw,rename as Pw,writeFile as Dw}from"node:fs/promises";import{dirname as Ow,join as Mw}from"node:path";async function ou(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??iu,o=n.fetcher??nu,a=await jw(i);if(a!==null&&r-Date.parse(a.fetched_at)<Fw&&a.project_key===e)return{text:a.text,via:"cache"};let l=await o({apiKey:t,deviceId:Uw(),projectKey:e,bridgeVersion:P,timeoutMs:Lw});return l!==null?(await Hw(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 $w(){try{if(Y().mode==="off")return 0;let t=await I(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;await Xd();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let u=await fe(n);return await J(n,{...u,carryover:!0}),0}let i=C();if(i===null)return 0;let o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=L(),c=await ou(a,i),l=await fe(n);return c.text===null?(await J(n,{...l,inject_failed:!0}),await B({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.
|
|
198
|
+
`),0):(process.stdout.write(su(c.text,c.via)),await J(n,{...l,injected:!0}),await B({event:"inject_ok",session_id:n,cwd:o,project_key:a??void 0,detail:c.via}),0)}catch{return 0}}function su(e,t){let n=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=e;return Buffer.byteLength(r,"utf8")>ru&&(r=r.slice(0,ru)+`
|
|
199
199
|
\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:
|
|
200
200
|
|
|
201
201
|
`+r+`
|
|
202
|
-
`}async function
|
|
202
|
+
`}async function jw(e){try{if(!Iw(e))return null;let t=JSON.parse(await Cw(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 Hw(e,t){try{await Nw(Ow(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await Dw(n,JSON.stringify(t,null,2),{mode:384}),await Pw(n,e)}catch{}}function Uw(){try{return j()}catch{return null}}var iu,Fw,Lw,ru,cu=w(()=>{"use strict";K();ie();me();Ee();je();_t();bt();_r();iu=Mw(yt,"briefing-cache.json"),Fw=12*60*60*1e3,Lw=3e3,ru=10*1024;s(ou,"resolveBriefingInjection");s($w,"runGuardInject");s(su,"formatInjection");s(jw,"readCache");s(Hw,"writeCache");s(Uw,"safeDeviceId")});var pu={};W(pu,{decideGate:()=>uu,runGuardGate:()=>Kw});function uu(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:lu(n)}:(n.deny_count??0)>=du?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. "+lu(n)}:{kind:"deny",reason:Gw(e.sessionId,n)}}function lu(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 Gw(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:
|
|
203
203
|
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
204
204
|
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
|
|
205
|
-
After ${
|
|
206
|
-
`,{mode:384}),await
|
|
207
|
-
`).filter(r=>r.trim());if(t.length<=
|
|
205
|
+
After ${du} denies this gate downgrades itself to warn.`}async function Kw(){try{let e=Y();if(e.mode==="off")return 0;let t=await I(),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 fe(r),o=(await F()).guard_signals?.[r]?.consulted_at!==void 0,a=uu({mode:e.mode,session:i,consulted:o,sessionId:r}),c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),l=L()??void 0;return a.kind==="deny"?(process.stdout.write(mt(a.reason)),await J(r,{...i,deny_count:(i.deny_count??0)+1}),await B({event:"deny",session_id:r,cwd:c,project_key:l}),0):a.kind==="warn"?(process.stdout.write(ke(a.context)),await J(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await B({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 du,fu=w(()=>{"use strict";ie();ht();Le();me();je();_t();bt();du=3;s(uu,"decideGate");s(lu,"warnText");s(Gw,"denyText");s(Kw,"runGuardGate")});var hu={};W(hu,{decideStopGate:()=>mu,runGuardStop:()=>Ww});function mu(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function Ww(){try{let e=Y();if(e.mode==="off"||!e.stopGate)return 0;let t=await I(),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 fe(n),i=(await F()).guard_signals?.[n]?.reviewed_at!==void 0;return mu({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:Bw})),await J(n,{...r,stop_blocked:!0}),await B({event:"stop_block",session_id:n})),0}catch{return 0}}var Bw,gu=w(()=>{"use strict";ie();Le();je();_t();bt();s(mu,"decideStopGate");Bw="[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(Ww,"runGuardStop")});import{appendFile as Vw,mkdir as qw,readFile as bu,rename as wu,writeFile as _u}from"node:fs/promises";import{homedir as ku}from"node:os";import{join as vu}from"node:path";function Su(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},o=new Map,a=1/0,c=-1/0;for(let u of e){u.at<a&&(a=u.at),u.at>c&&(c=u.at);let d=i[u.tool]??={calls:0,warns:0,denies:0};if(u.event==="tool_call"?d.calls+=1:u.event==="policy_warn"||u.event==="sha_warn"?d.warns+=1:d.denies+=1,(u.event==="policy_warn"||u.event==="policy_deny")&&u.convention_id!==void 0&&u.convention_version!==void 0){let p=o.get(u.convention_id);(p===void 0||u.convention_version>p)&&o.set(u.convention_id,u.convention_version)}}let l=Object.entries(i).sort((u,d)=>d[1].calls+d[1].warns+d[1].denies-(u[1].calls+u[1].warns+u[1].denies)).slice(0,64);return{window_start:new Date(a).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...o.entries()].slice(0,32).map(([u,d])=>({convention_id:u,convention_version:d})),...r?{project_key:r}:{}}}function He(){return vu(ku(),".maind","gateway","attest-spool.jsonl")}async function Po(e){let t=C();if(t===null)return!1;let n=await Qt("gateway_attest",{...e},{apiKey:t,deviceId:j(),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 Eu(e){try{await qw(vu(ku(),".maind","gateway"),{recursive:!0}),await Vw(He(),JSON.stringify(e)+`
|
|
206
|
+
`,{mode:384}),await Jw()}catch{}}async function Jw(){try{let t=(await bu(He(),"utf8")).split(`
|
|
207
|
+
`).filter(r=>r.trim());if(t.length<=yu)return;let n=`${He()}.${process.pid}.tmp`;await _u(n,t.slice(-yu).join(`
|
|
208
208
|
`)+`
|
|
209
|
-
`,{mode:384}),await
|
|
210
|
-
`).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
|
|
209
|
+
`,{mode:384}),await wu(n,He())}catch{}}async function xu(){let e;try{e=(await bu(He(),"utf8")).split(`
|
|
210
|
+
`).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 Po(i)||(n=!0,t.push(r))}try{let r=`${He()}.${process.pid}.tmp`;await _u(r,t.length>0?t.join(`
|
|
211
211
|
`)+`
|
|
212
|
-
`:"",{mode:384}),await
|
|
213
|
-
`,384)}async function
|
|
214
|
-
`),2;let n=
|
|
215
|
-
`);continue}let a
|
|
216
|
-
`);continue}if(!(t.yes||await
|
|
212
|
+
`:"",{mode:384}),await wu(r,He())}catch{}}var yu,Ru=w(()=>{"use strict";K();_r();Ee();yu=256;s(Su,"aggregateWindow");s(He,"attestSpoolPath");s(Po,"postAttestation");s(Eu,"spoolAttestation");s(Jw,"capSpool");s(xu,"flushAttestSpool")});function Zt(e=process.env,t=te()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function kr(e=process.env,t=te()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function Au(e,t=le()){let n={};try{let i=await H(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 O(t,JSON.stringify(r,null,2)+`
|
|
213
|
+
`,384)}async function Tu(e,t=le()){await Au({gateway_mode:e},t)}async function Iu(e,t=le()){await Au({gateway_attest:e},t)}function Nu(e=process.env,t=te()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var Do=w(()=>{"use strict";qe();ae();s(Zt,"resolveGatewayMode");s(kr,"resolveGatewayAttest");s(Au,"writeGatewayConfigPatch");s(Tu,"writeGatewayMode");s(Iu,"writeGatewayAttest");s(Nu,"resolveShaProofMode")});function Pu(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,o=i.gateway_gate;if(typeof o!="object"||o===null)continue;let a=o;if(a.enabled!==!0)continue;let c=typeof i.id=="string"&&i.id.length>0&&i.id.length<=64?i.id:null,l=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||l===null)continue;let u=typeof i.severity=="string"&&zw.has(i.severity)?i.severity:"recommended",d=typeof i.summary=="string"?i.summary:"",p=Array.isArray(a.servers)?a.servers.filter(h=>typeof h=="string"&&h.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(h=>typeof h=="string"&&h.length>0):[];for(let h of f){if(n.length>=256)return n;n.push({tool:h,servers:p,conventionId:c,conventionVersion:l,severity:u,summary:d})}}return n}function Yw(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Du(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let o of n)Yw(o,e,t)&&(i===null||Cu[o.severity]>Cu[i.severity])&&(i=o);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function Ou(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 zw,Cu,Oo=w(()=>{"use strict";zw=new Set(["required","recommended","info"]);s(Pu,"extractGatewayRules");Cu={required:2,recommended:1,info:0};s(Yw,"ruleMatches");s(Du,"decideToolCall");s(Ou,"policyDenyText")});import{mkdirSync as Xw,readFileSync as Qw,renameSync as Zw,writeFileSync as e_}from"node:fs";import{homedir as t_}from"node:os";import{dirname as n_,join as r_}from"node:path";function Mu(){return r_(t_(),".maind","gateway","policy-cache.json")}function vr(e,t,n=new Date().toISOString()){try{let r={version:Mo,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=Mu();Xw(n_(i),{recursive:!0});let o=`${i}.${process.pid}.tmp`;e_(o,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),Zw(o,i)}catch{}}function Sr(e){try{let t=Qw(Mu(),"utf8"),n=JSON.parse(t);return n.version!==Mo||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:Mo,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var Mo,Fo=w(()=>{"use strict";Mo=1;s(Mu,"policyCachePath");s(vr,"writePolicyCache");s(Sr,"readPolicyCache")});function en(e=process.env){let t=e.MAIND_MCP_URL??Co,n=C();return{mcpUrl:t,keyFp:n?on(n):"anon"}}async function Er(e=6e3){let t=C();if(t===null)return null;let n=null;try{n=L()}catch{n=null}let r=await Qt("get_conventions",{},{apiKey:t,deviceId:j(),projectKey:n,bridgeVersion:P,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return Pu(i)}var Lo=w(()=>{"use strict";Ke();K();_r();me();Ee();Oo();s(en,"policyIdentity");s(Er,"fetchGatewayRules")});function tn(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 i_(e){if(tn(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 o_(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:tn(e)?{action:"skip",reason:"already-wrapped"}:i_(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Fu(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 Lu(e){if(!tn(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 $u(e){return Object.entries(e).map(([t,n])=>{let r=o_(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var ju=w(()=>{"use strict";s(tn,"isGatewayWrapped");s(i_,"isMaindProxyEntry");s(o_,"classifyServer");s(Fu,"wrapServerEntry");s(Lu,"unwrapServerEntry");s($u,"planRewrites")});var Wu={};W(Wu,{runGatewayInstall:()=>u_,runGatewayUninstall:()=>p_});import{existsSync as s_,readFileSync as a_}from"node:fs";import{homedir as c_}from"node:os";import{join as Hu}from"node:path";import{createInterface as l_}from"node:readline";function Uu(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 Gu(){return[{label:"Claude Code (project .mcp.json)",path:Hu(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:Hu(c_(),".claude.json")}]}async function Ku(e){let t=l_({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 Bu(e){let t=d_(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 d_(e){try{return s_(e)?a_(e,"utf8"):null}catch{return null}}async function u_(e){let t=Uu(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
214
|
+
`),2;let n=Z({entryPath:ee(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of Gu()){let o=Bu(i.path);if(o===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
|
|
215
|
+
`);continue}let a=$u(o.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
|
|
216
|
+
`);continue}if(!(t.yes||await Ku(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
|
|
217
217
|
Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
|
|
218
218
|
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
|
|
219
|
-
`);continue}o.servers[c.key]=
|
|
219
|
+
`);continue}o.servers[c.key]=Fu(o.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
|
|
220
220
|
`)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await O(i.path,JSON.stringify(o.raw,null,2)+`
|
|
221
221
|
`,384)}return process.stderr.write(r>0?`
|
|
222
222
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
|
|
223
223
|
`:`
|
|
224
224
|
Nothing to wrap.
|
|
225
|
-
`),0}async function
|
|
226
|
-
`),2;let n=0;for(let r of
|
|
225
|
+
`),0}async function p_(e){let t=Uu(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
226
|
+
`),2;let n=0;for(let r of Gu()){let i=Bu(r.path);if(i===null)continue;let o=!1;for(let[a,c]of Object.entries(i.servers)){if(!tn(c)||!(t.yes||await Ku(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let u=Lu(c);if(u===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
|
|
227
227
|
`);continue}i.servers[a]=u,o=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
|
|
228
228
|
`)}!t.dryRun&&o&&await O(r.path,JSON.stringify(i.raw,null,2)+`
|
|
229
229
|
`,384)}return process.stderr.write(n>0?`
|
|
230
230
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
|
|
231
231
|
`:`
|
|
232
232
|
Nothing wrapped \u2014 nothing to restore.
|
|
233
|
-
`),0}var
|
|
233
|
+
`),0}var Vu=w(()=>{"use strict";ae();Ve();ju();s(Uu,"parseFlags");s(Gu,"targets");s(Ku,"confirm");s(Bu,"loadConfig");s(d_,"readFileSafeSync");s(u_,"runGatewayInstall");s(p_,"runGatewayUninstall")});var qu={};W(qu,{runGatewayAttest:()=>m_,runGatewayMode:()=>f_,runGatewayPolicy:()=>y_});async function f_(e){let t=e[0];if(t===void 0){let n=Zt(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
|
|
234
234
|
`),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
235
|
-
`),2):(await
|
|
235
|
+
`),2):(await Tu(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
|
|
236
236
|
`:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
|
|
237
237
|
`:`Convention policy is off; only explicit --deny-tool flags apply.
|
|
238
|
-
`)),0)}async function
|
|
238
|
+
`)),0)}async function m_(e){let t=e[0];if(t===void 0){let n=kr(),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)":""}.
|
|
239
239
|
`+(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.
|
|
240
240
|
`)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
|
|
241
|
-
`),2):(await
|
|
241
|
+
`),2):(await Iu(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.
|
|
242
242
|
`:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
|
|
243
|
-
`),0)}function
|
|
243
|
+
`),0)}function h_(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
|
|
244
244
|
`;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})
|
|
245
|
-
`}return t}function
|
|
246
|
-
`):(
|
|
247
|
-
`))}let i=
|
|
245
|
+
`}return t}function g_(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 y_(e){let t=e.includes("--refresh"),n=Zt(),r=en();if(t){let o=await Er();o===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
246
|
+
`):(vr(r,o),process.stdout.write(`maind: policy refreshed (${o.length} rule(s)).
|
|
247
|
+
`))}let i=Sr(r);return process.stdout.write(`maind: gateway mode '${n}'
|
|
248
248
|
`),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
|
|
249
|
-
`),0):(process.stdout.write(`maind: policy from cache (${
|
|
250
|
-
`),process.stdout.write(
|
|
251
|
-
`),0)}var
|
|
252
|
-
`,{mode:384})}catch{}}function
|
|
249
|
+
`),0):(process.stdout.write(`maind: policy from cache (${g_(i)}, ${r.mcpUrl}):
|
|
250
|
+
`),process.stdout.write(h_(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.
|
|
251
|
+
`),0)}var Ju=w(()=>{"use strict";Do();Fo();Lo();s(f_,"runGatewayMode");s(m_,"runGatewayAttest");s(h_,"renderRules");s(g_,"cacheAge");s(y_,"runGatewayPolicy")});var Zu={};W(Zu,{gatewayEventsFile:()=>Xu,parseGatewayArgs:()=>Qu,runGateway:()=>E_});import{spawn as b_}from"node:child_process";import{appendFile as w_,mkdir as __}from"node:fs/promises";import{homedir as zu}from"node:os";import{basename as k_,join as Yu}from"node:path";import{createInterface as v_}from"node:readline";function Xu(){return Yu(zu(),".maind","gateway","events.jsonl")}async function S_(e){try{let t=Xu();await __(Yu(zu(),".maind","gateway"),{recursive:!0}),await w_(t,JSON.stringify(e)+`
|
|
252
|
+
`,{mode:384})}catch{}}function Qu(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 E_(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:v,runGatewayUninstall:E}=await Promise.resolve().then(()=>(Vu(),Wu));return e[0]==="install"?v(e.slice(1)):E(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:v,runGatewayMode:E,runGatewayPolicy:R}=await Promise.resolve().then(()=>(Ju(),qu));return e[0]==="mode"?E(e.slice(1)):e[0]==="attest"?v(e.slice(1)):R(e.slice(1))}let t=Qu(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
|
|
253
253
|
maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
254
254
|
maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
255
255
|
maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
@@ -259,54 +259,54 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
|
|
|
259
259
|
NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
|
|
260
260
|
install/uninstall rewrite Claude Code MCP configs (consent per server).
|
|
261
261
|
mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
|
|
262
|
-
`),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r??
|
|
263
|
-
`),process.exitCode=1});let
|
|
264
|
-
`),m(
|
|
265
|
-
`),m(
|
|
266
|
-
`),m(
|
|
267
|
-
`),m(
|
|
268
|
-
`)}),
|
|
269
|
-
`),await
|
|
270
|
-
`),a.warned[o]=c.current,await
|
|
271
|
-
`);let m=r.params?.name;process.stdout.write(
|
|
272
|
-
`);return}i=
|
|
273
|
-
`)}}if(this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let
|
|
274
|
-
`);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(
|
|
275
|
-
`);return}if(
|
|
276
|
-
`);return}if(i!==null){let
|
|
277
|
-
`);return}if(u.startsWith("text/event-stream"))await
|
|
278
|
-
`)}}}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
|
|
279
|
-
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${
|
|
262
|
+
`),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r??k_(i),c=Zt(),l=Nu(),u=l==="off"?null:nn(),d=c==="off"?[]:Sr(en())?.rules??[];c!=="off"&&Er().then(v=>{v!==null&&(d=v,vr(en(),v))}).catch(()=>{});let p=[],f=kr()&&C()!==null&&c!=="off",h=null;try{h=L()}catch{h=null}let m=s(v=>{S_(v),f&&p.push(v)},"record"),g=s(async()=>{if(!f)return;let v=Su(p.splice(0),c,a,h);v!==null&&(await Po(v)||await Eu(v))},"attestAndReset");f&&xu().catch(()=>{});let y=setInterval(()=>{g()},30*6e4);y.unref();let b=b_(i,o,{stdio:["pipe","pipe","inherit"]});b.stdout.pipe(process.stdout),b.on("error",v=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(v)}
|
|
263
|
+
`),process.exitCode=1});let _=v_({input:process.stdin,terminal:!1});_.on("line",v=>{let E=Qo(v);if(E.kind==="request"&&E.method==="tools/call"&&E.toolName){if(n.has(E.toolName)&&E.id!==void 0){process.stdout.write(Ue(E.id,E.toolName)+`
|
|
264
|
+
`),m(Rr("deny",a,E.toolName,Date.now()));return}let R=Du(E.toolName,a,d,c);if(R.kind==="deny"&&E.id!==void 0){process.stdout.write(Ue(E.id,E.toolName,Ou(E.toolName,R.rule))+`
|
|
265
|
+
`),m(Ar("policy_deny",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));return}(R.kind==="warn"||R.kind==="deny")&&m(Ar("policy_warn",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));let G=rn(v,u);if(G.length>0){let T=G.find(X=>X.verdict==="fabricated");if(T!==void 0&&l==="enforce"&&c==="enforce"&&E.id!==void 0&&T!==void 0&&E.id!==void 0){process.stdout.write(Ue(E.id,E.toolName,Ge(T,!0))+`
|
|
266
|
+
`),m(Tr("sha_deny",a,E.toolName,Date.now()));return}let A=T??G[0];process.stderr.write(`[maind gateway] ${Ge(A,!1)}
|
|
267
|
+
`),m(Tr("sha_warn",a,E.toolName,Date.now()))}m(Rr("tool_call",a,E.toolName,Date.now()))}b.stdin.write(v+`
|
|
268
|
+
`)}),_.on("close",()=>{b.stdin.end()});let S=await new Promise(v=>{b.on("exit",(E,R)=>{v(E??(R?1:0))})});return clearInterval(y),await g(),S}var ep=w(()=>{"use strict";Ir();Ru();Do();Oo();Nr();Fo();Lo();K();me();s(Xu,"gatewayEventsFile");s(S_,"logEvent");s(Qu,"parseGatewayArgs");s(E_,"runGateway")});var Bo={};W(Bo,{MAX_ENTRIES:()=>$o,TTL_MS:()=>Uo,crossSessionDir:()=>Go,decideCrossSession:()=>rp,parseSessionDb:()=>np,pruneDb:()=>Ko,runGuardCrossCheck:()=>D_,runGuardCrossObserve:()=>P_,staleReason:()=>jo});import{mkdir as x_,readFile as R_,readdir as A_,stat as tp,unlink as T_,writeFile as I_}from"node:fs/promises";import{homedir as N_}from"node:os";import{join as Ho}from"node:path";function Go(){return Ho(N_(),".maind","cross-session")}function np(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 Ko(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Uo);return n.length>$o&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-$o)),{files:Object.fromEntries(n),warned:e.warned}}function rp(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function jo(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 ip(e){let t=Go();return await x_(t,{recursive:!0}),Ho(t,`${e}.json`)}async function op(e,t){try{let n=await R_(await ip(e),"utf8");return Ko(np(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function sp(e,t){try{await I_(await ip(e),JSON.stringify(t),{mode:384})}catch{}}async function C_(e){try{let t=Go();for(let n of await A_(t)){if(!n.endsWith(".json"))continue;let r=Ho(t,n),i=await tp(r).catch(()=>null);i&&e-i.mtimeMs>Uo&&await T_(r).catch(()=>{})}}catch{}}async function ap(e){try{return(await tp(e)).mtimeMs}catch{return}}async function P_(e,t=Date.now()){try{if(Y().mode==="off")return 0;let r=e??await I(),i=typeof r.session_id=="string"?r.session_id:"",o=re(r);if(!i||!o)return 0;let a=await ap(o);if(a===void 0)return 0;let c=await op(i,t);return c.files[o]={m:a,t},delete c.warned[o],await sp(i,Ko(c,t)),await C_(t),0}catch{return 0}}async function D_(e,t=Date.now()){try{let n=Y();if(n.mode==="off")return 0;let r=e??await I(),i=typeof r.session_id=="string"?r.session_id:"",o=re(r);if(!i||!o)return 0;let a=await op(i,t),c=rp(a.files[o]?.m,await ap(o));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(mt(jo(o,c))+`
|
|
269
|
+
`),await B({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(ke(jo(o,c))+`
|
|
270
|
+
`),a.warned[o]=c.current,await sp(i,a),await B({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o})),0)}catch{return 0}}var Uo,$o,Wo=w(()=>{"use strict";ie();ht();je();_t();Uo=48*3600*1e3,$o=500;s(Go,"crossSessionDir");s(np,"parseSessionDb");s(Ko,"pruneDb");s(rp,"decideCrossSession");s(jo,"staleReason");s(ip,"dbPath");s(op,"loadDb");s(sp,"saveDb");s(C_,"sweepStaleSessionFiles");s(ap,"fileMtime");s(P_,"runGuardCrossObserve");s(D_,"runGuardCrossCheck")});var qo={};W(qo,{INDEX_REFRESH_WORKER:()=>dp,acquireLock:()=>pp,releaseLock:()=>Vo,runIndexRefreshWorker:()=>U_,runOnIndexRefresh:()=>H_});import{spawn as O_}from"node:child_process";import{existsSync as M_,mkdirSync as F_,rmdirSync as cp,statSync as L_}from"node:fs";import{join as lp}from"node:path";function up(e){return lp(e,".maind","index-refresh.lock")}function j_(e){return lp(e,".maind","code-index.sqlite")}function pp(e,t=Date.now()){let n=up(e);try{if(t-L_(n).mtimeMs<$_)return!1;cp(n)}catch{}try{return F_(n,{recursive:!1}),!0}catch{return!1}}function Vo(e){try{cp(up(e))}catch{}}async function H_(){try{let e=await I(),t=q(typeof e.cwd=="string"?e.cwd:process.cwd());if(!M_(j_(t))||!pp(t))return 0;let n=process.argv[1];if(n===void 0)return Vo(t),0;O_(process.execPath,[n,dp,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function U_(){let e=process.argv[3]??q();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(oo(),Xc)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{Vo(e)}return 0}var $_,dp,Jo=w(()=>{"use strict";ie();Wt();$_=30*6e4,dp="index-refresh-run";s(up,"lockPath");s(j_,"indexDbPath");s(pp,"acquireLock");s(Vo,"releaseLock");s(H_,"runOnIndexRefresh");s(U_,"runIndexRefreshWorker")});import{randomUUID as G_}from"node:crypto";import{createInterface as Pp}from"node:readline";var fp=[["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 mp(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of fp)if(t.includes(n))return r;return null}s(mp,"mapClientInfoNameToFamily");function Xo(e){let t;try{t=JSON.parse(e)}catch{return null}if(!xr(t)||t.method!=="initialize")return null;let n=t.params;if(!xr(n))return null;let r=n.clientInfo;if(!xr(r))return null;let i=r.name,o=mp(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(Xo,"tryExtractInitializeClient");function xr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(xr,"isRecord");Ir();Nr();Ke();var Dp="https://mcp.maind.dev/mcp",kt=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},dn=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=on(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=Op(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=Mp(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=nn(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??Dp}async run(){let t=Pp({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=Xo(t);d!==null&&(this.clientFamily=d.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=d.version))}this.initFrame===null&&cn(t)&&(this.initFrame=t);let r=$p(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let d=rn(t,this.shaRepoRoot);if(d.length>0){let p=d.find(h=>h.verdict==="fabricated"),f=p??d[0];if(p!==void 0&&ts(p)&&r.id!==null){let h=Ge(p,!0);process.stderr.write(`[maind] ${h}
|
|
271
|
+
`);let m=r.params?.name;process.stdout.write(Ue(r.id,typeof m=="string"?m:"unknown",h)+`
|
|
272
|
+
`);return}i=Ge(f,!1),process.stderr.write(`[maind] ${i}
|
|
273
|
+
`)}}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+`
|
|
274
|
+
`);return}let o=this.localRouter!==null&&r?.method==="tools/list",a=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:a,body:t})}catch(d){let p=an(t);if(this.serveInitializeFromCache(t,p))return;ln(p,-32603,`bridge network error: ${Hp(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&&!cn(t)){let d=await c.text().catch(()=>"");if(jp(d)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=an(t);ln(p,-32603,`bridge upstream error (HTTP 404): ${d.slice(0,500)}`);return}if(!c.ok){let d=an(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,d))return;ln(d,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let u=c.headers.get("content-type")??"";if(o&&this.localRouter){let d=u.startsWith("text/event-stream")?await Pr(c):await c.text(),p=this.localRouter.augmentToolsList(d);p.trim().length>0&&process.stdout.write(p+`
|
|
275
|
+
`);return}if(cn(t)){let d=u.startsWith("text/event-stream")?await Pr(c):await c.text();this.cacheInitializeResult(d),this.presence?.onSessionReady(),d.trim().length>0&&process.stdout.write(d+`
|
|
276
|
+
`);return}if(i!==null){let d=u.startsWith("text/event-stream")?await Pr(c):await c.text(),p=Lp(d,i);p.trim().length>0&&process.stdout.write(p+`
|
|
277
|
+
`);return}if(u.startsWith("text/event-stream"))await Fp(c);else{if(c.status===202)return;{let d=await c.text();d.trim().length>0&&process.stdout.write(d+`
|
|
278
|
+
`)}}}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 kt(Up(i));let a=an(n);ln(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 Gp(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=se()),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(!cn(t))return!1;let r=ss(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(as(n,r)+`
|
|
279
|
+
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${sn(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Op(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(Op,"normalizeClientFamily");function Mp(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(Mp,"normalizeClientVersion");async function Fp(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(`
|
|
280
280
|
`).trim();i=[],a.length>0&&process.stdout.write(a+`
|
|
281
|
-
`)},"flushEvent");try{for(;;){let{value:a,done:c}=await t.read();if(c)break;r+=n.decode(a,{stream:!0});let
|
|
282
|
-
`))!==-1;){let u=r.slice(0,
|
|
283
|
-
`).trim();o=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:
|
|
284
|
-
`))!==-1;){let
|
|
285
|
-
`)}s(
|
|
286
|
-
`)}s(
|
|
287
|
-
`).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(
|
|
288
|
-
`),null));if(p){if(p.status==="approved")return
|
|
281
|
+
`)},"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(`
|
|
282
|
+
`))!==-1;){let u=r.slice(0,l);r=r.slice(l+1);let d=u.endsWith("\r")?u.slice(0,-1):u;if(d===""){o();continue}d.startsWith(":")||d.startsWith("data:")&&i.push(d.slice(5).replace(/^\s/,""))}}}finally{o()}}s(Fp,"pipeSseToStdout");function Lp(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(Lp,"appendNoteToToolResult");function $p(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s($p,"parseRpc");async function Pr(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(`
|
|
283
|
+
`).trim();o=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let u;for(;(u=r.indexOf(`
|
|
284
|
+
`))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let p=d.endsWith("\r")?d.slice(0,-1):d;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&o.push(p.slice(5).replace(/^\s/,""))}}}finally{a()}return i.join(`
|
|
285
|
+
`)}s(Pr,"collectSseText");function an(e){try{return JSON.parse(e).id??null}catch{return null}}s(an,"tryExtractId");function cn(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(cn,"isInitializeRequest");function jp(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(jp,"isSessionLossBody");function Hp(e){return e instanceof Error?e.message:String(e)}s(Hp,"stringifyErr");function ln(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
286
|
+
`)}s(ln,"emitJsonRpcError");function Up(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(Up,"extractHint");function Gp(e){try{let t=e.trim();if(t.length===0)return null;let n=t;if(!t.startsWith("{")){let o=t.split(`
|
|
287
|
+
`).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(Gp,"parsePresenceToolResult");K();K();import{spawn as Qp}from"node:child_process";import{platform as Zp}from"node:os";var ef="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function tf(){let e=process.env.MAIND_FUNCTIONS_ORIGIN;return e&&e.length>0?e.replace(/\/+$/,""):ef}s(tf,"functionsOrigin");async function Be(e,t=process.stderr){let n=tf(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,o=pn(e),a=`mcp-bridge-${o.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:o})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await sf(l.verification_uri_complete).catch(()=>{}),of(l,t);let u=Date.now()+l.expires_in*1e3,d=Math.max(l.interval,3)*1e3;for(;Date.now()<u;){await rf(d);let p=await nf(i,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
|
|
288
|
+
`),null));if(p){if(p.status==="approved")return Se(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
|
|
289
289
|
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
|
|
290
290
|
`),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
|
|
291
291
|
`),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
|
|
292
|
-
`),null}s(
|
|
292
|
+
`),null}s(Be,"runDeviceFlow");async function nf(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(nf,"pollOnce");function rf(e){return new Promise(t=>setTimeout(t,e))}s(rf,"sleep");function of(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: ${ps(e.verification_uri,56)} \u2502`,` \u2502 Code: ${ps(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(`
|
|
293
293
|
`)+`
|
|
294
|
-
`)}s(
|
|
295
|
-
`))}s(
|
|
296
|
-
`;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(u=>u.target.length)),r=Math.max(t[1].length,...this.results.map(u=>u.action.length)),i=Math.max(t[2].length,...this.results.map(u=>u.status.length)),o=Math.max(t[3].length,...this.results.map(u=>(u.detail??"").length)),a=s((u,
|
|
294
|
+
`)}s(of,"printAuthInstructions");function ps(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}s(ps,"pad");async function sf(e){let t,n;switch(Zp()){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=Qp(t,n,{stdio:"ignore",detached:!0});o.on("error",i),o.unref(),r()}catch(o){i(o)}})}s(sf,"openExternalBrowser");Ee();me();Ee();import*as dl from"node:os";function fs(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 Q("--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 Q("--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 Q("--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 Q("--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 Q("--client requires a family argument (e.g. claude-code, cursor, windsurf, copilot, codex, claude-desktop)");t.client=i,n++;break}default:throw new Q(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}s(fs,"parseInstallFlags");var Q=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function ms(){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(`
|
|
295
|
+
`))}s(ms,"printInstallHelp");var fn=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
|
+
`;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(u=>u.target.length)),r=Math.max(t[1].length,...this.results.map(u=>u.action.length)),i=Math.max(t[2].length,...this.results.map(u=>u.status.length)),o=Math.max(t[3].length,...this.results.map(u=>(u.detail??"").length)),a=s((u,d)=>u+" ".repeat(Math.max(0,d-u.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(o)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],i)} | ${a(t[3],o)} |`),l.push(c);for(let u of this.results)l.push(`| ${a(u.target,n)} | ${a(u.action,r)} | ${a(u.status,i)} | ${a(u.detail??"",o)} |`);return l.join(`
|
|
297
297
|
`)+`
|
|
298
298
|
`}print(t){let n=this.summary();t.write(`
|
|
299
299
|
`),t.write(this.toMarkdownTable()),t.write(`
|
|
300
300
|
Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
|
|
301
|
-
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as
|
|
301
|
+
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as hs from"node:fs/promises";import*as he from"node:path";import*as gs from"node:readline";var ff=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function ys(e){let t=he.resolve(e),n=t;for(;;){if(await ws(n))return n;let r=he.dirname(n);if(r===n)return t;n=r}}s(ys,"detectProjectRoot");async function bs(e){let n=he.resolve(e),r=[];for(;;){await ws(n)&&r.push(n);let i=he.dirname(n);if(i===n)break;n=i}return r}s(bs,"findAllProjectRoots");async function ws(e){for(let t of ff)try{return await hs.access(he.join(e,t)),!0}catch{}return!1}s(ws,"hasAnyMarker");async function _s(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
|
|
302
302
|
Multiple project roots found between cwd and the filesystem root:
|
|
303
303
|
`),e.forEach((o,a)=>{process.stdout.write(` [${a+1}] ${o}
|
|
304
304
|
`)}),process.stdout.write(`
|
|
305
|
-
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=
|
|
306
|
-
`),null):e[i-1]}s(
|
|
307
|
-
`;if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await O(e.path,u)}catch(
|
|
305
|
+
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=gs.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>.
|
|
306
|
+
`),null):e[i-1]}s(_s,"disambiguateProjectRoot");Ve();import*as z from"node:path";function Es(e){let t=e.launch??Z({entryPath:ee(),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(Es,"buildMaindServerEntry");function yf(e){switch(e.platform){case"darwin":return z.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??z.join(e.homeDir,"AppData","Roaming");return z.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??z.join(e.homeDir,".config");return z.join(t,"Claude","claude_desktop_config.json")}}}s(yf,"claudeDesktopConfigPath");function xs(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:z.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:z.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:yf(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:z.join(e.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:z.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:z.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}s(xs,"getClientTargets");function Rs(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}s(Rs,"filterTargetsByFamily");function As(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Ss(e.env.XDG_CONFIG_HOME),appData:Ss(e.env.APPDATA)}}s(As,"makeDefaultContext");function Ss(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}s(Ss,"nonEmpty");Ve();ae();var Et="maind";async function Ps(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 H(e.path)}catch(d){return Lr(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 Lr(e,"parse",d)}}if(!ge(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"&&_f(i),c,l=!1;if(a){let d=i[Et];ge(d)&&Cs(d,t)&&(l=!0),c={...i,[Et]:Ns(d,t)}}else{let d=ge(i.mcpServers)?i.mcpServers:{},p=d[Et];ge(p)&&Cs(p,t)&&(l=!0),c={...i,mcpServers:{...d,[Et]:Ns(p,t)}}}if(l&&r!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let u=JSON.stringify(c,null,2)+`
|
|
307
|
+
`;if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await O(e.path,u)}catch(d){return Lr(e,"write",d)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(Ps,"mergeJsonConfig");function Ns(e,t){let n=ge(e)&&ge(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(Ns,"mergeEntry");function _f(e){return!("mcpServers"in e||!(Et in e))}s(_f,"hasRootShape");function Cs(e,t){if(!ge(e)||e.command!==t.command||!kf(e.args,t.args)||!ge(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(Cs,"serverEntriesEqual");function kf(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(kf,"arrayEquals");function ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(ge,"isObject");function Lr(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(Lr,"failed");ae();import{parse as vf,stringify as Sf}from"smol-toml";async function Ds(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 H(e.path)}catch(m){return yn(e,"read",m)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{let m=vf(r);if(!xe(m))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=m}catch(m){return yn(e,"parse",m)}}let a=xe(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(xe(c)&&Ef(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=xe(c)&&xe(c.env)?c.env:{},u={...t.env};for(let[m,g]of Object.entries(l))!(m in u)&&typeof g=="string"&&(u[m]=g);let d={command:t.command,args:[...t.args],env:u},p={...i,mcp_servers:{...a,maind:d}},f;try{f=Sf(p),f.endsWith(`
|
|
308
308
|
`)||(f+=`
|
|
309
|
-
`)}catch(m){return
|
|
309
|
+
`)}catch(m){return yn(e,"write",m)}let h=f.match(/^\[mcp_servers\.maind\]/gm)??[];if(h.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${h.length}`};if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await O(e.path,f)}catch(m){return yn(e,"write",m)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(Ds,"mergeTomlConfig");function Ef(e,t){if(!xe(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(!xe(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(Ef,"tomlServerEntryEqual");function xe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(xe,"isObject");function yn(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(yn,"failed");import*as ce from"node:path";var xf="__STACK__";var Rf="__INTENT__";var $r="https://mcp.maind.dev/mcp",Af=`?stack=${xf}&intent=${Rf}`;function Tf(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(Tf,"buildStackAwareEndpoint");var nv=Tf($r,{stack:["nextjs","supabase"],intent:"mixed"}),Rt=`## maind MCP integration \u2014 Mandatory consultation
|
|
310
310
|
|
|
311
311
|
This project uses the maind MCP server (mcp.maind.dev/mcp) as
|
|
312
312
|
authoritative source for vetted coding conventions and lessons. The
|
|
@@ -375,7 +375,7 @@ For non-trivial changes, resolve documentation path in this order:
|
|
|
375
375
|
If no path is discoverable, provide a guided fallback:
|
|
376
376
|
\`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
|
|
377
377
|
|
|
378
|
-
Full tool set + provenance via \`get_conventions\`.`;function
|
|
378
|
+
Full tool set + provenance via \`get_conventions\`.`;function If(e){return`I want to add the **maind MCP server** to my AI coding agent.
|
|
379
379
|
|
|
380
380
|
- My stack: \`__STACK__\`
|
|
381
381
|
- MCP endpoint: \`${e}\`
|
|
@@ -571,7 +571,7 @@ written config.
|
|
|
571
571
|
|
|
572
572
|
--- Preamble block ---
|
|
573
573
|
|
|
574
|
-
${
|
|
574
|
+
${Rt}`}s(If,"buildAiPromptBody");function xt(e,t,n){let r=n?`
|
|
575
575
|
MAIND_CLIENT_FAMILY="${n}"`:"";return`#!/usr/bin/env bash
|
|
576
576
|
set -euo pipefail
|
|
577
577
|
|
|
@@ -606,7 +606,7 @@ ${n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":""}
|
|
|
606
606
|
config.mcpServers.maind = server;
|
|
607
607
|
fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
|
|
608
608
|
console.log("WROTE " + file);
|
|
609
|
-
NODE`}s(
|
|
609
|
+
NODE`}s(xt,"buildJsonConfigInstaller");function Nf(e){return`#!/usr/bin/env bash
|
|
610
610
|
set -euo pipefail
|
|
611
611
|
|
|
612
612
|
CONFIG_FILE="$HOME/.codex/config.toml"
|
|
@@ -659,7 +659,7 @@ if (serverCount !== 1 || envCount !== 1) {
|
|
|
659
659
|
|
|
660
660
|
fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
|
|
661
661
|
console.log("WROTE " + file);
|
|
662
|
-
NODE`}s(
|
|
662
|
+
NODE`}s(Nf,"buildCodexTomlInstaller");function Cf(e=$r){let t=`${e}${Af}`;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:If(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:`{
|
|
663
663
|
"mcpServers": {
|
|
664
664
|
"maind": {
|
|
665
665
|
"command": "npx",
|
|
@@ -670,7 +670,7 @@ NODE`}s(tf,"buildCodexTomlInstaller");function nf(e=Tr){let t=`${e}${Qp}`;return
|
|
|
670
670
|
}
|
|
671
671
|
}
|
|
672
672
|
}
|
|
673
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the project .mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-code.sh",lang:"bash",template:
|
|
673
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the project .mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-code.sh",lang:"bash",template:xt(".mcp.json",t,"claude-code")}]},{id:"claude-desktop",label:"Claude Desktop",description:"Browser-pairing desktop 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:"~/Library/Application Support/Claude/claude_desktop_config.json",lang:"json",template:`{
|
|
674
674
|
"mcpServers": {
|
|
675
675
|
"maind": {
|
|
676
676
|
"command": "npx",
|
|
@@ -681,13 +681,13 @@ NODE`}s(tf,"buildCodexTomlInstaller");function nf(e=Tr){let t=`${e}${Qp}`;return
|
|
|
681
681
|
}
|
|
682
682
|
}
|
|
683
683
|
}
|
|
684
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Claude Desktop. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-desktop.sh",lang:"bash",template:
|
|
684
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Claude Desktop. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-desktop.sh",lang:"bash",template:xt("$HOME/Library/Application Support/Claude/claude_desktop_config.json",t,"claude-desktop")}]},{id:"codex",label:"Codex CLI",description:"Browser-pairing Codex 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:"~/.codex/config.toml",lang:"toml",template:`[mcp_servers.maind]
|
|
685
685
|
command = "npx"
|
|
686
686
|
args = ["-y", "@maind-dev/mcp-bridge"]
|
|
687
687
|
|
|
688
688
|
[mcp_servers.maind.env]
|
|
689
689
|
MAIND_CLIENT_FAMILY = "codex"
|
|
690
|
-
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:
|
|
690
|
+
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:Nf(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:`{
|
|
691
691
|
"mcpServers": {
|
|
692
692
|
"maind": {
|
|
693
693
|
"command": "npx",
|
|
@@ -698,7 +698,7 @@ MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",
|
|
|
698
698
|
}
|
|
699
699
|
}
|
|
700
700
|
}
|
|
701
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the workspace .mcp.json used by VS Code Copilot. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-copilot.sh",lang:"bash",template:
|
|
701
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the workspace .mcp.json used by VS Code Copilot. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-copilot.sh",lang:"bash",template:xt(".mcp.json",t,"copilot")}]},{id:"agent-preamble",label:"Agent preamble files (CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, .cursorrules, .windsurfrules + optional SessionStart reminder)",description:"Idempotent shell script that creates or extends SIX artefacts: the five agent-preamble files (CLAUDE.md / AGENTS.md / .github/copilot-instructions.md / .cursorrules / .windsurfrules) plus a SessionStart-Reminder file at ~/.claude/maind-session-start-reminder.md (for Claude Code users \u2014 referenced by an optional SessionStart-Hook). Existing installations are detected via grep on the line `## maind MCP integration` (matches both the legacy soft variant and the new hardened variant). The script also emits a copy-paste JSON snippet for merging the SessionStart-Hook into ~/.claude/settings.json \u2014 manual merge step because naive append breaks JSON syntax. Switching between agents later does not require any MCP re-config. Drift-note: the five preamble files carry duplicated content (single source: this snippet's heredoc).",filename:"writes CLAUDE.md + AGENTS.md + .github/copilot-instructions.md + .cursorrules + .windsurfrules + ~/.claude/maind-session-start-reminder.md",lang:"bash",template:`#!/usr/bin/env bash
|
|
702
702
|
# maind agent-preamble installer \u2014 idempotent. Creates or extends:
|
|
703
703
|
# CLAUDE.md (Claude Code)
|
|
704
704
|
# AGENTS.md (Codex, Windsurf, newer Cursor \u2014 cross-agent standard)
|
|
@@ -715,7 +715,7 @@ set -e
|
|
|
715
715
|
|
|
716
716
|
read -r -d '' MAIND_BLOCK <<'MAIND_PREAMBLE_EOF' || true
|
|
717
717
|
|
|
718
|
-
${
|
|
718
|
+
${Rt}
|
|
719
719
|
MAIND_PREAMBLE_EOF
|
|
720
720
|
|
|
721
721
|
mkdir -p .github
|
|
@@ -764,7 +764,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
764
764
|
}
|
|
765
765
|
}
|
|
766
766
|
}
|
|
767
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cursor/mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cursor.sh",lang:"bash",template:
|
|
767
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cursor/mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cursor.sh",lang:"bash",template:xt("$HOME/.cursor/mcp.json",t,"cursor")}]},{id:"windsurf",label:"Windsurf",description:"Browser-pairing Windsurf 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:"~/.codeium/windsurf/mcp_config.json",lang:"json",template:`{
|
|
768
768
|
"mcpServers": {
|
|
769
769
|
"maind": {
|
|
770
770
|
"command": "npx",
|
|
@@ -775,7 +775,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
775
775
|
}
|
|
776
776
|
}
|
|
777
777
|
}
|
|
778
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codeium/windsurf/mcp_config.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-windsurf.sh",lang:"bash",template:
|
|
778
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codeium/windsurf/mcp_config.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-windsurf.sh",lang:"bash",template:xt("$HOME/.codeium/windsurf/mcp_config.json",t,"windsurf")}]},{id:"langchain-ts",label:"LangChain / LangGraph (TS)",description:"Bridge-backed stdio MCP client. The bridge opens browser pairing, creates a fresh device-bound key, and forwards calls to the stack-aware maind endpoint. Replace `__STACK__` with your stack slugs.",filename:"agent.ts",lang:"ts",template:`import { MultiServerMCPClient } from "@langchain/mcp-adapters";
|
|
779
779
|
|
|
780
780
|
const mcp = new MultiServerMCPClient({
|
|
781
781
|
maind: {
|
|
@@ -796,15 +796,15 @@ const tools = await mcp.getTools();
|
|
|
796
796
|
"env": {
|
|
797
797
|
"MAIND_MCP_URL": "${t}"
|
|
798
798
|
}
|
|
799
|
-
}`}]}s(
|
|
800
|
-
`:
|
|
801
|
-
`;return await O(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(
|
|
799
|
+
}`}]}s(Cf,"buildSnippetTemplates");var rv=Cf($r);ae();var Pf="## maind MCP integration";function Df(e){return[{key:"preamble:CLAUDE.md",path:ce.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:ce.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:ce.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:ce.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:ce.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:ce.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}s(Df,"buildPreambleTargets");async function Os(e,t=!1){let n=Df(e),r=[];for(let i of n)r.push(await Of(i,t));return r}s(Os,"writePreambleFiles");async function Of(e,t){try{if(e.mayNeedParentDir&&!t&&await Fr(ce.dirname(e.path)),await Ts(e.path,Pf))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await H(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?`${Rt}
|
|
800
|
+
`:Mf(r)+`${Rt}
|
|
801
|
+
`;return await O(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(Of,"writeOnePreambleFile");function Mf(e){return e.endsWith(`
|
|
802
802
|
|
|
803
803
|
`)?e:e.endsWith(`
|
|
804
804
|
`)?e+`
|
|
805
805
|
`:e+`
|
|
806
806
|
|
|
807
|
-
`}s(
|
|
807
|
+
`}s(Mf,"ensureTrailingBlankLine");Vr();qe();ae();import*as Us from"node:readline";var Re="config:auto_working_paths",qf=`
|
|
808
808
|
Enable presence enrichment (auto working_paths)?
|
|
809
809
|
With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
|
|
810
810
|
locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
|
|
@@ -813,34 +813,34 @@ before editing the same area. Directory names only: never file contents, never
|
|
|
813
813
|
absolute paths. Server-side these paths are account-private (org members never
|
|
814
814
|
see them) and revocable any time on the dashboard consent page or via
|
|
815
815
|
{"auto_working_paths": false} in the bridge config.
|
|
816
|
-
[y/N]: `;async function
|
|
817
|
-
`;if(e.dryRun)return{target:Re,action:"merge",status:"would-merge",detail:t};try{await O(t,o,384)}catch(a){return{target:Re,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:Re,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}s(
|
|
818
|
-
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=C();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
|
|
819
|
-
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw
|
|
820
|
-
`),2;let a;if(n.projectRoot!==null)a=n.projectRoot;else{let
|
|
821
|
-
`);for(let v of
|
|
822
|
-
`);return 2}a=S}}let c=new
|
|
816
|
+
[y/N]: `;async function Gs(e){let t=e.configPath??le(),n={};try{let a=await H(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:Re,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:Re,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??Jf)(e.out,qf)}else return{target:Re,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:Re,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)+`
|
|
817
|
+
`;if(e.dryRun)return{target:Re,action:"merge",status:"would-merge",detail:t};try{await O(t,o,384)}catch(a){return{target:Re,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:Re,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}s(Gs,"applyWorkingPathsConsent");async function Jf(e,t){e.write(t);let n=Us.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(Jf,"promptYesNoDefaultNo");K();async function Ks(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(Ks,"exchangeOneClickToken");async function Vs(e){let t="browser-pair";if(e.token!==null)try{let o=zf(e.token);return e.dryRun?{apiKey:o,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(St(),Se(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:Bs(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=pn(e.bridgeVersion),a=await Ks({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:o.device_id,label:us(),clientMeta:{...o}});if(a.ok)return St(),Se(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,Ws(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
|
|
818
|
+
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=C();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 Be(e.bridgeVersion,Ws(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:Bs(o)}}}}s(Vs,"pairOrUseToken");function zf(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(zf,"validateTokenShape");function Bs(e){return e instanceof Error?e.message:String(e)}s(Bs,"errMessage");function Ws(e){return e.out??process.stdout}s(Ws,"out");var Yf="https://vsddmiosisvfrairepxv.supabase.co/functions/v1",Xf="/install-completed";async function qs(e){if(!e.enabled||e.apiKey===null)return;let n=`${(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"")||Yf}${Xf}`,r={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:Zf(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:Qf(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(qs,"postInstallTelemetry");function Qf(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(Qf,"countStatuses");function Zf(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}s(Zf,"parseNodeMajor");Wt();var pg="https://mcp.maind.dev/mcp";async function ul(e){let t=Date.now(),n;try{n=fs(e)}catch(_){if(_ instanceof Q)return process.stderr.write(`error: ${_.message}
|
|
819
|
+
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw _}if(n.help)return ms(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,o=dl.homedir();if(o.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
|
|
820
|
+
`),2;let a;if(n.projectRoot!==null)a=n.projectRoot;else{let _=await bs(process.cwd());if(_.length===0)a=await ys(process.cwd());else if(_.length===1)a=_[0];else{let S=await _s(_,i);if(S===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
|
|
821
|
+
`);for(let v of _)process.stderr.write(` candidate: ${v}
|
|
822
|
+
`);return 2}a=S}}let c=new fn,l=(process.env.MAIND_MCP_URL??"").trim()||pg;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
|
|
823
823
|
`),process.stdout.write(`maind install \u2014 project root: ${a}
|
|
824
|
-
`),process.stdout.write(` \u2014 mcp endpoint: ${
|
|
824
|
+
`),process.stdout.write(` \u2014 mcp endpoint: ${l}
|
|
825
825
|
|
|
826
|
-
`);let u=await
|
|
826
|
+
`);let u=await Vs({bridgeVersion:P,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(c.add(u.result),u.result.status==="failed")return process.stderr.write(`
|
|
827
827
|
pairing failed: ${u.result.detail??"unknown"}
|
|
828
828
|
Skipping remaining steps.
|
|
829
|
-
`),c.print(process.stdout),2;let
|
|
829
|
+
`),c.print(process.stdout),2;let d=As({projectRoot:a,homeDir:o,platform:process.platform,env:process.env}),p=xs(d);if(p=Rs(p,n.client),n.skipCodex&&(p=p.filter(_=>_.key!=="codex-cli")),p.length===0)return process.stderr.write(n.client!==null?`error: --client "${n.client}" matched no known target. Run --help for the list.
|
|
830
830
|
`:`error: no client targets selected (did you skip all of them?)
|
|
831
|
-
`),c.print(process.stdout),2;for(let
|
|
831
|
+
`),c.print(process.stdout),2;for(let _ of p){let S=Es({mcpUrl:l,clientFamily:_.clientFamilyEnv}),v;_.kind==="json"?v=await Ps(_,S,n.dryRun):v=await Ds(_,S,n.dryRun),c.add(v)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let _=await Os({projectRoot:a,homeDir:o},n.dryRun);for(let S of _)c.add(S)}let f={homeDir:o,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await js(f));for(let _ of await Hs(f))c.add(_);c.add(await Gs({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let h=il();h.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${h.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await qs({enabled:n.telemetry||n.full,installerVersion:P,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:u.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let m=c.exitCode(),g=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
|
|
832
832
|
DRY RUN finished in ${g}s. No files were modified. Re-run without --dry-run to apply.
|
|
833
833
|
`):process.stdout.write(`
|
|
834
834
|
Finished in ${g}s. Restart your MCP client so it picks up the new server entry.
|
|
835
|
-
`);let
|
|
835
|
+
`);let y=Z({entryPath:ee(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),b=y.fallbackReason===null?`${We(y)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${b}
|
|
836
836
|
`),m===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.
|
|
837
|
-
`),m}s(Ec,"runInstall");Ft();import{readFileSync as yh}from"node:fs";import{join as xc}from"node:path";function Wn(e){return e?Math.ceil(e.length/4):0}s(Wn,"estimateTokens");var Rc=1e6,Vn=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 Tc(e){try{let t=yh(e,"utf8");return t.length>Rc?t.slice(0,Rc):t}catch{return""}}s(Tc,"readFileCapped");function wh(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(wh,"distinctFilePaths");function Ac(e,t,n,r){try{let i=Wn(n);if(e==="codebase_search"){let o=wh(t);if(o.length===0)return 0;let a=0;for(let c of o)a+=Wn(Tc(xc(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=Wn(Tc(xc(r,o)));return Math.max(0,a-i)}return 0}catch{return 0}}s(Ac,"measureLocalToolSaved");Ht();Ft();import{createHash as Gh}from"node:crypto";function qn(e){return Gh("sha256").update(e,"utf8").digest("hex")}s(qn,"nodeKeyHash");var Bh=["module","class","interface","function","method","type_alias","enum","variable"],Fi=[{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:Bh,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. 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."}}}}],Zc=new Set(Fi.map(e=>e.name));function L(e){return typeof e=="string"&&e.length>0?e:void 0}s(L,"str");var Wh=10;function Vh(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>=Wh&&r++,c>i&&(i=c);for(let u of a.ownership?.topAuthors??[])n.add(u.email.toLowerCase()||u.name);let d=a.lastCommits[0]?.dateIso;if(d){let u=Date.parse(d);Number.isFinite(u)&&u>o&&(o=u)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:o>0?Math.max(0,Math.floor((t-o)/864e5)):0}}s(Vh,"aggregateHistoryContext");function Ne(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Ne,"num");function Xc(e){if(e===void 0)return{repoRoot:W(),scanDirs:void 0};let t=Bn(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(Xc,"anchorRepo");function Qc(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(Qc,"dirNotFound");async function el(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 l=_c(i);if(l===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await Ae(l.repoRoot,l.repoRelPath,{minFiles:r}),f=p.namespace,h=s(g=>g===null?null:`${f?.prefix??""}${g}`,"full"),m=f===null?"no_opinion":p.taken?"taken":"free";return{ok:m==="free",mode:"proposed_path",verdict:m,reason:m==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:l.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:h(p.number),taken:m==="no_opinion"?null:p.taken,suggestion:h(p.suggestion),held_by:p.sightings.map(g=>({kind:g.kind,where:g.where,path:g.path})),hint:m==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${h(p.number)} is already held (see held_by). Create the file as ${h(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${h(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let o=Array.isArray(n.dirs)?n.dirs.filter(l=>typeof l=="string"):void 0;if(o!==void 0&&o.length>0){let l=new Map,p=[];for(let S of o){let v=Bn(S);if(v===null){p.push(S);continue}let E=l.get(v.repoRoot)??new Set;E.add(v.repoRelDir),l.set(v.repoRoot,E)}if(l.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],h=[],m=[],g=[];for(let[S,v]of l){let E=[...v],R=E.includes(""),U=await It(S,{dirs:R?void 0:E,minFiles:r});f.push({repo_root:S,dirs:R?null:E}),h.push(...U.findings),m.push(...U.facts.namespaces.map(A=>({repo_root:S,dir:A.dir,prefix:A.prefix,file_count:A.fileCount}))),g.push(...U.facts.skipped)}let w=h.filter(S=>S.status==="open"),y=h.filter(S=>S.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:w.length===0,open_count:w.length,preexisting_count:y.length,findings:w,preexisting:y.map(S=>`${S.namespace.prefix}${S.number}`),namespaces:m,skipped:g,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(w.length===0?m.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.":`${w.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+k}}let a=W(),c=await e.checkNumberCollisions({minFiles:r}),d=c.findings.filter(l=>l.status==="open"),u=c.findings.filter(l=>l.status==="info");return{ok:c.ok,repo_root:a,open_count:d.length,preexisting_count:u.length,findings:d,preexisting:u.map(l=>`${l.namespace.prefix}${l.number}`),namespaces:c.facts.namespaces.map(l=>({dir:l.dir,prefix:l.prefix,file_count:l.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.":`${d.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:L(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=s(p=>r.findings.filter(f=>f.status===p),"of"),o=i("open"),a=i("warn"),c=i("info"),d={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...d,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let u="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",l=o.filter(p=>p.id.startsWith("contract.unreadable:"));return{...d,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:a.length,preexisting_count:c.length,findings:[...o,...a],preexisting:c.map(p=>p.id),coverage_note:u,hint:(r.ok?"The declared entries agree.":l.length>0?`${l.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${o.length-l.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${o.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+u}}case"check_theme_class_drift":{let r=L(n.dir),i,o;if(r!==void 0){let l=Bn(r);if(l===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=l.repoRoot,o=l.repoRelDir===""?void 0:[l.repoRelDir]}else i=W(),o=void 0;let a=$t(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(l=>l.status==="open").length,d=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(l=>({file:l.file,class:l.klass,status:l.status,missing_token:l.token,namespace:l.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; ${d} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${d>0?` (plus ${d} 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=Xc(L(n.dir));if(r===null)return Qc("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=jt(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(d=>d.status==="open"),c=i.findings.filter(d=>d.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(d=>({dir:d.dir,migration_count:d.migrationCount,table_count:d.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(d=>d.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=Xc(L(n.dir));if(r===null)return Qc("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=Mi(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:L(n.remote_db_url)}),o=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=s(p=>i.findings.filter(f=>f.status===p),"of"),c=a("open"),d=a("warn"),u=a("info"),l=o.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:o,open_count:c.length,warn_count:d.length,findings:[...c,...d],expected:u.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:l,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${l}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${l}. 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 + ${d.length} warning finding(s). Talked to \u2014 ${l}.`)+" 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:Ne(n.limit)})).map(o=>({...o,nodeKeyHash:qn(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:Ne(n.max_depth),limit:Ne(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:qn(r)}}case"codebase_map":return e.getArchitecture({topN:Ne(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:L(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Ne(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:qn(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:Ne(n.limit)}),i;if(n.include_history!==!1)try{i=Vh(await e.fileHistory({since:L(n.since),limit:1}))}catch{i=void 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(o=>({name:o.name,qualified_name:o.qualifiedName,kind:o.kind,language:o.language,change:o.change,changed_line_count:o.changedLineCount,stale_index:o.staleIndex,file:o.filePath,start_line:o.startLine,node_key:o.nodeKey,node_key_hash:qn(o.nodeKey)})),review_args:{changed_symbols:r.symbols.map(o=>({name:o.name,qualified_name:o.qualifiedName,kind:o.kind,language:o.language,change:o.change,changed_line_count:o.changedLineCount})),risk_flags:r.riskFlags,diff_stats:{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,head_sha:r.headSha,dirty:r.dirty,base_sha:r.baseSha,code_index_version:Yc},...i?{history:i}:{}},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."}}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:Ne(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(el,"dispatchLocalTool");var Jn=class{constructor(t=vc,n=null,r=W){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Fi}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Zc.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 el(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),d=wc(a)?`${bc} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:d}],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=Ac(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};var qh="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function tl(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:qh}s(tl,"functionsOrigin");var Jh="/mcp-client-metrics-ingest",zh=4e3,Yh="codebase_search_tokens_saved";async function nl(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${tl()}${Jh}`,n=new AbortController,r=setTimeout(()=>n.abort(),zh);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:Yh,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)}
|
|
838
|
-
`),!1}finally{clearTimeout(r)}}s(
|
|
839
|
-
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,
|
|
840
|
-
`),process.exit(1)),n.apiKey}s(
|
|
841
|
-
`),process.exit(1)),e.apiKey}s(
|
|
842
|
-
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(
|
|
843
|
-
`),process.exit(0));let t=j(),n=await
|
|
844
|
-
`),n=await
|
|
845
|
-
`))}s(
|
|
837
|
+
`),m}s(ul,"runInstall");Wt();import{readFileSync as fg}from"node:fs";import{join as pl}from"node:path";function nr(e){return e?Math.ceil(e.length/4):0}s(nr,"estimateTokens");var fl=1e6,rr=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 ml(e){try{let t=fg(e,"utf8");return t.length>fl?t.slice(0,fl):t}catch{return""}}s(ml,"readFileCapped");function mg(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(mg,"distinctFilePaths");function hl(e,t,n,r){try{let i=nr(n);if(e==="codebase_search"){let o=mg(t);if(o.length===0)return 0;let a=0;for(let c of o)a+=nr(ml(pl(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=nr(ml(pl(r,o)));return Math.max(0,a-i)}return 0}catch{return 0}}s(hl,"measureLocalToolSaved");Vt();Wt();import{createHash as Eg}from"node:crypto";function ir(e){return Eg("sha256").update(e,"utf8").digest("hex")}s(ir,"nodeKeyHash");var xg=["module","class","interface","function","method","type_alias","enum","variable"],uo=[{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:xg,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."}}}}],Al=new Set(uo.map(e=>e.name));function M(e){return typeof e=="string"&&e.length>0?e:void 0}s(M,"str");var Rg=10;function Ag(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>=Rg&&r++,c>i&&(i=c);for(let u of a.ownership?.topAuthors??[])n.add(u.email.toLowerCase()||u.name);let l=a.lastCommits[0]?.dateIso;if(l){let u=Date.parse(l);Number.isFinite(u)&&u>o&&(o=u)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:o>0?Math.max(0,Math.floor((t-o)/864e5)):0}}s(Ag,"aggregateHistoryContext");function Oe(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Oe,"num");function xl(e){if(e===void 0)return{repoRoot:q(),scanDirs:void 0};let t=tr(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(xl,"anchorRepo");function Rl(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(Rl,"dirNotFound");async function Tl(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=M(n.for_path);if(i!==void 0){let d=al(i);if(d===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await Ie(d.repoRoot,d.repoRelPath,{minFiles:r}),f=p.namespace,h=s(g=>g===null?null:`${f?.prefix??""}${g}`,"full"),m=f===null?"no_opinion":p.taken?"taken":"free";return{ok:m==="free",mode:"proposed_path",verdict:m,reason:m==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:d.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:h(p.number),taken:m==="no_opinion"?null:p.taken,suggestion:h(p.suggestion),held_by:p.sightings.map(g=>({kind:g.kind,where:g.where,path:g.path})),hint:m==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${h(p.number)} is already held (see held_by). Create the file as ${h(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${h(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let o=Array.isArray(n.dirs)?n.dirs.filter(d=>typeof d=="string"):void 0;if(o!==void 0&&o.length>0){let d=new Map,p=[];for(let S of o){let v=tr(S);if(v===null){p.push(S);continue}let E=d.get(v.repoRoot)??new Set;E.add(v.repoRelDir),d.set(v.repoRoot,E)}if(d.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],h=[],m=[],g=[];for(let[S,v]of d){let E=[...v],R=E.includes(""),G=await Te(S,{dirs:R?void 0:E,minFiles:r});f.push({repo_root:S,dirs:R?null:E}),h.push(...G.findings),m.push(...G.facts.namespaces.map(T=>({repo_root:S,dir:T.dir,prefix:T.prefix,file_count:T.fileCount}))),g.push(...G.facts.skipped)}let y=h.filter(S=>S.status==="open"),b=h.filter(S=>S.status==="info"),_=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:y.length===0,open_count:y.length,preexisting_count:b.length,findings:y,preexisting:b.map(S=>`${S.namespace.prefix}${S.number}`),namespaces:m,skipped:g,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(y.length===0?m.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.`)+_}}let a=q(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(d=>d.status==="open"),u=c.findings.filter(d=>d.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:u.length,findings:l,preexisting:u.map(d=>`${d.namespace.prefix}${d.number}`),namespaces:c.facts.namespaces.map(d=>({dir:d.dir,prefix:d.prefix,file_count:d.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:M(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=s(p=>r.findings.filter(f=>f.status===p),"of"),o=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let u="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",d=o.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:a.length,preexisting_count:c.length,findings:[...o,...a],preexisting:c.map(p=>p.id),coverage_note:u,hint:(r.ok?"The declared entries agree.":d.length>0?`${d.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${o.length-d.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${o.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+u}}case"check_theme_class_drift":{let r=M(n.dir),i,o;if(r!==void 0){let d=tr(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=q(),o=void 0;let a=Pe(i,{dirs:o,baseRef:M(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(d=>d.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(d=>({file:d.file,class:d.klass,status:d.status,missing_token:d.token,namespace:d.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=xl(M(n.dir));if(r===null)return Rl("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Ce(r.repoRoot,{dirs:r.scanDirs,baseRef:M(n.base_ref),includeBaseline:n.include_baseline!==!1}),o="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+o}}case"check_migration_ledger_drift":{let r=xl(M(n.dir));if(r===null)return Rl("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=lo(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:M(n.remote_db_url)}),o=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=s(p=>i.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),u=a("info"),d=o.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:o,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:u.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:d,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${d}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${d}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${d}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=M(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:M(n.kind),limit:Oe(n.limit)})).map(o=>({...o,nodeKeyHash:ir(o.nodeKey)}))}case"codebase_trace":{let r=M(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:Oe(n.max_depth),limit:Oe(n.limit)})}case"codebase_snippet":{let r=M(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:ir(r)}}case"codebase_map":return e.getArchitecture({topN:Oe(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:M(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Oe(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:ir(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:M(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Oe(n.limit)}),i;if(n.include_history!==!1)try{i=Ag(await e.fileHistory({since:M(n.since),limit:1}))}catch{i=void 0}let o;try{o=await e.reviewDetectors({baseRef:M(n.since)})}catch(l){o=tt(jt(`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:El,detector_coverage:o.coverage},c=o.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,u)=>l+u.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:ir(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:M(n.since),limit:Oe(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(Tl,"dispatchLocalTool");var or=class{constructor(t=ll,n=null,r=q){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return uo}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Al.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 Tl(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)?`${sl} (${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=hl(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};var Tg="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function Il(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:Tg}s(Il,"functionsOrigin");var Ig="/mcp-client-metrics-ingest",Ng=4e3,Cg="codebase_search_tokens_saved";async function Nl(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Il()}${Ig}`,n=new AbortController,r=setTimeout(()=>n.abort(),Ng);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:Cg,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)}
|
|
838
|
+
`),!1}finally{clearTimeout(r)}}s(Nl,"postSavingsMetric");mo();ar();lr();import{execFile as yy}from"node:child_process";var by=8,wy=32;function _y(e){return e.split(`
|
|
839
|
+
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,wy)}s(_y,"parsePorcelain");function ky(e,t=by){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(ky,"condenseToDirs");async function Yl(e=vy){let t=await e();if(t===null)return null;let n=ky(_y(t));return n.length>0?n:null}s(Yl,"deriveWorkingPaths");async function vy(){return await new Promise(e=>{yy("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(vy,"defaultGitStatus");var K_=1,B_=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function W_(e){return B_.includes(e)}s(W_,"isHookSubcommand");var V_=6e4;async function q_(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==C()&&Se(e),e;let t=C();if(t!==null)return t;let n=await Be(P);return n===null&&(process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
|
|
840
|
+
`),process.exit(1)),n.apiKey}s(q_,"ensureApiKey");async function J_(){let e=await Be(P);return e===null&&(process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
|
|
841
|
+
`),process.exit(1)),e.apiKey}s(J_,"reauth");async function z_(){let e=process.argv.slice(2).find(m=>!m.startsWith("-"));if(e==="install"){let m=process.argv.indexOf("install"),g=process.argv.slice(m+1),y=await ul(g);process.exit(y)}if(e==="on-session-end"){let{runOnSessionEnd:m}=await Promise.resolve().then(()=>(Vd(),Wd));process.exit(await m())}if(e==="guard"){let m=process.argv.indexOf("guard"),{runGuard:g}=await Promise.resolve().then(()=>(tu(),eu));process.exit(await g(process.argv.slice(m+1)))}if(e==="guard-inject"){let{runGuardInject:m}=await Promise.resolve().then(()=>(cu(),au));process.exit(await m())}if(e==="guard-gate"){let{runGuardGate:m}=await Promise.resolve().then(()=>(fu(),pu));process.exit(await m())}if(e==="guard-stop"){let{runGuardStop:m}=await Promise.resolve().then(()=>(gu(),hu));process.exit(await m())}if(e==="gateway"){let m=process.argv.indexOf("gateway"),{runGateway:g}=await Promise.resolve().then(()=>(ep(),Zu));process.exit(await g(process.argv.slice(m+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:m}=await Promise.resolve().then(()=>(Wo(),Bo));process.exit(await m())}if(e==="guard-cross-check"){let{runGuardCrossCheck:m}=await Promise.resolve().then(()=>(Wo(),Bo));process.exit(await m())}if(e==="on-index-refresh"){let{runOnIndexRefresh:m}=await Promise.resolve().then(()=>(Jo(),qo));process.exit(await m())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:m}=await Promise.resolve().then(()=>(Jo(),qo));process.exit(await m())}if(e!==void 0&&W_(e)){let m=await Promise.resolve().then(()=>(No(),Gd)),g={"on-session-start":m.runOnSessionStart,"on-tool-use":m.runOnToolUse,"on-file-write":m.runOnFileWrite,"on-file-edit":m.runOnFileEdit,"on-repo-health":m.runOnRepoHealth,"on-write-health":m.runOnWriteHealth,"sync-config":m.runSyncConfig,flush:m.runFlush,status:m.runHookStatus}[e];process.exit(await g())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(P+`
|
|
842
|
+
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(Y_(),process.exit(0)),process.argv.includes("--reauth")&&(St(),await Be(P,process.stdout)===null&&process.exit(1),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
|
|
843
|
+
`),process.exit(0));let t=j(),n=await q_(),r=L(),o=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new rr:null,a=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new or(void 0,o),c=`bridge-${G_()}`,l=s(async()=>{if(!o)return;let m=o.takePending();m.tokens<=0||await Nl({apiKey:n,deviceId:t,sessionId:c,tokensSaved:m.tokens,bridgeVersion:P})},"flushSavings"),u=o?setInterval(()=>{l()},V_):null;u?.unref();let d=null,p=new sr({projectKey:r,identity:new cr({projectKey:r}),postToolCall:s((m,g)=>d===null?Promise.reject(new Error("presence: no active forwarder")):d.postPresenceToolCall(m,g),"postToolCall"),deriveWorkingPaths:s(()=>Yl(),"deriveWorkingPaths"),snapshot:r!==null?Gl({projectKey:r}):void 0}),f=p.isEnabled?setInterval(()=>{p.pollActivity()},Dl):null;if(f?.unref(),p.isEnabled){let m=s(g=>{p.end().finally(()=>process.exit(g))},"endAndExit");process.on("SIGTERM",()=>m(143)),process.on("SIGINT",()=>m(130))}let h=0;try{for(;;){let m=new dn({apiKey:n,deviceId:t,bridgeVersion:P,projectKey:r,localRouter:a,presence:p});d=m;try{await m.run();return}catch(g){if(g instanceof kt&&h<K_){h+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${g.message}; re-authorizing\u2026
|
|
844
|
+
`),n=await J_();continue}throw g}}}finally{u&&clearInterval(u),f&&clearInterval(f),await p.end(),await l()}}s(z_,"main");function Y_(){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(`
|
|
845
|
+
`))}s(Y_,"printHelp");z_().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
|
|
846
846
|
`),process.exit(1)});
|