@maind-dev/mcp-bridge 0.56.0 → 0.57.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 +161 -161
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var ko=Object.defineProperty;var s=(e,t)=>ko(e,"name",{value:t,configurable:!0});var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var B=(e,t)=>{for(var n in t)ko(e,n,{get:t[n],enumerable:!0})};function So(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 Fe(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 fr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function mr(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function hr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var gr=b(()=>{"use strict";s(So,"parseFrame");s(Fe,"denyResult");s(fr,"toolEvent");s(mr,"policyEvent");s(hr,"shaEvent")});import{execFileSync as xo}from"node:child_process";function Ro(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=ju}function Hu(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 Fu){let a=r[o];typeof a=="string"&&$u.test(a)&&i.push({field:o,sha:a})}return i}function Uu(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,Eo);for(let i=Eo;i>=Lu;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 $e(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 To(){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 Jt(e=process.cwd()){try{let n=xo("git",["rev-parse","--show-toplevel"],{cwd:e,env:To(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function Ku(e){return t=>{try{let r=xo("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:To(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function zt(e,t){if(t===null)return[];let n=Hu(e);if(n.length===0)return[];let r=Ku(t),i=[];for(let{field:o,sha:a}of n){let c=Uu(a,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var Fu,$u,Lu,Eo,ju,yr=b(()=>{"use strict";Fu=["commit_sha","base_sha","head_sha"],$u=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,Lu=7,Eo=12,ju=10;s(Ro,"isDenyGrade");s(Hu,"extractShaArgs");s(Uu,"classifySha");s($e,"shaFindingText");s(To,"cleanGitEnv");s(Jt,"resolveRepoRootForSha");s(Ku,"gitShaResolver");s(zt,"inspectLineForShas")});import{execFileSync as Gu}from"node:child_process";import{createHash as Bu}from"node:crypto";import{mkdirSync as Wu,readFileSync as Vu,renameSync as qu,writeFileSync as Ju}from"node:fs";import{dirname as zu,join as Ao}from"node:path";function oe(e=process.cwd()){try{let t=Gu("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 Yt(e){return Bu("sha256").update(e).digest("hex").slice(0,16)}function Xt(e){return Ao(e,Yu)}function Io(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function No(e,t,n,r=new Date().toISOString()){try{if(!Io(n))return;let i={version:wr,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},o=Xt(e);Wu(zu(o),{recursive:!0});let a=`${o}.${process.pid}.tmp`;Ju(a,JSON.stringify(i,null,2),"utf8"),qu(a,o)}catch{}}function Co(e,t){try{let n=Vu(Xt(e),"utf8"),r=JSON.parse(n);return r.version!==wr||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Io(r.result)?null:{version:wr,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function Po(e,t,n=new Date){let r=Xu(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 Xu(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${Qu(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function Qu(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i} minute${i===1?"":"s"} ago`;let o=Math.floor(i/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let a=Math.floor(o/24);return`${a} day${a===1?"":"s"} ago`}var wr,Yu,Le=b(()=>{"use strict";wr=1,Yu=Ao(".maind","conventions-cache.json");s(oe,"resolveRepoRoot");s(Yt,"keyFingerprint");s(Xt,"cachePath");s(Io,"hasInstructions");s(No,"writeConventionsCache");s(Co,"readConventionsCache");s(Po,"buildCachedInitializeResponse");s(Xu,"fallbackMarker");s(Qu,"relativeAge")});import{existsSync as nn,mkdirSync as dp,readFileSync as Do,writeFileSync as kr,chmodSync as Oo}from"node:fs";import{homedir as up,hostname as pp,platform as _r,release as fp}from"node:os";import{randomUUID as mp}from"node:crypto";import{join as ke}from"node:path";function ht(){let e=up(),t=process.env;if(_r()==="darwin")return ke(e,"Library","Application Support","maind");if(_r()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:ke(e,"AppData","Roaming");return ke(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:ke(e,".config");return ke(n,"maind")}function Mo(e){nn(e)||dp(e,{recursive:!0,mode:448})}function j(){let e=ht();Mo(e);let t=ke(e,hp);if(nn(t)){let r=Do(t,"utf8").trim();if(wp(r))return r}let n=mp();kr(t,n+`
|
|
5
|
+
`,{encoding:"utf8",mode:384});try{Oo(t,384)}catch{}return n}function wp(e){return yp.test(e)}function vr(){return ke(ht(),gp)}function ve(e){let t=ht();Mo(t);let n=vr();kr(n,e+`
|
|
6
|
+
`,{encoding:"utf8",mode:384});try{Oo(n,384)}catch{}}function C(){let e=vr();if(!nn(e))return null;let t=Do(e,"utf8").trim();return t.length>0?t:null}function gt(){let e=vr();nn(e)&&kr(e,"",{encoding:"utf8",mode:384})}function Fo(){try{return`mcp-bridge-${pp()}`}catch{return"mcp-bridge"}}function rn(e){return{os:`${_r()} ${fp()}`,ide:"mcp-bridge",ext_version:e,device_id:j()}}var hp,gp,yp,K=b(()=>{"use strict";s(ht,"configDir");s(Mo,"ensureDir");hp="device-id",gp="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(wp,"isUuid");s(vr,"apiKeyPath");s(ve,"writeApiKey");s(C,"readApiKey");s(gt,"clearApiKey");s(Fo,"bridgeLabel");s(rn,"clientMeta")});var P,Se=b(()=>{"use strict";P="0.57.0"});import{execFileSync as Tp}from"node:child_process";import{createHash as Ap}from"node:crypto";function Ip(e){return Ap("sha256").update(e).digest("hex")}function Np(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 Cp(e){let t=Np(e);return t?Ip(t):null}function F(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&Pp.test(e))return e;let t;try{t=Tp("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Cp(t):null}var Pp,fe=b(()=>{"use strict";s(Ip,"sha256Hex");s(Np,"normalizeRemoteUrl");s(Cp,"projectKeyFromRemote");Pp=/^[a-f0-9]{64}$/;s(F,"computeProjectKey")});import Op from"node:path";import{fileURLToPath as Mp}from"node:url";function Fp(e,t=Op.sep){return e.split(t).includes("_npx")}function Q(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",qo,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):Fp(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=Mp(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function He(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Vo(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Vo(n)).join(" ")}function sn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(qo)}function an(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Vo(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var qo,Ue=b(()=>{"use strict";qo="@maind-dev/mcp-bridge";s(Fp,"isEphemeralEntry");s(Q,"resolveBridgeLaunch");s(Z,"currentBridgeEntry");s(He,"launchToShellCommand");s(sn,"isNpxForm");s(an,"isLegacyHookForm");s(Vo,"shellQuote")});import*as D from"node:fs/promises";import*as cn from"node:path";async function H(e){try{return await D.readFile(e,"utf8")}catch(t){if(Lp(t))return null;throw t}}async function Sr(e){await D.mkdir(e,{recursive:!0})}async function O(e,t,n){let r=cn.dirname(e);await Sr(r);let i=cn.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(jp(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 Zo(e,t){let n=await H(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function Lp(e){return es(e)&&e.code==="ENOENT"}function jp(e){return!es(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function es(e){return typeof e=="object"&&e!==null&&"code"in e}var se=b(()=>{"use strict";s(H,"readFileSafe");s(Sr,"ensureDir");s(O,"atomicWriteFile");s(Zo,"hasLinePrefix");s(Lp,"isNoEnt");s(jp,"isWindowsRenameFailure");s(es,"isNodeError")});import{existsSync as nf}from"node:fs";import*as ss from"node:path";function _t(e,t={},n=Tr){let r=t.fileExists??nf,i=t.expectedCommand??rf,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Rr(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},d=of(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(an(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(sn(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=sf(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 Ar(e){return e.some(t=>t.status!=="ok")}function un(e){return e.some(t=>t.remedy==="run-install")}function rf(e){return He(Q({entryPath:Z(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function of(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Rr(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Rr(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function sf(e){for(let t of af(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return ss.isAbsolute(t)?t:null;return null}function af(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 Rr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Tr,dn,kt=b(()=>{"use strict";Ue();Tr=[{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."}],dn=[{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(_t,"inspectHookWiring");s(Ar,"hasWiringDrift");s(un,"needsInstallRun");s(rf,"defaultExpectedCommand");s(of,"findCommand");s(sf,"extractScriptPath");s(af,"tokenize");s(Rr,"isObject")});import*as Cr from"node:path";import*as cs from"node:readline";async function ls(e,t){let n=Cr.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: ${Ir(f)}`}}let o,a="create";if(i===null||i.trim().length===0)o={};else{a="merge";try{let f=JSON.parse(i);if(!Nr(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: ${Ir(f)}`}}}let c=lf(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 df(e.out,`
|
|
7
7
|
Merge a ${t.event} hook into ${n}?
|
|
8
8
|
${t.consentDescription}
|
|
9
9
|
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let d={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},u=o.hooks?.[t.event]??[],l={...o,hooks:{...o.hooks??{},[t.event]:[...u,d]}},p=JSON.stringify(l,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: ${
|
|
11
|
-
`,1)[0]??"").trim().slice(0,200)}function
|
|
12
|
-
`).slice(0,1e3)}var
|
|
13
|
-
`));let n=[];return
|
|
14
|
-
`)){if(!c.trim())continue;let d=c.split(" ");if(d.length<2)continue;let u=d[0][0],l=
|
|
15
|
-
`)){if(d.length<4)continue;let u=d[0],l=d[1];if(u==="D"||l==="D")continue;let p=d.slice(3),f=p.indexOf(" -> ");f>=0&&(p=p.slice(f+4)),p=
|
|
16
|
-
`)){if(u.length<4||u[0]!=="?")continue;let l=u.slice(3);l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),!(!l||a.has(l))&&a.set(l,{path:l,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:a,coverage:c}}function
|
|
17
|
-
`)){if(d.startsWith("diff --git ")){c(),o=!1,a=!1;continue}if(d.startsWith("new file mode")){a=!0;continue}if(d.startsWith("rename to ")){o=!0;continue}if(d.startsWith("Binary files ")||d.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(d.startsWith("+++ ")){let l=d.slice(4).trim();if(l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),l.startsWith("b/")&&(l=l.slice(2)),l==="/dev/null")continue;r={path:l,status:a?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let u=
|
|
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(A=>A.trim().length>0).length,m=
|
|
22
|
-
`).map(N=>N.trim()).filter(N=>N.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:d,remoteTrackingExists:u,ahead:l,behind:p,uncommitted:h,detachedHead:i,inProgressOp:m,isSharedMainTree:
|
|
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(ye(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
|
|
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.`}:l});d.sort((l,p)=>
|
|
29
|
-
`):t.readUntracked(e)}var
|
|
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: ${Ir(f)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function ds(e){let t=Cr.join(e.homeDir,as);return ls(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 ${as} into every new Claude Code session.`})}function cf(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function Pr(e,t){let n=e.launch??Q({entryPath:Z(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=He(n);return ls(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:cf(t),skipDetail:s(i=>{let o=`${t.label} already runs maind ${t.subcommand}`;return an(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}`:sn(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 us(e){let t=[];for(let n of Tr)t.push(await Pr(e,n));return t}function lf(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Nr(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Nr(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function df(e,t){e.write(t);let n=cs.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 Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ir(e){return e instanceof Error?e.message:String(e)}var as,Dr=b(()=>{"use strict";se();Ue();kt();as=".claude/maind-session-start-reminder.md";s(ls,"mergeClaudeHook");s(ds,"mergeSessionStartHook");s(cf,"targetKeyFor");s(Pr,"mergeSubcommandHook");s(us,"mergeAllSubcommandHooks");s(lf,"findExistingHookCommand");s(df,"promptYesNo");s(Nr,"isObject");s(Ir,"errMessage")});import{existsSync as uf,readFileSync as pf}from"node:fs";import{join as ff}from"node:path";function ce(){return ff(ht(),"config.json")}function ee(){try{let e=ce();if(!uf(e))return null;let t=JSON.parse(pf(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 Ke=b(()=>{"use strict";K();s(ce,"bridgeConfigPath");s(ee,"readBridgeConfig")});import{execFileSync as kf}from"node:child_process";import{createHash as vf}from"node:crypto";function Sf(e){return vf("sha256").update(e).digest("hex")}function Ef(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 xf(e){let t=Ef(e);return t?Sf(t):null}function Tf(e){return typeof e=="string"&&Rf.test(e)}function bs(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(Tf(t))return t;let n;try{n=kf("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?xf(n):null}var Rf,_s=b(()=>{"use strict";s(Sf,"sha256Hex");s(Ef,"normalizeRemoteUrl");s(xf,"projectKeyFromRemote");Rf=/^[a-f0-9]{64}$/;s(Tf,"isProjectKey");s(bs,"computeProjectKey")});function pn(e){return`${e}#<module>`}function fn(e,t,n){return`${e}#${t}:${n}`}var vt=b(()=>{"use strict";s(pn,"moduleKey");s(fn,"symbolKey")});function mn(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 Or(e){return e.toLowerCase().endsWith(".d.ts")}var hn=b(()=>{"use strict";s(mn,"languageForPath");s(Or,"isSkippablePath")});function gn(){return{nodes:[],edges:[],refs:[],imports:[]}}function ge(e){return e+1}function yn(e){return(e.text.split(`
|
|
11
|
+
`,1)[0]??"").trim().slice(0,200)}function Af(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 If(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=Af(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Ge(e,t,n,r){for(let i of If(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}var wn=b(()=>{"use strict";s(gn,"newResult");s(ge,"line1");s(yn,"signatureOf");s(Af,"calleeName");s(If,"collectCallTargets");s(Ge,"addCallRefs")});function vs(e,t){let n=gn();for(let r of e.namedChildren)Nf(r,t,n);return n}function Ss(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function Nf(e,t,n){let r=Ss(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??Pf(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=bn(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&&Ge(n,o.nodeKey,a,ks);return}case"class_definition":Cf(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=bn(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 Cf(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=bn(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 d=c.childForFieldName("attribute")?.text;d&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:d})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let d=Ss(c);if(d.type!=="function_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let l=`${r}.${u}`,p=bn(d,t,u,l,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=d.childForFieldName("body");f&&Ge(n,p.nodeKey,f,ks)}}function bn(e,t,n,r,i){return{nodeKey:fn(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:ge(e.startPosition.row),endLine:ge(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:yn(e),doc:null}}function Pf(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var ks,Es=b(()=>{"use strict";vt();wn();ks="call";s(vs,"extractPython");s(Ss,"unwrapDecorated");s(Nf,"handleTopLevel");s(Cf,"addClass");s(bn,"makeNode");s(Pf,"firstDottedName")});function Ts(e,t){let n=gn();for(let r of e.namedChildren)Of(r,t,n);return n}function Df(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function Of(e,t,n){let r=Df(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:Ff(i)});return}case"function_declaration":case"generator_function_declaration":{xs(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{Mf(r,t,n);return}case"interface_declaration":Mr(r,t,n,"interface");return;case"type_alias_declaration":Mr(r,t,n,"type_alias");return;case"enum_declaration":Mr(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";xs(i,t,n,c?"function":"variable",o,a)}return}default:return}}function xs(e,t,n,r,i,o){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let d=_n(e,t,c,c,r);n.nodes.push(d),n.edges.push({srcKey:t.moduleKey,dstKey:d.nodeKey,kind:"contains"});let u=o??e.childForFieldName("body")??e;r==="function"&&u&&Ge(n,d.nodeKey,u,Rs)}function Mr(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=_n(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}function Mf(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=_n(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 d=c.type==="implements_clause"?"implements":"extends";for(let u of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:d,targetName:u.text});for(let u of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:d,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 d=`${r}.${c}`,u=_n(a,t,c,d,"method");n.nodes.push(u),n.edges.push({srcKey:i.nodeKey,dstKey:u.nodeKey,kind:"contains"});let l=a.childForFieldName("body");l&&Ge(n,u.nodeKey,l,Rs)}}function _n(e,t,n,r,i){return{nodeKey:fn(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:ge(e.startPosition.row),endLine:ge(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:yn(e),doc:null}}function Ff(e){return e.replace(/^["'`]|["'`]$/g,"")}var Rs,As=b(()=>{"use strict";vt();wn();Rs="call_expression";s(Ts,"extractTypescript");s(Df,"unwrapExport");s(Of,"handleTopLevel");s(xs,"addFunctionLike");s(Mr,"addSimpleNamed");s(Mf,"addClass");s(_n,"makeNode");s(Ff,"stripQuotes")});import{createRequire as $f}from"node:module";import{join as Lf}from"node:path";function Cs(e,t){return t?Lf(t,Is[e]):$f(import.meta.url).resolve(`tree-sitter-wasms/out/${Is[e]}`)}var Is,Ns,Ps=b(()=>{"use strict";Is={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Ns="tree-sitter.wasm";s(Cs,"grammarPath")});import{join as jf}from"node:path";import Fr from"web-tree-sitter";var Hf,kn,Ds=b(()=>{"use strict";vt();hn();Es();As();wn();Ps();Hf=["typescript","tsx","javascript","python"],kn=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await Fr.init(this.assetDir?{locateFile:s(t=>jf(this.assetDir,t||Ns),"locateFile")}:void 0),this.parser=new Fr,this.initialized=!0)}supports(t){return Hf.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=pn(t),d={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:ge(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:c},l=r==="python"?vs(a,u):Ts(a,u);return o.delete(),{filePath:t,language:r,nodes:[d,...l.nodes],edges:l.edges,refs:l.refs,imports:l.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await Fr.Language.load(Cs(t,this.assetDir)),this.grammars.set(t,n)),n}}});function Os(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
|
|
12
|
+
`).slice(0,1e3)}var Ms=b(()=>{"use strict";s(Os,"nodeEmbedText")});var $r,Lr=b(()=>{"use strict";$r=["function","method","class","interface","enum","type_alias"]});function Fs(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],d=t[a];r+=c*d,i+=c*c,o+=d*d}return i===0||o===0?0:r/(Math.sqrt(i)*Math.sqrt(o))}var $s=b(()=>{"use strict";s(Fs,"cosineSimilarity")});import{posix as jr}from"node:path";function Ls(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!Uf.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 js(e,t){let n=new Set,r=[],i=new Set,o=s((a,c,d)=>{if(a===c)return;let u=`${a}\0${c}\0${d}`;n.has(u)||(n.add(u),r.push({srcKey:a,dstKey:c,kind:d}),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=Kf(e.filePath,a.specifier,t.files);c&&o(a.fromModuleKey,pn(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}function Kf(e,t,n){if(!t.startsWith("."))return null;let r=jr.normalize(jr.join(jr.dirname(e),t)),i=[],o=vn.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 d of vn)i.push(c+d)}if(!o){for(let c of vn)i.push(r+c);for(let c of vn)i.push(`${r}/index${c}`)}for(let c of i)if(n.has(c))return c;return null}var Uf,vn,Hs=b(()=>{"use strict";vt();Uf=new Set(["function","method","class","interface","enum","type_alias"]),vn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];s(Ls,"buildResolutionIndex");s(js,"resolveFileEdges");s(Kf,"resolveImportTarget")});import{execFileSync as Gf}from"node:child_process";import{createHash as Bf}from"node:crypto";import{readdirSync as Wf,statSync as Vf}from"node:fs";import{posix as Bs,sep as Us}from"node:path";function k(e,t){try{return Gf("git",[...qf,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function Jf(e){return Us==="/"?e:e.split(Us).join("/")}function Sn(e){let t=[];for(let n of e){let r=Jf(n).trim();if(!r||Or(r))continue;let i=mn(r);i&&t.push({path:r,language:i})}return t}function Ws(e){return Sn(e)}function Vs(e){let t=Be(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Sn(t.split(`
|
|
13
|
+
`));let n=[];return qs(e,"",n),Sn(n)}function qs(e,t,n){let r;try{r=Wf(Bs.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&Ks.has(i.name)||Ks.has(i.name))continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?qs(e,o,n):i.isFile()&&n.push(o)}}function Hr(e,t){let r=k(e,["merge-base",t,"HEAD"])?.trim();return r&&r.length>0?r:t}function En(e,t={}){if(St(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Hr(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=Be(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 d=c.split(" ");if(d.length<2)continue;let u=d[0][0],l=Gs((d.length>=3?d[d.length-1]:d[1]).trim());l&&(u==="A"||u==="C"?a.set(l,"added"):u==="R"?a.set(l,"renamed"):a.set(l,"modified"))}if(n){let c=Be(e,["status","--porcelain","-uall"])??"";for(let d of c.split(`
|
|
15
|
+
`)){if(d.length<4)continue;let u=d[0],l=d[1];if(u==="D"||l==="D")continue;let p=d.slice(3),f=p.indexOf(" -> ");f>=0&&(p=p.slice(f+4)),p=Gs(p),!(!p||a.has(p))&&(u==="?"||u==="A"||l==="A"?a.set(p,"added"):u==="R"?a.set(p,"renamed"):a.set(p,"modified"))}}return a}function Gs(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Js(e,t={}){let n=En(e,t);return n===null?null:Sn(n.keys())}function zs(e,t){try{let n=Vf(Bs.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function xn(e){return Bf("sha256").update(e).digest("hex")}function St(e){return Be(e,["rev-parse","HEAD"])?.trim()??null}function Rn(e,t){return Be(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function Ys(e){let t=Be(e,["status","--porcelain","-uall"]);return t!==null&&t.trim().length>0}var Ks,qf,Be,J=b(()=>{"use strict";hn();Ks=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),qf=["-c","diff.renames=true","-c","core.quotePath=false"];s(k,"runGit");Be=k;s(Jf,"toPosix");s(Sn,"classify");s(Ws,"classifyPaths");s(Vs,"discoverSourceFiles");s(qs,"walk");s(Hr,"resolveDiffBase");s(En,"enumerateChangedPaths");s(Gs,"unquote");s(Js,"changedSourceFiles");s(zs,"statFile");s(xn,"hashContent");s(St,"headCommit");s(Rn,"resolveCommitSha");s(Ys,"isWorktreeDirty")});function Qs(e,t={}){if(k(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Hr(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")>zf?c="none":Zf(o,a,()=>{c="partial"}),n){let d=k(e,["status","--porcelain","-uall"])??"";for(let u of d.split(`
|
|
16
|
+
`)){if(u.length<4||u[0]!=="?")continue;let l=u.slice(3);l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),!(!l||a.has(l))&&a.set(l,{path:l,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:a,coverage:c}}function Zf(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 d of e.split(`
|
|
17
|
+
`)){if(d.startsWith("diff --git ")){c(),o=!1,a=!1;continue}if(d.startsWith("new file mode")){a=!0;continue}if(d.startsWith("rename to ")){o=!0;continue}if(d.startsWith("Binary files ")||d.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(d.startsWith("+++ ")){let l=d.slice(4).trim();if(l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),l.startsWith("b/")&&(l=l.slice(2)),l==="/dev/null")continue;r={path:l,status:a?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let u=Qf.exec(d);if(u){if(i++,i>Yf){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let l=Number(u[1]),p=u[2]===void 0?1:Number(u[2]);p>0?r.addedRanges.push({start:l,end:l+p-1}):r.deletionPoints.push(l);continue}d.startsWith("+")&&!d.startsWith("+++")&&!r.degraded&&r.addedLines.length<Xf&&r.addedLines.push(d.slice(1))}c()}var zf,Yf,Xf,Xs,Qf,Zs=b(()=>{"use strict";J();zf=16*1024*1024,Yf=500,Xf=4e3,Xs=256*1024,Qf=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(Qs,"changedHunks");s(Zf,"parseUnifiedDiff")});function nm(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function ta(e){return e.split(em).filter(t=>t.trim().length>0)}function na(e){let[t,n,r,i,o]=e.replace(/\n+$/,"").split(tm);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:o??""}}function rm(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 ia(e,t,n={}){let r=nm(n.limit,20,100),i=n.includeOwnership!==!1,o=Math.max(r,ra),a=t.map(l=>l.trim()).filter(l=>l.length>0&&!l.startsWith(":")),c=a.slice(0,Ur),d=[];for(let l of c){let p=k(e,["log","-n",String(o),ea,"--",l]),f=p===null?[]:ta(p).map(na).filter(h=>h!==null);d.push({path:l,lastCommits:f.slice(0,r),ownership:i?{topAuthors:rm(f),commitsInWindow:f.length}:null})}let u=null;if(n.since){let l=Rn(e,n.since),p=l!==null?[`${l}..HEAD`]:[`--since=${n.since}`],f=k(e,["log",...p,"-n",String(Tn+1),ea,"--name-only","--",...c]),h=[];if(f!==null)for(let m of ta(f)){let g=m.split(`
|
|
18
|
+
`),w=na(g[0]??"");if(!w)continue;let y=g.slice(1).filter(_=>_.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,Tn),truncated:h.length>Tn}}return{history:d,regression:u,ownershipWindowCommits:o,pathsTruncated:a.length>Ur}}var em,tm,ra,Ur,Tn,ea,Kr=b(()=>{"use strict";J();em="",tm="\0",ra=200,Ur=50,Tn=100,ea="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";s(nm,"clamp");s(ta,"splitRecords");s(na,"parseHistoryRecord");s(rm,"aggregateOwnership");s(ia,"readFileHistory")});import{execFileSync as im}from"node:child_process";import{readdirSync as om,statSync as oa}from"node:fs";import{isAbsolute as sm,join as Gr,relative as am,resolve as cm}from"node:path";function dm(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function um(e,t){try{let n=im("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 pm(e){let t;try{t=om(e)}catch{return null}for(let n of t.filter(dm))try{let r=oa(Gr(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function fm(e){try{return oa(e).isDirectory()}catch{return!1}}function mm(e,t){let n=am(e,t);return!n||n.startsWith("..")?t:n}function Br(e){let t=lm.filter(c=>fm(Gr(e,c))),n=um(e,"core.hooksPath"),r=n?sm(n)?n:cm(e,n):Gr(e,".git","hooks"),i=mm(e,r),o=pm(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 Wr(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 lm,Vr=b(()=>{"use strict";lm=[".githooks",".husky"];s(dm,"isRealHook");s(um,"gitConfig");s(pm,"hasExecutableHook");s(fm,"isDir");s(mm,"displayPath");s(Br,"resolveHookState");s(Wr,"describeHookState")});import{posix as sa}from"node:path";function We(e){let t=hm.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 Re(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=sa.basename(o),c=We(a);if(c===null)continue;let d=sa.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 aa(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 hm,Et=b(()=>{"use strict";J();hm=/^(\d+)_.+\.sql$/;s(We,"parseMigrationVersion");s(le,"compareVersions");s(Re,"discoverSupabaseProjects");s(aa,"resolveDefaultBranch")});import{execFileSync as gm}from"node:child_process";import{existsSync as $,readFileSync as ye,readdirSync as An,statSync as Jr}from"node:fs";import{posix as x}from"node:path";function _m(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&&Yr(n,o))){let c=km(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=x.dirname(r)}return null}function km(e,t){let n=[];for(let r of wm){let i;try{i=An(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=Jr(c),l=Jr(d);if(!l.isFile())continue;if(u.size!==l.size){n.push(a);continue}if(u.size>bm)continue;ye(c).equals(ye(d))||n.push(a)}catch{continue}}}return n.sort()}function ma(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 ${Xr}.`})}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=vm(e.hooks);return o&&t.push(o),Sm(t)}function vm(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:Wr(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 Sm(e){return[...e].sort((t,n)=>ca[t.status]-ca[n.status]||t.id.localeCompare(n.id))}function ha(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function de(e){let t=e?.trim();return t||null}function Em(e){let t=de(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 xm(e){let t=de(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 Rm(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 Tm(e){let t=x.join(e,Xr);if(!$(t))return[];try{return ye(t,"utf8").split(`
|
|
20
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function Am(e){try{return Re(e).map(t=>x.join(x.dirname(t.dir),"config.toml"))}catch{return[]}}function Im(e){let t=k(e,["ls-files","-z","--",...ym]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=fa[x.basename(r)];if(i===void 0)continue;let o=x.dirname(r);if(!Nm(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 Nm(e,t){return t==="."?!0:zr(e,t)}function zr(e,t){if($(x.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(ye(x.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function ga(e,t={}){if(de(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=de(k(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",o=i?null:r,a=Em(e),c=de(k(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),d=null,u=null;if(c){let A=de(k(e,["rev-parse","HEAD"])),N=de(k(e,["rev-parse","@{u}"]));d=A!=null&&N!=null?A===N:null,u=k(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let l=null,p=null;if(a){let A=de(k(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(A){let[N,T]=A.split(/\s+/).map(Y=>Number.parseInt(Y,10));Number.isFinite(N)&&(p=N),Number.isFinite(T)&&(l=T)}}let h=(k(e,["status","--porcelain"])??"").split(`
|
|
21
|
+
`).filter(A=>A.trim().length>0).length,m=xm(e),g=de(k(e,["rev-parse","--show-toplevel"]))??e,w=Rm(k(e,["worktree","list","--porcelain"])??""),y=w[0]?.path??null,_=y!=null&&Yr(y,g),S=Math.max(0,w.length-1),v=null;if(y&&!Yr(y,g)){let A=s(T=>$(x.join(y,T))&&!$(x.join(g,T)),"here"),N=[...pa,...Am(g),...Tm(g),...t.probePaths??[]];v={mainWorktreePath:y,currentWorktreePath:g,missing:[...new Set(N.filter(A))],missingDeps:Im(g).filter(T=>A(T.dir))}}let E=_m(g,e),R=t.includeRelease===!1?null:$m(e,o),U=[];return a&&(U=(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:d,remoteTrackingExists:u,ahead:l,behind:p,uncommitted:h,detachedHead:i,inProgressOp:m,isSharedMainTree:_,otherWorktrees:S,worktreeParity:v,toolCopyDrift:E,stalePackageBuilds:ya(g),release:R,unmergedMigrations:U,hooks:Br(e)}}function Yr(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function Dm(e){let t=new Set;zr(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<da;){let i=n.pop();if(i===void 0)break;if(i.depth>=Pm)continue;let o;try{o=An(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>=da)break;zr(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function Om(e){let t=[];try{let n=x.join(e,"pnpm-workspace.yaml");if($(n)){let r=!1;for(let i of ye(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(ye(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 Mm(e){let t=[];for(let n of Dm(e)){let r=n==="."?e:x.join(e,n),i=s(o=>n==="."?o:x.join(n,o),"prefix");for(let o of Om(r)){if(t.length>=qr)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 d of An(c,{withFileTypes:!0}))if(d.isDirectory()&&!d.name.startsWith(".")&&t.push(i(x.join(a,d.name))),t.length>=qr)break}else o.includes("*")||t.push(i(o))}catch{}}}return t.slice(0,qr)}function ua(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=An(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 d=Jr(c).mtimeMs;(t===null||d>t)&&(t=d)}catch{}if(n>=la)break}}}return t}function Fm(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(ye(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=o[a];if(!(c===null||typeof c!="object"))for(let[d,u]of Object.entries(c))typeof u=="string"&&u.startsWith("workspace:")&&n.add(d)}}catch{}return n}function ya(e){let t=[],n=Mm(e),r=Fm(e,n);for(let i of n)try{let o=x.join(e,i,"package.json");if(!$(o))continue;let a=JSON.parse(ye(o,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(y=>{if(typeof y!="string")return null;let _=y.replace(/^\.\//,"").split("/")[0];return _==="build"||_==="dist"?_:null},"builtSeg"),d=c(a.types??a.typings),u=c(a.main),l=d??u;if(l===null)continue;let p=d!==null&&u!==null?"both":d!==null?"types":"runtime",f=x.join(e,i,"src"),h=x.join(e,i,l);if(!$(f)||!$(h))continue;let m=ua(f),g=ua(h);if(m===null||g===null)continue;let w=m-g;w>Cm&&t.push({packageDir:i,buildDir:l,srcNewerByMs:Math.round(w),impact:p})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}function $m(e,t){if(!t)return null;let n=Lm(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 Lm(e,t){try{return gm("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function xt(e,t={}){let n=await ga(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=ma(n),i=ha(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var pa,Xr,fa,ym,wm,bm,ca,Cm,qr,la,Pm,da,Qr=b(()=>{"use strict";Vr();J();Et();pa=["supabase/config.toml","supabase/.temp",".env"],Xr=".maind/worktree-requirements",fa={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},ym=Object.keys(fa).flatMap(e=>[e,"*/"+e]),wm=["scripts"],bm=512*1024;s(_m,"gatherToolCopyDrift");s(km,"compareToolDirs");s(ma,"computeDivergence");s(vm,"computeHookFinding");ca={open:0,warn:1,info:2,passed:3};s(Sm,"sortFindings");s(ha,"isHealthy");s(de,"trimOrNull");s(Em,"resolveDefaultBranch");s(xm,"detectInProgressOp");s(Rm,"parseWorktrees");s(Tm,"readWorktreeRequirements");s(Am,"discoverSupabaseConfigProbes");s(Im,"discoverDependencyDirs");s(Nm,"isWorkspaceRoot");s(zr,"hasWorkspaceMarkers");s(ga,"gatherRepoHealthFacts");s(Yr,"samePath");Cm=2e3,qr=64,la=4e3,Pm=3,da=400;s(Dm,"findWorkspaceRoots");s(Om,"workspacePatternsAt");s(Mm,"listWorkspacePackageDirs");s(ua,"newestMtimeUnder");s(Fm,"consumedWorkspaceNames");s(ya,"gatherStalePackageBuilds");s($m,"gatherReleaseFact");s(Lm,"runGh");s(xt,"checkDivergence")});import{existsSync as Zr,readdirSync as wa}from"node:fs";import{posix as te}from"node:path";function _a(e,t={}){let n=t.minFiles??ei;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??ba)}function qe(e){return`${e.dir}#${e.prefix}`}function Rt(e){let t=jm.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function ka(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[d,u]of a){let l=[...new Set(u.map(m=>m.path))];if(l.length<2)continue;let p=l.find(m=>n.has(m)),f=l.filter(m=>m!==p),h=`${i.prefix}${d}`;t.push(p?{id:`number.collision:${o}#${d}`,status:"open",namespace:i,number:d,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}${ti(c,d)}`,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}#${d}`,status:"info",namespace:i,number:d,title:`${h} is used more than once (pre-existing)`,detail:`${h} is carried by ${l.length} files: ${l.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 va(e){return!e.some(t=>t.status==="open")}function ti(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}function ni(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Sa(e,t){let n=ni(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=Rt(te.basename(n));if(!i)return r;let o=`${te.dirname(n)}#${i.prefix}`,a=e.namespaces.find(l=>qe(l)===o)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(o)??new Map,d=new Set,u=[];for(let l of c.get(i.number)??[])l.path===n||d.has(l.path)||(d.add(l.path),u.push(l));return{path:n,namespace:a,number:i.number,taken:u.length>0,sightings:u,suggestion:ti(c.keys(),i.number)}}function In(e){let t=e?.trim();return t||null}function Ve(e){return e?e.split(`
|
|
24
|
+
`).filter(Boolean):[]}function Hm(e){let t=In(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 Ea(e,t={}){let n=t.minFiles??ei,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=te.dirname(a),d=Rt(te.basename(a));if(!d)continue;let u=`${c}#${d.prefix}`,l=o.get(u);l?l.numbers.push(d.number):o.set(u,{dir:c,prefix:d.prefix,numbers:[d.number]})}return[...o.values()].filter(a=>_a(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 ri(e,t={}){let n=[];if(In(k(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=Ea(e,t),o=new Map(i.map(h=>[qe(h),h])),a=[...new Set(i.map(h=>h.dir))],c=new Map,d=s((h,m,g)=>{let w=te.dirname(h),y=Rt(te.basename(h));if(!y)return;let _=`${w}#${y.prefix}`;if(!o.has(_))return;let S=c.get(_)??new Map,v=S.get(y.number)??[];v.push({kind:m,where:g,path:h}),S.set(y.number,v),c.set(_,S)},"record"),u=s((h,m,g)=>{if(a.length===0)return;let w=k(e,["ls-tree","-r","--name-only",h,"--",...a]);if(w===null){n.push(`could not read ${g}`);return}for(let y of Ve(w))d(y,m,g)},"scanTree");for(let h of a){let m=te.join(e,h);if(Zr(m))try{for(let g of wa(m))d(`${h}/${g}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let l=Hm(e);l?u(`origin/${l}`,"default_branch",`origin/${l}`):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let p=In(k(e,["rev-parse","--abbrev-ref","HEAD"]));for(let h of Ve(k(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))h!==p&&u(h,"branch",`Branch ${h}`);if(t.includeWorktrees!==!1){let h=In(k(e,["rev-parse","--show-toplevel"]));for(let m of Ve(k(e,["worktree","list","--porcelain"]))){if(!m.startsWith("worktree "))continue;let g=m.slice(9).trim();if(!(!g||g===h||!Zr(g)))for(let w of a){let y=te.join(g,w);if(Zr(y))try{for(let _ of wa(y))d(`${w}/${_}`,"worktree",`Worktree ${g}`)}catch{n.push(`could not read ${w} in ${g}`)}}}}let f=[];if(l&&a.length>0){let h=k(e,["diff","--name-only","--diff-filter=A",`origin/${l}...HEAD`,"--",...a]);h===null?n.push("could not diff against the default branch \u2014 everything reported as info"):f=Ve(h);let m=k(e,["ls-files","--others","--exclude-standard","--",...a]);m!==null&&(f=[...f,...Ve(m)]);let g=k(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);g!==null&&(f=[...f,...Ve(g)])}return{isRepo:!0,defaultBranch:l,namespaces:i,sightingsByNamespace:c,addedPaths:f,skipped:n}}async function Tt(e,t={}){let n=await ri(e,t),r=ka(n);return{ok:va(r),findings:r,facts:n}}async function Te(e,t,n={}){let r=ni(t);if(!Rt(te.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await ri(e,{...n,dirs:n.dirs??[te.dirname(r)]});return Sa(i,r)}var jm,ei,ba,ii=b(()=>{"use strict";J();jm=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,ei=3,ba=.8;s(_a,"isCounterNamespace");s(qe,"namespaceKey");s(Rt,"parseNumbered");s(ka,"computeNumberCollisions");s(va,"isCollisionFree");s(ti,"suggestNextNumber");s(ni,"normaliseRepoPath");s(Sa,"checkProposedNumber");s(In,"trimOrNull");s(Ve,"lines");s(Hm,"resolveDefaultBranch");s(Ea,"detectNamespaces");s(ri,"gatherNumberCollisionFacts");s(Tt,"checkNumberCollisions");s(Te,"checkNumberForPath")});import{existsSync as Um,readFileSync as xa}from"node:fs";import{posix as Km}from"node:path";function Pn(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 Dn(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 At(e){return e==='"'||e==="'"||e==="`"}function On(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function Nn(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(At(o)){i=Pn(e,i);continue}if(On(e,i)){i=Dn(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function Gm(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(On(e,t)){t=Dn(e,t);continue}break}return e.slice(t)}function Je(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let o=e[i];if(At(o)){i=Pn(e,i);continue}if(On(e,i)){i=Dn(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=>Gm(o).trim()).filter(o=>o.length>0)}function Ia(e){let t=Pn(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
|
|
26
|
+
`:i==="r"?"\r":i==="t"?" ":i)}function Bm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function si(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${Bm(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(At(a)){i=Pn(e,i);continue}if(On(e,i)){i=Dn(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 Nn(e,i);if(a===";")return null;i++}return null}function ai(e){let t={};if(!e.startsWith("{"))return t;for(let n of Je(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();At(o[0]??"")&&(t[i]=Ia(o))}return t}function Wm(e,t){if(!e.startsWith("{"))return null;for(let n of Je(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 Na(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Ca(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Pa(e,t){let n=si(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Ca(),i=[],o=0;for(let a of Je(n.slice(1,-1))){if(!a.startsWith("{")){o++;continue}let c=ai(a),d=c[t.key_field];if(!d){o++;continue}let u=(t.partition_by??[]).map(l=>c[l]??"");i.push({key:d,fields:Na(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 Da(e,t){let n=si(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=Ca(),i=[],o=0,a=s((c,d,u)=>{let l=t.levels[d],p=d===t.levels.length-1;for(let f of Je(c.slice(1,-1))){let h={...u},m=null;if(l.shape==="object"){if(!f.startsWith("{")){o++;continue}let g=ai(f);for(let[w,y]of Object.entries(l.fields??{}))h[w]=g[String(y)]??"";if(!p&&typeof l.children=="string"){let w=Wm(f,l.children);m=w&&w.startsWith("[")?Nn(w,0):null}}else{if(!f.startsWith("[")){o++;continue}let g=Je(f.slice(1,-1));for(let[w,y]of Object.entries(l.fields??{})){let _=g[Number(y)];h[w]=_!==void 0&&At(_[0]??"")?Ia(_):""}if(!p&&typeof l.children=="number"){let w=g[l.children];m=w!==void 0&&w.startsWith("[")?Nn(w,0):null}}if(p){let g=h[t.key_field];if(!g){o++;continue}let w=(t.partition_by??[]).map(y=>h[y]??"");i.push({key:g,fields:Na(h,t.fields),orderPath:w,ordinal:r(w)});continue}m!==null&&a(m,d+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 Ra(e,t){return t.extractor==="object-array"?Pa(e,t):Da(e,t)}function Oa(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 Ma(e,t,n){return`spec.drift:${e}#${t}:${n}`}function Vm(e){return e.orderPath.join(" / ")||"(flat)"}function Fa(e,t,n,r){let i=[],o=s((u,l,p,f,h,m)=>{i.push({id:Ma(e.id,u,p),contract:e.id,dimension:u,status:l,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 l=a.get(u.key);if(!l){o("coverage","open",u.key,`${u.key} is declared by the specification but missing from the implementation`,`Partition ${Vm(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=l.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 d=new Map;for(let u of t){let l=u.orderPath.join("\0"),p=d.get(l);p?p.push(u):d.set(l,[u])}for(let[u,l]of d){let p=l.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(Oa(u,e.grounding,r))continue;let l=a.has(u);o("unrealized",l?"open":"warn",u,l?`${u} is referenced by the implementation but has no artefact`:`${u} is declared by the specification but not built yet`,l?`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 qm(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 d=Number(c[1]),u=t[i.counts];d!==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 ${d} 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 Ta(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 $a(e,t={}){let n=s(l=>({ok:!1,verdict:"no_opinion",reason:l,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(l=>t.contracts.includes(l.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(l=>`"${l}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=s(l=>{let p=[],f=[];for(let h of r){let m=l.get(h.spec.path),g=l.get(h.impl.path);if(m==null||g==null){let S=m==null?h.spec.path:h.impl.path;p.push(Ta(h.id,`Declared file could not be read: ${S}`)),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let w=Ra(m,h.spec),y=Ra(g,h.impl);if(w.error||y.error){p.push(Ta(h.id,w.error??y.error??"unknown")),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=w.dropped>0||y.dropped>0;f.push({id:h.id,measured:!0,specRecords:w.records.length,implRecords:y.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:`${w.dropped} specification and ${y.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(...Fa(h,w.records,y.records,e.files)),p.push(...qm(h,{spec:w.records.length,impl:y.records.length},l))}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 l of i(e.baselineSources).findings)l.id.startsWith("contract.unreadable:")||a.add(l.id);let c=new Map;for(let l of r)for(let p of l.exceptions??[])c.set(Ma(l.id,p.dimension,p.key),p);let d=o.findings.map(l=>{let p=c.get(l.id);return p?{...l,status:"info",exceptionReason:p.reason}:a.has(l.id)?{...l,status:"info",detail:`${l.detail}
|
|
28
|
+
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:l});d.sort((l,p)=>Aa[l.status]-Aa[p.status]||l.id.localeCompare(p.id));let u=d.some(l=>l.status==="open");return{ok:!u,verdict:u?"drifted":"aligned",reason:null,findings:d,contracts:o.contracts}}function oi(e){let t=e?.trim();return t||null}function Mn(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 d=n(c),u=r(d?.id),l=u?`contract "${u}"`:`contract #${a+1}`;if(!d)return o(`${l}: not an object`);if(!u)return o(`${l}: \`id\` is missing`);if(!r(d.reason))return o(`${l}: \`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(d[p]);if(!f)return o(`${l}: \`${p}\` is missing`);let h=r(f.extractor);if(!h)return o(`${l}: \`${p}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return o(`${l}: unknown \`${p}.extractor\` "${h}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return o(`${l}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(f.levels))return o(`${l}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(d.exceptions)?d.exceptions:[]){let f=n(p);if(!f||!r(f.reason))return o(`${l}: 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 Jm(e){let t=oi(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 zm(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 La(e,t={}){let n=s((m,g)=>Km.join(m,g),"join"),r=t.manifestPath??Cn,i=[],o={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(oi(k(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...o,manifestError:"not a git work tree"};let a=n(e,r);if(!Um(a))return{...o,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,d=null;try{({manifest:c,error:d}=Mn(xa(a,"utf8")))}catch(m){d=`manifest at ${r} could not be read: ${m.message}`}if(!c)return{...o,isRepo:!0,manifestError:d};let u=new Map;for(let m of zm(c))try{u.set(m,xa(n(e,m),"utf8"))}catch{u.set(m,null),i.push(`declared file unreadable in the working tree: ${m}`)}let l=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&&l.add(m);let f=null,h=new Map;if(t.includeBaseline!==!1){let m=Jm(e);if(!m)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(f=oi(k(e,["merge-base",`origin/${m}`,"HEAD"])),!f)i.push(`no merge-base with origin/${m} \u2014 every finding reported as new`);else for(let g of u.keys())h.set(g,k(e,["show",`${f}:${g}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:u,baselineSources:h,baseRef:f,files:l,skipped:i}}async function It(e,t={}){let n=await La(e,t);return{...$a(n,t),facts:n}}var Cn,Aa,ci=b(()=>{"use strict";J();Cn=".maind/spec-contracts.json";s(Pn,"endOfString");s(Dn,"skipComment");s(At,"isQuote");s(On,"isCommentStart");s(Nn,"sliceBalanced");s(Gm,"stripLeadingTrivia");s(Je,"splitTopLevel");s(Ia,"readStringLiteral");s(Bm,"escapeRe");s(si,"findSymbolArray");s(ai,"parseObjectFields");s(Wm,"objectFieldRaw");s(Na,"pickFields");s(Ca,"makeOrdinals");s(Pa,"extractObjectArray");s(Da,"extractNestedList");s(Ra,"extractRecords");s(Oa,"isGrounded");s(Ma,"findingId");s(Vm,"partitionOf");s(Fa,"compareContract");s(qm,"checkAssertions");s(Ta,"unreadable");Aa={open:0,warn:1,info:2,passed:3};s($a,"computeSpecDrift");s(oi,"trimOrNull");s(Mn,"parseManifest");s(Jm,"resolveDefaultBranch");s(zm,"declaredPaths");s(La,"gatherSpecDriftFacts");s(It,"checkSpecDrift")});var ja,li=b(()=>{"use strict";ja=[{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 Ha(e){let t=new Set;for(let[n,r]of e.paths)for(let i of ja){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let o=Ym(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function Ym(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
29
|
+
`):t.readUntracked(e)}var Ua=b(()=>{"use strict";li();s(Ha,"scanRiskFlags");s(Ym,"contentForPath")});var ze,Ka,Ye,Xe,di,Fn,$n,Ln,ui,Ga,Nt=b(()=>{"use strict";ze="1",Ka=`
|
|
30
30
|
CREATE TABLE IF NOT EXISTS meta (
|
|
31
31
|
key TEXT PRIMARY KEY,
|
|
32
32
|
value TEXT NOT NULL
|
|
@@ -85,7 +85,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
85
85
|
vec BLOB NOT NULL,
|
|
86
86
|
content_hash TEXT NOT NULL
|
|
87
87
|
);
|
|
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
|
|
88
|
+
`,Ye="schema_version",Xe="last_index_commit",di="last_indexed_at",Fn="embed_recipe_version",$n="embed_model",Ln="embed_dim",ui="last_synced_at",Ga="last_synced_commit"});function pi(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 Ba(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of pi(e.name))t.add(i);for(let i of pi(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function Wa(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 pi(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var fi=b(()=>{"use strict";s(pi,"splitIdentifier");s(Ba,"buildSearchText");s(Wa,"toFtsMatchQuery")});import{readFileSync as Va}from"node:fs";import{posix as qa}from"node:path";function Ja(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 Ae(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function za(e){return e==="added"?0:e==="modified"?1:2}function Xm(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 Ct,mi=b(()=>{"use strict";Ms();Lr();$s();Hs();J();Zs();Kr();Qr();ii();ci();Ua();Nt();fi();Ct=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(Ye),i=await this.store.countFiles()>0;(t.full||i&&r!==ze)&&await this.wipe();let o=Vs(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=zs(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 _=xn(y);if(w&&w.contentHash===_){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,Ba(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),l.filesParsed++,t.onProgress?.({path:m.path,done:f,total:o.length})}if(p.length>0){let m=await this.store.getNameIndex(),g=Ls(m);for(let w of p){let y=js(w,g);await this.store.replaceOutgoingEdges(y.srcKeys,y.edges)}}if(this.embedder&&t.embed){let m=await this.store.getNodesByKinds([...$r]),g=await this.store.getEmbeddingContentHashes(),w=[];for(let _ of m){let S=Os(_),v=xn(`${this.embedder.recipeVersion}\0${S}`);g.get(_.nodeKey)!==v&&w.push({nodeKey:_.nodeKey,text:S,hash:v})}let y=64;for(let _=0;_<w.length;_+=y){let S=w.slice(_,_+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(_+y,w.length);t.onProgress?.({path:"embedding symbols",done:E,total:w.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Fn,this.embedder.recipeVersion),await this.store.setMeta($n,this.embedder.model),await this.store.setMeta(Ln,String(this.embedder.dim))}await this.store.setMeta(Ye,ze),await this.store.setMeta(di,String(n));let h=St(this.repoRoot);return h&&await this.store.setMeta(Xe,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(di);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(Xe),schemaVersion:await this.store.getMeta(Ye),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Ae(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({...Ja(c),score:a.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Ae(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(d=>({nodeKey:d.nodeKey,score:Fs(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({...Ja(u),score:d.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Ae(n.maxDepth,3,5),o=Ae(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=Va(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(Ae(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Js(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Ae(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=En(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(St(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return ia(this.repoRoot,n,t)}async checkDivergence(t={}){return xt(this.repoRoot,t)}async checkNumberCollisions(t={}){return Tt(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Te(this.repoRoot,t,n)}async checkSpecDrift(t={}){return It(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=En(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Qs(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=Ha({paths:n,hunks:i,readUntracked:s(f=>this.readRepoFileHead(f,Xs),"readUntracked")}),c=Ws(n.keys()),d=Ae(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&&xn(g)!==m.contentHash;w&&(p++,o==="full"&&(o="partial"));let y=n.get(f.path)??"modified",_=i.get(f.path);for(let S of h)u.push(Xm(S,y,_,w))}return u.sort((f,h)=>za(f.change)-za(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:St(this.repoRoot),dirty:Ys(this.repoRoot),baseSha:t.since?Rn(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 Va(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(Ja,"toHit");s(Ae,"clampLimit");s(za,"changeRank");s(Xm,"classifyReviewSymbol")});import{createRequire as Qm}from"node:module";function Xa(){return Ya("node:sqlite")}function Qe(){if(Pt)return Pt;try{let{DatabaseSync:e}=Xa(),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(),Pt={ok:!0}}finally{t.close()}}catch(e){Pt={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Pt}function Zm(e){let{DatabaseSync:t}=Xa(),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 eh(e){let t=Ya("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 th(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function jn(e){let t=th(),n=s(i=>{let o=i==="node:sqlite"?Zm(e):eh(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=Qe();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=Qe();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 Ya,Pt,hi=b(()=>{"use strict";Ya=Qm(import.meta.url);s(Xa,"loadBuiltin");Pt=null;s(Qe,"probeBuiltinSqlite");s(Zm,"openBuiltin");s(eh,"openBetter");s(th,"backendOverride");s(jn,"openSqliteDatabase")});function Hn(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 Qa,Dt,Za=b(()=>{"use strict";hi();Nt();fi();s(Hn,"toNodeRow");Qa=400,Dt=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=jn(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Ka)}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?Hn(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Hn)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Hn)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Hn)}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=Wa(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
89
89
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
90
90
|
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
91
91
|
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
@@ -98,7 +98,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
98
98
|
FROM nodes n
|
|
99
99
|
WHERE n.kind = 'module'
|
|
100
100
|
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+=
|
|
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+=Qa)for(let a of n.slice(o,o+Qa))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
102
|
node_key, kind, name, qualified_name, file_path, language,
|
|
103
103
|
start_line, end_line, start_byte, end_byte, signature, doc
|
|
104
104
|
) 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 +108,26 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
108
108
|
content_hash = excluded.content_hash,
|
|
109
109
|
mtime_ms = excluded.mtime_ms,
|
|
110
110
|
size = excluded.size,
|
|
111
|
-
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as
|
|
111
|
+
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as nh}from"node:crypto";function Ze(e){return nh("sha256").update(e,"utf8").digest("hex")}function ec(e){return{node_key_hash:Ze(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:Ze(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?Ze(e.signature):null}}function tc(e){return{src_key_hash:Ze(e.srcKey),dst_key_hash:Ze(e.dstKey),kind:e.kind}}function nc(e,t,n){return{node_key_hash:Ze(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var rc=b(()=>{"use strict";s(Ze,"sha256");s(ec,"toCloudNode");s(tc,"toCloudEdge");s(nc,"toCloudEmbedding")});function gi(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ic(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function ih(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var et,tt,rh,yi=b(()=>{"use strict";Nt();rc();et=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},tt=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(Xe),lastSyncedAt:ic(await this.store.getMeta(ui))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(ec),n=(await this.store.getAllEdges()).map(tc),r=await this.store.getMeta(Ye)??ze,i=await this.store.getMeta(Xe),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=gi(t,this.chunk),l=gi(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(ui,String(Date.now())),i&&await this.store.setMeta(Ga,i),{nodes:t.length,edges:n.length,pruned:ih(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=>nc(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=gi(a,rh),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(Fn),n=await this.store.getMeta($n),r=ic(await this.store.getMeta(Ln));if(!t||!n||!r)throw new et("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 et(`${n} failed (HTTP ${t.status})${o?`: ${o}`:""}`,t.status,o)}return i}},rh=250;s(gi,"chunkArray");s(ic,"numOrNull");s(ih,"numOr0")});var oc={};B(oc,{CodeIndexSync:()=>tt,DEFAULT_DB_RELPATH:()=>bi,SyncError:()=>et,createCodeIndexSync:()=>sh,createNodeCodeIndex:()=>_i,openSqliteDatabase:()=>jn,probeBuiltinSqlite:()=>Qe});import{mkdirSync as oh}from"node:fs";import{posix as wi}from"node:path";function _i(e){let t=e.dbPath??wi.join(e.repoRoot,bi);oh(wi.dirname(t),{recursive:!0});let n=new Dt(t),r=new kn;return new Ct({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function sh(e){let t=e.dbPath??wi.join(e.repoRoot,bi),n=e.projectKey??bs(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 Dt(t);return new tt(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var bi,ki=b(()=>{"use strict";_s();Ds();mi();Za();yi();yi();hi();bi=".maind/code-index.sqlite";s(_i,"createNodeCodeIndex");s(sh,"createCodeIndexSync")});import{execFileSync as sc}from"node:child_process";import{existsSync as ac,realpathSync as cc}from"node:fs";import{createRequire as ah}from"node:module";import{basename as ch,dirname as lh,isAbsolute as lc,join as dh,relative as dc,resolve as Un,sep as uc}from"node:path";function pc(){let e=Qe();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return ah(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 fc(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=sc("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 hc(e,t=W(),n=process.cwd()){let r=lc(e)?[e]:[Un(t,e),Un(n,e)];for(let i of r){let o=lh(i);if(!ac(o))continue;let a;try{a=cc(o)}catch{continue}let c=gc(a);if(c===null)continue;let d=dc(c,dh(a,ch(i)));if(!d.startsWith(".."))return{repoRoot:c,repoRelPath:d.split(uc).join("/")}}return null}function Kn(e,t=W(),n=process.cwd()){let r=lc(e)?[e]:[Un(t,e),Un(n,e)];for(let i of r){if(!ac(i))continue;let o;try{o=cc(i)}catch{continue}let a=gc(o);if(a===null)continue;let c=dc(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(uc).join("/")}}return null}function gc(e){try{let t=sc("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 yc(){return _i({repoRoot:W()})}var mc,Ot=b(()=>{"use strict";ki();s(pc,"probeNativeStore");s(fc,"isNativeStoreUnavailable");mc="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(hc,"resolveRepoRootForPath");s(Kn,"resolveRepoRootForDir");s(gc,"gitToplevelOf");s(yc,"defaultEngineFactory")});var Ec=b(()=>{"use strict"});import{readFileSync as mh}from"node:fs";import{join as vi}from"node:path";function Ei(e){let t=new Set;for(let n of e.matchAll(hh))t.add(n[1]);return t}function xi(e){return new Set([...e].map(t=>t.split("-")[0]))}function Nc(e){return e.split(`
|
|
112
112
|
`).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
|
|
113
|
-
`)}function
|
|
114
|
-
`).filter(Boolean)}function
|
|
115
|
-
`).filter(Boolean)),d=s(p=>c.has(p)?
|
|
116
|
-
`).filter(i=>i.length>0&&n.some(o=>
|
|
117
|
-
`;)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 d=c[0],u=e.indexOf(d,n+d.length);n=u===-1?r:u+d.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 d=e[c];if(d==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(d==="."&&!r){o();continue}n+=d}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
|
|
118
|
-
`).filter(Boolean)){let[p,...f]=l.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 d=[],u=new Set(c);for(let{ref:l,content:p}of n)!a.has(l.path)&&!u.has(l.path)&&d.push({name:l.name,version:l.version,content:p});for(let l of c){let p=
|
|
119
|
-
`).filter(Boolean).slice(-1)[0]}}function
|
|
120
|
-
`).map(i=>i.trim()).filter(Boolean)}}function
|
|
121
|
-
`)){if(!o.startsWith("worktree "))continue;let a=o.slice(9).trim();if(!a||a===i||!
|
|
122
|
-
`)),this.machineLabel=
|
|
123
|
-
`,{mode:384}),
|
|
124
|
-
`)}function
|
|
125
|
-
`)}function
|
|
113
|
+
`)}function Ri(e){let t=xi(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let o=Nc(i),a=new Set;for(let c of o.matchAll(gh)){let d=c[2],u=d.split("-")[0];if(!t.has(u)||e.tokens.has(d))continue;let l=`${c[1]}-${d}`;a.has(l)||(a.add(l),n.push({file:r,klass:l,token:d,namespace:u}))}}return n}function xc(e){return`${e.file} ${e.klass}`}function yh(e,t){let n=t===null?null:new Set(t.map(xc));return e.map(r=>({...r,status:n!==null&&n.has(xc(r))?"info":"open"}))}function Cc(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function Ti(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Tc(e,t){let n=k(e,["ls-files","--",...t]);return n===null?[]:n.split(`
|
|
114
|
+
`).filter(Boolean)}function Mt(e,t={}){let n=t.maxFileBytes??wh,r=new Set;for(let u of Tc(e,["*.css"])){let l=Si(vi(e,u),n);if(l!==null)for(let p of Ei(l))r.add(p)}if(r.size===0)return{ok:!1,verdict:"no_opinion",tokenCount:0,namespaceCount:0,findings:[],scannedFiles:0};let i=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(u=>Rc.map(l=>`${u.replace(/\/+$/,"")}/**/${l}`)):Rc,o=[];for(let u of Tc(e,i)){if(!Ti(u))continue;let l=Si(vi(e,u),n);l!==null&&o.push({path:u,content:l})}let a=Ri({tokens:r,sources:o}),c=yh(a,t.includeBaseline===!1?null:bh(e,i,n,t.baseRef)),d=Cc(r.size,c.length);return{ok:d!=="no_opinion"&&!c.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:xi(r).size,findings:c,scannedFiles:o.length}}function bh(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(`
|
|
115
|
+
`).filter(Boolean)),d=s(p=>c.has(p)?k(e,["show",`${o}:${p}`]):Si(vi(e,p),n),"atBase"),u=new Set;for(let p of Ac(e,o,["*.css"])){let f=d(p);if(f!==null)for(let h of Ei(f))u.add(h)}if(u.size===0)return null;let l=[];for(let p of Ac(e,o,t)){if(!Ti(p))continue;let f=d(p);f===null||f.length>n||l.push({path:p,content:f})}return Ri({tokens:u,sources:l})}function Ac(e,t,n){let r=k(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
|
|
116
|
+
`).filter(i=>i.length>0&&n.some(o=>_h(i,o)))}function _h(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 Si(e,t){try{let n=mh(e,"utf8");return n.length>t?null:n}catch{return null}}var Ic,hh,gh,Rc,wh,Pc=b(()=>{"use strict";J();Ic=["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"],hh=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,gh=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Ic.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(Ei,"extractTokens");s(xi,"deriveNamespaces");s(Nc,"stripCommentLines");s(Ri,"evaluateThemeClasses");s(xc,"findingKey");s(yh,"gradeAgainstBaseline");s(Cc,"deriveThemeClassVerdict");Rc=["*.ts","*.tsx","*.js","*.jsx"],wh=15e5;s(Ti,"isScannableSource");s(Tc,"listTracked");s(Mt,"checkThemeClassDrift");s(bh,"baselineFindings");s(Ac,"listTrackedAt");s(_h,"matchesSourcePattern");s(kh,"resolveBaseRef");s(Si,"safeRead")});import{readFileSync as vh}from"node:fs";import{join as Sh,posix as Eh}from"node:path";function Dc(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]!==`
|
|
117
|
+
`;)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 d=c[0],u=e.indexOf(d,n+d.length);n=u===-1?r:u+d.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 d=e[c];if(d==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(d==="."&&!r){o();continue}n+=d}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 Ft(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 Oc(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(xh.test(a))return null;let c,d=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(d){if(!Ft(d[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=Ft(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=Ft(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>we(p)?.name??"").filter(p=>p.length>0&&p!=="public"),l=[];for(let p of Ft(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:[...Ai]};!m&&Ai.includes(h)&&l.push(h)}return{tables:c,roles:u,writePrivs:l}}function Ni(e){let t=new Map,n=[...e].sort((r,i)=>le(r.version,i.version));for(let r of n){let i=Dc(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 l=we(c[2]);if(!l||l.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(a)&&t.has(l.name))continue;t.set(l.name,{createdIn:r.version,anonAddressed:!1,authWritesRevoked:new Set});continue}let d=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(a);if(d){let l=d[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let p of Ft(l)){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 l=we(u[1]),p=we(u[2]);if(l&&p&&l.schema==="public"){let f=t.get(l.name);f&&(t.delete(l.name),t.set(p.name,f))}continue}if(/^REVOKE\b/i.test(a)){let l=Oc(a);if(!l)continue;let p=l.tables==="all_in_public"?[...t.keys()]:l.tables,f=l.roles.includes("anon"),h=l.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 w of l.writePrivs)g.authWritesRevoked.add(w)}continue}}}return t}function Ii(e){let t=[];for(let[n,r]of Ni(e)){let i=[];r.anonAddressed||i.push("anon"),Ai.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 Mc(e){let t=Ii(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Ii(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(d=>i.has(d))?"info":"open",c=r.missing.map(d=>d==="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 Fc(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function Th(e,t){try{let n=vh(e,"utf8");return n.length>t?null:n}catch{return null}}function Ah(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} \u2014 findings reported ungraded (open)`),null;let a=new Set,c=[];for(let l of o.split(`
|
|
118
|
+
`).filter(Boolean)){let[p,...f]=l.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 d=[],u=new Set(c);for(let{ref:l,content:p}of n)!a.has(l.path)&&!u.has(l.path)&&d.push({name:l.name,version:l.version,content:p});for(let l of c){let p=Eh.basename(l),f=We(p);if(f===null)continue;let h=k(e,["show",`${r}:${l}`]);if(h===null)return i.push(`could not read ${l} at ${r} \u2014 baseline degraded`),null;d.push({name:p,version:f,content:h})}return d}function $t(e,t={}){let n=t.maxFileBytes??Rh,r=[],i=Re(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=aa(e);a=f?`origin/${f}`:null,a===null&&r.push("no default branch resolvable \u2014 findings reported ungraded (open)")}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],d=[];for(let f of i){let h=[];for(let w of f.files){let y=Th(Sh(e,w.path),n);if(y===null){r.push(`could not read ${w.path} \u2014 excluded from the fold`);continue}h.push({ref:w,content:y})}let m=h.map(({ref:w,content:y})=>({name:w.name,version:w.version,content:y})),g=a===null?null:Ah(e,f.dir,h,a,r);c.push(...Mc({dir:f.dir,files:m,baseFiles:g})),d.push({dir:f.dir,migrationCount:m.length,tableCount:Ni(m).size})}let u=d.reduce((f,h)=>f+h.migrationCount,0),l=Fc(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:l!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:l,findings:c,facts:{projects:d,baseRef:a,skipped:r}}}var Ai,xh,Rh,$c=b(()=>{"use strict";J();Et();s(Dc,"stripSql");s(we,"normalizeQualifiedIdent");s(Ft,"splitTopLevel");Ai=["INSERT","UPDATE","DELETE"],xh=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(Oc,"parseTableRevoke");s(Ni,"foldTableAcl");s(Ii,"evaluateTableAcl");s(Mc,"computeTableAclFindings");s(Fc,"deriveTableAclVerdict");Rh=5e6;s(Th,"safeRead");s(Ah,"baseFilesFor");s($t,"checkTableAclLint")});import{existsSync as Ci,readdirSync as Ih,readFileSync as Nh}from"node:fs";import{spawnSync as Ch}from"node:child_process";import{dirname as Ph,join as Pi,posix as Dh}from"node:path";function jc(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 ${Di} 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 ${Di} 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(le);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(le),d=new Map,u=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let h=d.get(f)??[];h.push(p),d.set(f,h)}else u.push(p)}for(let[p,f]of d)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(le),h=e.remote.versions.filter(m=>!o.has(m)).sort(le);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 l=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:l,findings:t,db:n}}function Hc(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Kc(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 Lc(e,t,n){let r=e(t,Oh,n);return r.ok===!1?Kc(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
|
|
120
|
+
`).map(i=>i.trim()).filter(Boolean)}}function Gc(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 Mh(e){let t=k(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=Ph(t);return n===e?null:n}function Fh(e,t,n){let r=Dh.dirname(t),o=[{path:Pi(e,r,"config.toml"),source:"worktree"}],a=Mh(e);a&&o.push({path:Pi(a,r,"config.toml"),source:"main_worktree"});for(let c of o)if(Ci(c.path))try{let d=Gc(Nh(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 $h(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||!Ci(a))continue;let c=Pi(a,t);if(Ci(c))try{for(let d of Ih(c)){let u=We(d);u!==null&&!n.has(u)&&n.set(u,a)}}catch{}}return n}function Oi(e,t={}){let n=t.runPsql??Uc,r=t.timeoutMs??15e3,i=[],o=Re(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=Fh(e,p.dir,i),h=f.source==="missing"?null:Lc(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),m=t.remoteDbUrl!==void 0?Lc(n,t.remoteDbUrl,r):null,g=jc({dir:p.dir,fileVersions:p.files.map(w=>w.version),config:f,ledger:h,siblingVersions:$h(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=Hc(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 Di,Uc,Oh,Bc=b(()=>{"use strict";J();Et();Di=54322;s(jc,"evaluateLedgerProject");s(Hc,"deriveLedgerVerdict");Uc=s((e,t,n)=>{let r=Ch("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"),Oh="select version from supabase_migrations.schema_migrations order by version";s(Kc,"classifyLedgerError");s(Lc,"readLedger");s(Gc,"parseDbPort");s(Mh,"mainWorktreeRoot");s(Fh,"resolveConfig");s($h,"gatherSiblingVersions");s(Oi,"checkMigrationLedgerDrift")});var Wc,Lt=b(()=>{"use strict";Ec();mi();Kr();li();Qr();Vr();ii();Pc();ci();Et();$c();Bc();hn();Lr();Nt();Wc="0.1.0"});import{execFile as Zc}from"node:child_process";import{randomUUID as Vh}from"node:crypto";function Qh(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return Fi.test(t)?t:Vh()}function $i(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function Zh(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 eg(e){return await new Promise(t=>{Zc("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(tg(r))})})}function tg(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 ng(){return await new Promise(e=>{Zc("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 rg(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function ig(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=Fi.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(o=>{Fi.test(o)&&(n=o.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var Qc,el,qh,Jh,zh,Yh,Xh,Fi,qn,Li=b(()=>{"use strict";Ke();Qc=45e3,el=3e4,qh=5,Jh=120,zh=3e4,Yh=15*6e4,Xh=1500,Fi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Qh,"resolveClientSessionId");s($i,"autoAnnounceDisabled");s(Zh,"autoWorkingPathsEnabled");qn=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??ng,this.gitBranchObject=t.gitBranchObject??eg,this.log=t.log??(i=>process.stderr.write(i+`
|
|
122
|
+
`)),this.machineLabel=rg(r?.machine_label),this.enabled=this.projectKey!==null&&!$i(n,r),this.workingPathsEnabled=Zh(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??ig(n,Qh(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<Qc||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<Qc||(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,Xh).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(zh*2**(this.consecutiveFailures-1),Yh);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:Jh,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(eg,"defaultGitBranchObject");s(tg,"normalizeObjectId");s(ng,"defaultGitBranch");s(rg,"normalizeMachineLabel");s(ig,"staticIdentity")});import{mkdirSync as tl,readdirSync as ol,readFileSync as og,renameSync as nl,statSync as sg,unlinkSync as sl,writeFileSync as rl}from"node:fs";import{homedir as ag}from"node:os";import{join as nt}from"node:path";function al(){return nt(ag(),".maind","presence")}function cl(e,t){return nt(e,t)}function ll(e){let t=e.baseDir??al(),n=cl(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:[]};tl(n,{recursive:!0,mode:448}),c=nt(n,`${u.sessionId}.json`);let f=`${c}.tmp-${r}`;rl(f,JSON.stringify(p),{mode:384}),nl(f,c),il(n,a(),c)}catch{}},endSession(){try{c&&sl(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};tl(n,{recursive:!0,mode:448}),c=nt(n,`${u.sessionId}.json`);let p=`${c}.tmp-${r}`;rl(p,JSON.stringify(l),{mode:384}),nl(p,c),il(n,a(),c)}catch{}}}}function il(e,t,n){try{for(let r of ol(e)){if(!r.endsWith(".json"))continue;let i=nt(e,r);if(i!==n)try{t-sg(i).mtimeMs>cg&&sl(i)}catch{}}}catch{}}function rt(e,t=al()){try{let n=cl(t,e),r=[];for(let i of ol(n))if(i.endsWith(".json"))try{let o=JSON.parse(og(nt(n,i),"utf8")),a=lg(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function lg(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 cg,Jn=b(()=>{"use strict";cg=120*6e4;s(al,"presenceSnapshotBaseDir");s(cl,"projectDir");s(ll,"createSnapshotStore");s(il,"pruneStale");s(rt,"readSnapshots");s(lg,"parseSnapshot")});import{execFileSync as dg}from"node:child_process";import{createHash as ug,randomUUID as pg}from"node:crypto";import{existsSync as fg,mkdirSync as mg,readdirSync as hg,readFileSync as gg,renameSync as yg,statSync as ji,unlinkSync as ul,writeFileSync as wg}from"node:fs";import{homedir as bg}from"node:os";import{basename as _g,join as be}from"node:path";function it(e){return be(e??be(bg(),".maind","presence"),"identity")}function pl(e,t){if(e){let n=_g(e).replace(/\.jsonl$/i,"");if(jt.test(n))return n.toLowerCase()}return t&&jt.test(t)?t.toLowerCase():null}function fl(e){let t=e.nowMs??Date.now();mg(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()};wg(r,JSON.stringify(i,null,2)+`
|
|
123
|
+
`,{mode:384}),yg(r,n),xg(e.dir,t)}function ml(e,t,n,r=Date.now()){try{let i=ji(be(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function hl(e,t){try{ul(be(e,`${t}.json`))}catch{}}function xg(e,t){try{for(let n of hg(e))if(n.endsWith(".json"))try{let r=ji(be(e,n));t-r.mtimeMs>vg&&ul(be(e,n))}catch{}}catch{}}function Rg(e){return gl(e)?.file??null}function gl(e){let t=be(e.dir,`${e.agentPid}.json`);try{if(!fg(t))return null;let n=ji(t);if(n.mtimeMs<e.bridgeStartMs-Sg)return null;let r=JSON.parse(gg(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!jt.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!Tg(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function dl(e){return e.replace(/\/+$/,"")}function Tg(e,t){let n=dl(e),r=dl(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function Ag(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=ug("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 Ig(e){if(process.platform==="win32")return null;try{let t=dg("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function Ng(){try{return j()}catch{return null}}var jt,kg,vg,Sg,Eg,zn,Yn=b(()=>{"use strict";K();jt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,kg=8,vg=48*60*6e4,Sg=6e4,Eg="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(it,"identityDirPath");s(pl,"transcriptStemOf");s(fl,"writeAgentIdentityFile");s(ml,"identityFileStale");s(hl,"deleteAgentIdentityFile");s(xg,"pruneIdentityDir");s(Rg,"readAgentIdentityFile");s(gl,"readAgentIdentityEntry");s(dl,"normDir");s(Tg,"sameSessionTree");s(Ag,"uuidV5");s(Ig,"processStartTime");zn=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??it(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=jt.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??Ng)(),o=(t.ppidStart??Ig)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=Ag(`${i}|${this.agentPid}|${o}|${t.projectKey}`,Eg),this.source="derived";return}this.id=pg(),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(!jt.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>kg&&this.aliases.shift())}activityAtMs(){return gl({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let t=Rg({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()});return t===null?null:t.transcript_stem.toLowerCase()}};s(Ng,"defaultDeviceId")});var Hi=b(()=>{"use strict"});import{createReadStream as $g,existsSync as Lg}from"node:fs";import{stat as jg}from"node:fs/promises";import{createInterface as Hg}from"node:readline";async function Ui(e){if(!e||!Lg(e))return null;let t;try{t=await jg(e)}catch{return null}let n=0,r=0,i=0;return await new Promise(o=>{let a=$g(e,{encoding:"utf-8"}),c=Hg({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 wl=b(()=>{"use strict";s(Ui,"summariseTranscript")});var bl=b(()=>{"use strict"});function Xn(e){if(!e)return null;let t=null;for(let n of e.matchAll(Kg)){let r=n[1].toLowerCase();Ug.has(r)&&(t=r)}return t}var Ug,Kg,Qn=b(()=>{"use strict";Ug=new Set(["low","medium","high","xhigh","max"]),Kg=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(Xn,"detectEffortLevel")});import{createReadStream as Gg,existsSync as Bg}from"node:fs";import{createInterface as Wg}from"node:readline";function Ht(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Zg(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 Ki(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function ey(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
124
|
+
`)}function ty(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 ny(e,t,n){return Vg.test(e)?{polarity:-1,magnitude:ot.rework,kind:"rework"}:n&&qg.test(e)?{polarity:-1,magnitude:ot.correction,kind:"correction"}:Jg.test(e)?{polarity:1,magnitude:ot.acceptance,kind:"acceptance"}:t!==null&&ty(t,e)?{polarity:-1,magnitude:ot.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function ry(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:kl}}async function Gi(e){let t=ry("");if(!e||!Bg(e))return t;let n=[],r=new Map,i=null,o=!1,a=null;await new Promise(p=>{let f=Gg(e,{encoding:"utf-8"}),h=Wg({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 _=y.message?.role,S=y.isSidechain===!0,v=y.message?.usage;if(_==="assistant"&&v&&(t.input_tokens+=Ht(v.input_tokens),t.output_tokens+=Ht(v.output_tokens),t.cache_read_tokens+=Ht(v.cache_read_input_tokens),t.cache_creation_tokens+=Ht(v.cache_creation_input_tokens)),_==="assistant"&&typeof y.message?.model=="string"&&y.message.model&&y.message.model!==Xg){let T=y.timestamp?Date.parse(y.timestamp):Number.NaN;Zg(r,y.message.model,S,Ht(v?.output_tokens),Number.isFinite(T)?T:0)}if(_==="assistant")for(let T of Ki(y.message?.content)){if(T.type!=="tool_use"||typeof T.name!="string"||!T.name.startsWith(_l))continue;let Y=T.name.slice(_l.length);Y&&(t.maind_tool_calls[Y]=(t.maind_tool_calls[Y]??0)+1)}if(S)return;if(_==="assistant"){t.assistant_turns++;let T=Ki(y.message?.content),Y=!1;for(let _o of T)_o.type==="tool_use"&&(t.tool_calls++,Y=!0,_o.name==="AskUserQuestion"&&t.agent_questions++);o=Y;return}if(_!=="user")return;let E=Ki(y.message?.content),R=ey(E);if(R.includes(zg)){t.interrupts++,n.push({polarity:-1,magnitude:ot.interrupt,kind:"interrupt"});return}if(E.some(T=>T.type==="tool_result"&&T.is_error===!0&&typeof T.content=="string"&&T.content.includes(Yg))){t.tool_denials++,n.push({polarity:-1,magnitude:ot.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=Xn(R);A&&(i=A);let N=ny(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*Qg+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 _l,kl,Vg,qg,Jg,zg,Yg,Xg,Qg,ot,vl=b(()=>{"use strict";Qn();_l="mcp__maind__",kl="2026-08-16",Vg=/(\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,Jg=/(\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,zg="[Request interrupted by user",Yg="The user doesn't want to proceed with this tool use",Xg="<synthetic>",Qg=.7,ot={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(Ht,"num");s(Zg,"bumpModel");s(Ki,"asBlocks");s(ey,"textOf");s(ty,"isRepeat");s(ny,"classifyGenuine");s(ry,"emptyAnalysis");s(Gi,"analyzeSession")});function Bi(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 Sl=b(()=>{"use strict";s(Bi,"ingestBody")});import{createReadStream as iy,existsSync as oy}from"node:fs";import{createInterface as sy}from"node:readline";function El(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function ly(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
125
|
+
`)}function Tl(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 dy(e){let t=e.message?.role;if(t==="assistant")return{holder:El(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=El(e.message?.content),r=ly(n);return r.includes(ay)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(cy))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function Wi(e){let t=Tl("");if(!e||!oy(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(d=>{let u=iy(e,{encoding:"utf-8"}),l=sy({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=dy(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>=xl*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(y/1e3),c.length<Rl&&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 ay,cy,xl,Rl,Al=b(()=>{"use strict";ay="[Request interrupted by user",cy="The user doesn't want to proceed with this tool use",xl=60,Rl=200;s(El,"asBlocks");s(ly,"textOf");s(Tl,"emptySpan");s(dy,"classify");s(Wi,"analyzeSpan")});var Il=b(()=>{"use strict";Qn();Hi()});var Nl=b(()=>{"use strict"});import{homedir as uy}from"node:os";import{join as py}from"node:path";var fy,my,Cl=b(()=>{"use strict";fy=uy(),my=py(fy,".claude","projects")});var Vi=b(()=>{"use strict";Hi();wl();bl();vl();Sl();Al();Il();Qn();Nl();Cl()});function hy(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":j()}}async function Pl(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:hy(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 Zn,qi=b(()=>{"use strict";K();Zn=process.env.MAIND_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";s(hy,"ingestHeaders");s(Pl,"postMetrics")});function Dl(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function Ml(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 st(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 Ut(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function Fl(e,t,n){let r=n.maxAgeMs??Ol,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,a=Ml(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)Dl(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 ${Ut(d.last_seen_seconds+o)} ago)${u.note?` \u2014 note: "${u.note}"`:""}, claim expires in ${Ut(u.remaining_seconds)}`);if(n.via==="ppid"&&d.is_own_user){for(let u of d.working_paths)if(Dl(t,u)){c.push(`'${u}' has recent changes by your own peer session ${d.session_id_short}${d.branch?` (branch ${d.branch})`:""}, last seen ${Ut(d.last_seen_seconds+o)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${Ut(o)} ago, advisory \u2014 never a lock):
|
|
126
126
|
`+c.map(d=>` \u2022 ${d}`).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 $l(e,t,n,r=Ol,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=Ml(e,a),d=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 d;let u=c.reduce((m,g)=>m+g.claims.length,0),l=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=l>0?`, ${l} presence-only`:"",h=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${Ut(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return d!==null?`${d}
|
|
129
|
+
${h}`:h}var Ol,Ji=b(()=>{"use strict";s(Dl,"prefixConflict");Ol=10*6e4;s(Ml,"parsePeers");s(st,"selectOwnSnapshot");s(Ut,"ageDisplay");s(Fl,"adviseOnPath");s($l,"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 er(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function ne(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var re=b(()=>{"use strict";s(I,"readHookInput");s(er,"transcriptPathOf");s(ne,"toolFilePathOf")});function at(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function _e(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function Ll(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}var ct=b(()=>{"use strict";s(at,"denyPayload");s(_e,"advisoryPayload");s(Ll,"postAdvisoryPayload")});import{realpathSync as gy}from"node:fs";import{basename as jl,dirname as Hl,join as yy}from"node:path";function Ne(e){let t=Hl(e),n=[jl(e)];for(;;)try{let r=gy(t);return yy(r,...n.reverse())}catch{let r=Hl(t);if(r===t)return e;n.push(jl(t)),t=r}}var tr=b(()=>{"use strict";s(Ne,"realpathOfUnwritten")});import{mkdir as wy,readFile as by,writeFile as _y,rename as ky}from"node:fs/promises";import{existsSync as Kl}from"node:fs";import{homedir as vy}from"node:os";import{join as Gl}from"node:path";function Ul(){return{config:null,sessions:{},pending_metrics:[]}}async function M(){if(!Kl(nr))return Ul();try{let e=await by(nr,"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
|
+
`),Ul()}}async function ie(e){Kl(Ce)||await wy(Ce,{recursive:!0,mode:448});let t=`${nr}.tmp`;await _y(t,JSON.stringify(e,null,2),{mode:384}),await ky(t,nr)}function zi(e){return e.thresholds??e.config?.thresholds??Sy}var Ce,nr,Sy,Pe=b(()=>{"use strict";Ce=Gl(vy(),".maind"),nr=Gl(Ce,"state.json"),Sy={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(Ul,"emptyState");s(M,"loadState");s(ie,"saveState");s(zi,"resolveThresholds")});import{existsSync as Ey,realpathSync as xy,statSync as Ry}from"node:fs";import{dirname as Bl,isAbsolute as Ty,join as Ay}from"node:path";function Cy(e,t){let n=e.filter(i=>Wl.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 Py(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function Dy(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 Yi(e){let t=Bl(e);for(;;){try{if(Ry(t).isDirectory())return t}catch{}let n=Bl(t);if(n===t)return t;t=n}}async function Oy(e,t,n){let r=await n.load();if(Py(r,e,t))return null;Dy(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=>Wl.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:Iy,metric_value:1},{session_id:e,metric_key:Ny,metric_value:o}),await n.save(a),Cy(i,t)}async function Vl(){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=ne(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=Ty(r)?r:Ay(i,r),a=Ey(o)?xy(o):Ne(o),c=oe(Yi(a)),d=await Oy(n,c,{load:M,save:ie,check:s(async u=>(await xt(u,{includeRelease:!1})).findings,"check")});return d!==null&&process.stdout.write(_e(d)),0}catch{return 0}}var Wl,Iy,Ny,Xi=b(()=>{"use strict";Lt();Le();ct();re();tr();Pe();Wl=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],Iy="repo_health_hook_runs",Ny="repo_health_hook_findings";s(Cy,"formatRepoHealth");s(Py,"alreadySeen");s(Dy,"markSeen");s(Yi,"nearestExistingDir");s(Oy,"repoHealthForEdit");s(Vl,"runOnRepoHealth")});import{existsSync as My,readFileSync as Fy,realpathSync as $y}from"node:fs";import{isAbsolute as Jl,join as zl,posix as Ly,relative as jy,sep as Hy}from"node:path";function ql(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function Wy(e,t){return{contracts:t.filter(r=>ql(r.spec)===e||ql(r.impl)===e).map(r=>r.id),theme:Gy.test(e),acl:By.test(e)}}function Vy(e){return e.contracts.length===0&&!e.theme&&!e.acl}function qy(e,t,n,r,i=Date.now()){let o=e.write_health_seen??{},a=o[t]??{},c=new Set(a[n]?.keys??[]),d=r.filter(u=>!c.has(u.key));if(d.length>0){for(let u of d)c.add(u.key);a[n]={at:new Date(i).toISOString(),keys:[...c]},o[t]=a,e.write_health_seen=o}return d}function Jy(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 zy(e,t){let n=jy(e,t);return!n||n.startsWith("..")||Jl(n)?null:n.split(Hy).join(Ly.sep)}function Yy(e){try{let t=Fy(zl(e,Cn),"utf8"),{manifest:n}=Mn(t);return n?.contracts??[]}catch{return[]}}async function Yl(){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=ne(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=Jl(r)?r:zl(i,r),a=My(o)?$y(o):Ne(o),c=oe(Yi(a)),d=zy(c,a);if(d===null)return 0;let u=Wy(d,Yy(c));if(Vy(u))return 0;let l=[];if(u.contracts.length>0)try{let m=await It(c,{contracts:u.contracts});for(let g of m.findings)g.status==="open"&&l.push({key:`spec:${g.id}`,line:`spec-drift (${g.contract}): ${g.detail}`})}catch{}if(u.theme)try{let m=Mt(c);for(let g of m.findings)g.status==="open"&&l.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=$t(c);for(let g of m.findings)g.status==="open"&&l.push({key:`acl:${g.id}`,line:`table-acl-lint: \`${g.table}\` (created in ${g.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let p=await M(),f=qy(p,n,c,l);p.pending_metrics.push({session_id:n,metric_key:Uy,metric_value:1},{session_id:n,metric_key:Ky,metric_value:f.length}),await ie(p);let h=Jy(f,d);return h!==null&&process.stdout.write(Ll(h)),0}catch{return 0}}var Uy,Ky,Gy,By,Xl=b(()=>{"use strict";Lt();Le();ct();re();Xi();tr();Pe();Uy="write_health_hook_runs",Ky="write_health_hook_findings",Gy=/\.(tsx?|jsx?|css)$/,By=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(ql,"declPath");s(Wy,"routesForPath");s(Vy,"routesAreEmpty");s(qy,"takeUnreported");s(Jy,"formatWriteHealth");s(zy,"repoRelative");s(Yy,"readContracts");s(Yl,"runOnWriteHealth")});var ld={};B(ld,{agentHostPidCandidates:()=>ue,closeTrackedSession:()=>id,effectiveConfig:()=>De,grandparentPid:()=>sd,recordGuardSignals:()=>rd,runFlush:()=>pw,runHookStatus:()=>fw,runOnFileEdit:()=>lw,runOnFileWrite:()=>cw,runOnRepoHealth:()=>Vl,runOnSessionStart:()=>rw,runOnToolUse:()=>sw,runOnWriteHealth:()=>Yl,runSessionEndMetrics:()=>Zi,runSyncConfig:()=>hw,writeIdentitySideChannel:()=>Qi});import{execFileSync as Zl}from"node:child_process";import{existsSync as or,readFileSync as ed,realpathSync as Xy}from"node:fs";import{writeFile as Qy}from"node:fs/promises";import{homedir as td}from"node:os";import{isAbsolute as ir,join as Kt,relative as nd}from"node:path";function rd(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]??{},d=new Date(r).toISOString();i&&(c.consulted_at=d),o&&(c.reviewed_at=d),a[t]=c,e.guard_signals=a}function id(e,t,n=Date.now()){nw(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 nw(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>rr&&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>rr&&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>rr&&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>rr&&delete e.sessions[n]}}function De(e){if(e.config)return e.config;let t=C();return t===null?null:{api_key:t,endpoint:Zn}}function od(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 rw(){let e=await M();if(De(e)===null)return 0;let t=await I(),n=cd(t);if(n===null)return 0;od(e,n),await ie(e);try{Qi(t,n)}catch{}try{let r=F();if(r!==null){let i=rt(r),o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=st(i,{hostPids:ue(),cwd:o}),c=$l(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=_t(iw());if(Ar(r)&&un(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 iw(){try{let e=Kt(td(),".claude","settings.json");return or(e)?ed(e,"utf8"):null}catch{return null}}function Qi(e,t,n,r=it()){let i=n??ue();if(i.length===0)return;let o=pl(er(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)fl({dir:r,agentPid:c,sessionId:t,transcriptStem:o,cwd:a})}function sd(){try{if(process.platform==="win32")return null;let e=Zl("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 ue(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=sd();return n!==null&&n>1&&n!==t&&e.push(n),e}async function sw(){let e=await M();if(De(e)===null)return 0;let t=await I(),n=cd(t)??"unknown",r=od(e,n);r.tool_call_count+=1;try{let a=ue().filter(c=>ml(it(),c,ow));n!=="unknown"&&a.length>0&&Qi(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),rd(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 Ui(r.transcript_path);a&&(r.token_count=a.total_tokens,await uw(e,r))}return await ie(e),0}function aw(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 cw(){try{let e=await I();if((e.tool_name??"")!=="Write")return 0;let t=ne(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=ir(t)?t:Kt(n,t);if(or(r))return 0;let i=oe(n),o=nd(i,Ne(r));if(o.length===0||o.startsWith("..")||ir(o))return 0;let a=await Te(i,o);return!a.taken||a.namespace===null||process.stdout.write(at(aw(a,a.namespace))),0}catch{return 0}}async function lw(){try{let e=await I(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=ne(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=ir(n)?n:Kt(r,n),o=F();if(o===null)return 0;let a=rt(o);if(a.length===0)return 0;let c=st(a,{hostPids:ue(),cwd:r});if(c===null)return 0;let d=oe(r),u=or(i)?Xy(i):Ne(i),l=nd(d,u).replace(/\\/g,"/");if(l.length===0||l.startsWith("..")||ir(l))return 0;let p=Fl(c.snap,l,{via:c.via,currentBranch:c.via==="cwd"?dw(r):null,nowMs:Date.now()});return p===null||process.stdout.write(_e(p)),0}catch{return 0}}function dw(e){try{let n=Zl("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 uw(e,t){let n=zi(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 Qy(Kt(Ce,`handoff_advisory_${t.session_id}.json`),JSON.stringify(c,null,2))}catch(d){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${d instanceof Error?d.message:String(d)}
|
|
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 Zi(e){try{let t=await M(),n=De(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(id(t,r),await ie(t)),await ad(n,ew)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
|
|
155
|
+
`)}}async function pw(){let e=await M(),t=De(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 ad(t,tw);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
156
|
+
`),n.ok?0:1}async function ad(e,t){let n=await M();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=Pl(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 M();return c.pending_metrics=c.pending_metrics.slice(r.length),await ie(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 fw(){let e=await M(),t=De(e),n=mw(),r=Ar(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:zi(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})),...un(n.findings)?{remedy:Ql}:{}}},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
|
+
`);un(n.findings)&&process.stderr.write(` ${Ql}
|
|
161
|
+
`)}return 0}function mw(){let e=Kt(td(),".claude","settings.json"),t=null;try{or(e)&&(t=ed(e,"utf8"))}catch{}return{settingsPath:e,findings:_t(t)}}async function hw(){let e=await M(),t=De(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??Zy,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
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 ie(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
|
|
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 d of
|
|
167
|
+
`),0)}function cd(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var Zy,ew,tw,rr,ow,Ql,eo=b(()=>{"use strict";Vi();Lt();Le();K();kt();Jn();fe();qi();Ji();Yn();re();ct();tr();Pe();Xi();Xl();Zy=process.env.MAIND_THRESHOLDS_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds",ew=1500,tw=1e4,rr=7*24*60*60*1e3;s(rd,"recordGuardSignals");s(id,"closeTrackedSession");s(nw,"gcState");s(De,"effectiveConfig");s(od,"getOrCreateSession");s(rw,"runOnSessionStart");s(iw,"readSettingsRaw");s(Qi,"writeIdentitySideChannel");ow=6e4;s(sd,"grandparentPid");s(ue,"agentHostPidCandidates");s(sw,"runOnToolUse");s(aw,"denyReason");s(cw,"runOnFileWrite");s(lw,"runOnFileEdit");s(dw,"currentGitBranch");s(uw,"maybeEmitAdvisory");s(Zi,"runSessionEndMetrics");s(pw,"runFlush");s(ad,"flushPending");s(fw,"runHookStatus");Ql="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(mw,"readHookWiring");s(hw,"runSyncConfig");s(cd,"sessionIdOf")});function dd(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var ud=b(()=>{"use strict";s(dd,"resolveConnection")});var pd={};B(pd,{runOnSessionEnd:()=>_w});function yw(e,t){try{let n=F(),r=n!==null&&!$i(process.env,ee()),i=null;if(n!==null){let o=st(rt(n),{hostPids:ue(),cwd:process.cwd()});if(o){let a=Date.parse(o.snap.written_at);i=Number.isFinite(a)?Math.max(0,t-a):null}}return dd({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function ww(){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=F();if(n!==null){let i=st(rt(n),{hostPids:ue(),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 bw(e,t,n,r){let i=fetch(gw,{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 _w(){try{for(let i of ue())hl(it(),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=er(t);if(r)try{let[i,o]=await Promise.all([Gi(r),Wi(r)]);if(n&&(i.session_id=n,o.session_id=n),i.maind_connected=yw(i.maind_connected==="connected",Date.now()),i.session_id){let a=Bi(i,o,{client_session_id:ww(),client:"claude-code"},"live_bridge");await bw(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 Zi(n),0}var gw,fd=b(()=>{"use strict";Vi();Ke();K();qi();Ji();re();eo();Li();Jn();fe();Yn();Se();ud();gw=Zn;s(yw,"connectionVerdict");s(ww,"presenceSessionId");s(bw,"postWithTimeout");s(_w,"runOnSessionEnd")});function z(e=process.env,t=ee()){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 lt(e,t=ce()){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 Oe=b(()=>{"use strict";Ke();se();s(z,"resolveGuardConfig");s(lt,"writeGuardConfig")});function kw(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 md(e,t,n=process.stdout){let r=kw(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 d of dn)o.push(await Pr(i,d));for(let d of o)n.write(` ${d.status.padEnd(12)} ${d.target}${d.detail?` \u2014 ${d.detail}`:""}
|
|
171
171
|
`);let a=o.some(d=>d.detail==="user declined"),c=o.some(d=>d.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 lt({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 d of i>0?c.slice(1):c)if(d.trim())try{let u=JSON.parse(d);typeof u.event=="string"&&u.event in t&&(t[u.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var ft
|
|
183
|
-
`),1):(await
|
|
184
|
-
`),0)}case"off":return await
|
|
180
|
+
`),c?1:0)}var hd=b(()=>{"use strict";kt();Dr();Oe();s(kw,"parseGuardInstallFlags");s(md,"runGuardInstall")});import{existsSync as gd}from"node:fs";import{mkdir as vw,readFile as Sw,readdir as Ew,rename as xw,stat as Rw,unlink as Tw,writeFile as Aw}from"node:fs/promises";import{join as sr}from"node:path";function yd(e){return sr(Gt,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function pe(e){try{let t=yd(e);if(!gd(t))return{};let n=JSON.parse(await Sw(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function V(e,t){await vw(Gt,{recursive:!0,mode:448});let n=yd(e),r=`${n}.tmp`;await Aw(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await xw(r,n)}async function wd(e=7*24*60*60*1e3,t=Date.now()){try{if(!gd(Gt))return;for(let n of await Ew(Gt)){if(!n.endsWith(".json"))continue;let r=sr(Gt,n);try{let i=await Rw(r);t-i.mtimeMs>e&&await Tw(r)}catch{}}}catch{}}var dt,Gt,ut=b(()=>{"use strict";Pe();dt=sr(Ce,"guard"),Gt=sr(dt,"sessions");s(yd,"sessionFile");s(pe,"loadGuardSession");s(V,"saveGuardSession");s(wd,"sweepOldGuardSessions")});import{existsSync as Iw}from"node:fs";import{appendFile as Nw,mkdir as Cw,open as Pw}from"node:fs/promises";import{join as Dw}from"node:path";async function G(e){try{await Cw(dt,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
|
|
181
|
+
`;await Nw(pt,t,{mode:384})}catch{}}async function bd(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(!Iw(pt))return t;let n=await Pw(pt,"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 d of i>0?c.slice(1):c)if(d.trim())try{let u=JSON.parse(d);typeof u.event=="string"&&u.event in t&&(t[u.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var pt,ft=b(()=>{"use strict";ut();pt=Dw(dt,"events.jsonl");s(G,"appendGuardEvent");s(bd,"readGuardEventCounts")});var kd={};B(kd,{runGuard:()=>Lw});import{existsSync as Ow,readFileSync as Mw}from"node:fs";import{homedir as _d}from"node:os";import{join as Fw}from"node:path";async function Lw(e){let t=e[0],n=e.slice(1);switch(t){case"install":return md(n,_d());case"status":return Hw();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 lt({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
184
|
+
`),0)}case"off":return await lt({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
|
|
186
|
+
`),1):(await lt({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
187
|
+
`),0)}case"skip":return jw(n);default:return process.stdout.write($w),t===void 0||t==="--help"||t==="-h"?0:1}}async function jw(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
188
|
`),1;let r=n.trim().slice(0,500),i=await pe(t);return await V(t,{...i,override_reason:r}),await G({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 ${
|
|
190
|
-
`),0}async function
|
|
189
|
+
logged (auditable) in ${pt}
|
|
190
|
+
`),0}async function Hw(){let e=z(),t=Fw(_d(),".claude","settings.json"),n=null;try{Ow(t)&&(n=Mw(t,"utf8"))}catch{}let r=_t(n,{},dn),i=await bd();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:pt},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(
|
|
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 $w,vd=b(()=>{"use strict";kt();Oe();hd();ft();ut();$w=["usage: maind-mcp-bridge guard <verb>",""," install [--mode warn|block] [--stop-gate] [--full] [--dry-run]"," wire the guard hooks (consent per hook, append-only) + set the mode"," status mode, hook wiring, and local event counts"," mode <warn|block>"," flip enforcement hardness (config-only; settings.json untouched)"," off disable the guard (hooks stay wired, become no-ops)"," stop-gate <on|off>"," toggle the strict completion gate (review before finish)",' skip --session <id> --reason "<why>"'," record a logged override for one session (block-gate exit valve)",""].join(`
|
|
195
|
+
`);s(Lw,"runGuard");s(jw,"runGuardSkip");s(Hw,"runGuardStatus")});async function Sd(e){return Bt("get_session_briefing",{tools:["claude-code"]},e)}async function Bt(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??to,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:Uw,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),d=c.headers.get("mcp-session-id");if(await c.text().catch(()=>""),!c.ok||!d)return null;let u={...a,"mcp-session-id":d};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 l=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(!l.ok)return null;let f=(l.headers.get("content-type")??"").startsWith("text/event-stream")?await Kw(l):await l.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 Kw(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
196
|
`).trim();i=[],c.length>0&&(o=c)},"flush");for(;;){let{value:c,done:d}=await t.read();if(d)break;r+=n.decode(c,{stream:!0});let u;for(;(u=r.indexOf(`
|
|
197
|
-
`))!==-1;){let l=r.slice(0,u);r=r.slice(u+1);let p=l.endsWith("\r")?l.slice(0,-1):l;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return a(),o}var
|
|
198
|
-
`),0):(process.stdout.write(
|
|
197
|
+
`))!==-1;){let l=r.slice(0,u);r=r.slice(u+1);let p=l.endsWith("\r")?l.slice(0,-1):l;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return a(),o}var to,Uw,ar=b(()=>{"use strict";to="https://mcp.maind.dev/mcp",Uw="2025-06-18";s(Sd,"fetchSessionBriefing");s(Bt,"fetchToolText");s(Kw,"readSseMessage")});var Ad={};B(Ad,{BRIEFING_CACHE_FILE:()=>xd,formatInjection:()=>Td,resolveBriefingInjection:()=>Rd,runGuardInject:()=>Qw});import{existsSync as Gw}from"node:fs";import{mkdir as Bw,readFile as Ww,rename as Vw,writeFile as qw}from"node:fs/promises";import{dirname as Jw,join as zw}from"node:path";async function Rd(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??xd,o=n.fetcher??Sd,a=await Zw(i);if(a!==null&&r-Date.parse(a.fetched_at)<Yw&&a.project_key===e)return{text:a.text,via:"cache"};let d=await o({apiKey:t,deviceId:tb(),projectKey:e,bridgeVersion:P,timeoutMs:Xw});return d!==null?(await eb(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:d}),{text:d,via:"fetch"}):a!==null?{text:a.text,via:"stale-cache"}:{text:null,via:"none"}}async function Qw(){try{if(z().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 wd();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let u=await pe(n);return await V(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=F(),c=await Rd(a,i),d=await pe(n);return c.text===null?(await V(n,{...d,inject_failed:!0}),await G({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(Td(c.text,c.via)),await V(n,{...d,injected:!0}),await G({event:"inject_ok",session_id:n,cwd:o,project_key:a??void 0,detail:c.via}),0)}catch{return 0}}function Td(e,t){let n=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=e;return Buffer.byteLength(r,"utf8")>Ed&&(r=r.slice(0,Ed)+`
|
|
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 Zw(e){try{if(!Gw(e))return null;let t=JSON.parse(await Ww(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 eb(e,t){try{await Bw(Jw(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await qw(n,JSON.stringify(t,null,2),{mode:384}),await Vw(n,e)}catch{}}function tb(){try{return j()}catch{return null}}var xd,Yw,Xw,Ed,Id=b(()=>{"use strict";K();re();fe();Se();Oe();ft();ut();ar();xd=zw(dt,"briefing-cache.json"),Yw=12*60*60*1e3,Xw=3e3,Ed=10*1024;s(Rd,"resolveBriefingInjection");s(Qw,"runGuardInject");s(Td,"formatInjection");s(Zw,"readCache");s(eb,"writeCache");s(tb,"safeDeviceId")});var Dd={};B(Dd,{decideGate:()=>Pd,runGuardGate:()=>rb});function Pd(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:Nd(n)}:(n.deny_count??0)>=Cd?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. "+Nd(n)}:{kind:"deny",reason:nb(e.sessionId,n)}}function Nd(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 nb(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 ${Cd} denies this gate downgrades itself to warn.`}async function rb(){try{let e=z();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 pe(r),o=(await M()).guard_signals?.[r]?.consulted_at!==void 0,a=Pd({mode:e.mode,session:i,consulted:o,sessionId:r}),c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=F()??void 0;return a.kind==="deny"?(process.stdout.write(at(a.reason)),await V(r,{...i,deny_count:(i.deny_count??0)+1}),await G({event:"deny",session_id:r,cwd:c,project_key:d}),0):a.kind==="warn"?(process.stdout.write(_e(a.context)),await V(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await G({event:"warn",session_id:r,cwd:c,project_key:d}),0):(await V(r,{...i,edits_seen:(i.edits_seen??0)+1}),0)}catch{return 0}}var Cd,Od=b(()=>{"use strict";re();ct();Pe();fe();Oe();ft();ut();Cd=3;s(Pd,"decideGate");s(Nd,"warnText");s(nb,"denyText");s(rb,"runGuardGate")});var Fd={};B(Fd,{decideStopGate:()=>Md,runGuardStop:()=>ob});function Md(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function ob(){try{let e=z();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 pe(n),i=(await M()).guard_signals?.[n]?.reviewed_at!==void 0;return Md({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:ib})),await V(n,{...r,stop_blocked:!0}),await G({event:"stop_block",session_id:n})),0}catch{return 0}}var ib,$d=b(()=>{"use strict";re();Pe();Oe();ft();ut();s(Md,"decideStopGate");ib="[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(ob,"runGuardStop")});import{appendFile as sb,mkdir as ab,readFile as jd,rename as Hd,writeFile as Ud}from"node:fs/promises";import{homedir as Kd}from"node:os";import{join as Gd}from"node:path";function Bd(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 l=i[u.tool]??={calls:0,warns:0,denies:0};if(u.event==="tool_call"?l.calls+=1:u.event==="policy_warn"||u.event==="sha_warn"?l.warns+=1:l.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 d=Object.entries(i).sort((u,l)=>l[1].calls+l[1].warns+l[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(d),event_count:Math.min(e.length,1e5),citations:[...o.entries()].slice(0,32).map(([u,l])=>({convention_id:u,convention_version:l})),...r?{project_key:r}:{}}}function Me(){return Gd(Kd(),".maind","gateway","attest-spool.jsonl")}async function no(e){let t=C();if(t===null)return!1;let n=await Bt("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 Wd(e){try{await ab(Gd(Kd(),".maind","gateway"),{recursive:!0}),await sb(Me(),JSON.stringify(e)+`
|
|
206
|
+
`,{mode:384}),await cb()}catch{}}async function cb(){try{let t=(await jd(Me(),"utf8")).split(`
|
|
207
|
+
`).filter(r=>r.trim());if(t.length<=Ld)return;let n=`${Me()}.${process.pid}.tmp`;await Ud(n,t.slice(-Ld).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 Hd(n,Me())}catch{}}async function Vd(){let e;try{e=(await jd(Me(),"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 no(i)||(n=!0,t.push(r))}try{let r=`${Me()}.${process.pid}.tmp`;await Ud(r,t.length>0?t.join(`
|
|
211
211
|
`)+`
|
|
212
|
-
`:"",{mode:384}),await
|
|
213
|
-
`,384)}async function
|
|
214
|
-
`),2;let n=Q({entryPath:Z(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of
|
|
215
|
-
`);continue}let a=
|
|
216
|
-
`);continue}if(!(t.yes||await
|
|
212
|
+
`:"",{mode:384}),await Hd(r,Me())}catch{}}var Ld,qd=b(()=>{"use strict";K();ar();Se();Ld=256;s(Bd,"aggregateWindow");s(Me,"attestSpoolPath");s(no,"postAttestation");s(Wd,"spoolAttestation");s(cb,"capSpool");s(Vd,"flushAttestSpool")});function Wt(e=process.env,t=ee()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function cr(e=process.env,t=ee()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function Jd(e,t=ce()){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 zd(e,t=ce()){await Jd({gateway_mode:e},t)}async function Yd(e,t=ce()){await Jd({gateway_attest:e},t)}function Xd(e=process.env,t=ee()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var ro=b(()=>{"use strict";Ke();se();s(Wt,"resolveGatewayMode");s(cr,"resolveGatewayAttest");s(Jd,"writeGatewayConfigPatch");s(zd,"writeGatewayMode");s(Yd,"writeGatewayAttest");s(Xd,"resolveShaProofMode")});function Zd(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,d=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||d===null)continue;let u=typeof i.severity=="string"&&lb.has(i.severity)?i.severity:"recommended",l=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:d,severity:u,summary:l})}}return n}function db(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function eu(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let o of n)db(o,e,t)&&(i===null||Qd[o.severity]>Qd[i.severity])&&(i=o);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function tu(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 lb,Qd,io=b(()=>{"use strict";lb=new Set(["required","recommended","info"]);s(Zd,"extractGatewayRules");Qd={required:2,recommended:1,info:0};s(db,"ruleMatches");s(eu,"decideToolCall");s(tu,"policyDenyText")});import{mkdirSync as ub,readFileSync as pb,renameSync as fb,writeFileSync as mb}from"node:fs";import{homedir as hb}from"node:os";import{dirname as gb,join as yb}from"node:path";function nu(){return yb(hb(),".maind","gateway","policy-cache.json")}function lr(e,t,n=new Date().toISOString()){try{let r={version:oo,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=nu();ub(gb(i),{recursive:!0});let o=`${i}.${process.pid}.tmp`;mb(o,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),fb(o,i)}catch{}}function dr(e){try{let t=pb(nu(),"utf8"),n=JSON.parse(t);return n.version!==oo||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:oo,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var oo,so=b(()=>{"use strict";oo=1;s(nu,"policyCachePath");s(lr,"writePolicyCache");s(dr,"readPolicyCache")});function Vt(e=process.env){let t=e.MAIND_MCP_URL??to,n=C();return{mcpUrl:t,keyFp:n?Yt(n):"anon"}}async function ur(e=6e3){let t=C();if(t===null)return null;let n=null;try{n=F()}catch{n=null}let r=await Bt("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 Zd(i)}var ao=b(()=>{"use strict";Le();K();ar();fe();Se();io();s(Vt,"policyIdentity");s(ur,"fetchGatewayRules")});function qt(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 wb(e){if(qt(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 bb(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:qt(e)?{action:"skip",reason:"already-wrapped"}:wb(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function ru(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 iu(e){if(!qt(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 ou(e){return Object.entries(e).map(([t,n])=>{let r=bb(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var su=b(()=>{"use strict";s(qt,"isGatewayWrapped");s(wb,"isMaindProxyEntry");s(bb,"classifyServer");s(ru,"wrapServerEntry");s(iu,"unwrapServerEntry");s(ou,"planRewrites")});var pu={};B(pu,{runGatewayInstall:()=>xb,runGatewayUninstall:()=>Rb});import{existsSync as _b,readFileSync as kb}from"node:fs";import{homedir as vb}from"node:os";import{join as au}from"node:path";import{createInterface as Sb}from"node:readline";function cu(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 lu(){return[{label:"Claude Code (project .mcp.json)",path:au(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:au(vb(),".claude.json")}]}async function du(e){let t=Sb({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 uu(e){let t=Eb(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 Eb(e){try{return _b(e)?kb(e,"utf8"):null}catch{return null}}async function xb(e){let t=cu(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
214
|
+
`),2;let n=Q({entryPath:Z(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of lu()){let o=uu(i.path);if(o===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
|
|
215
|
+
`);continue}let a=ou(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 du(`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]=ru(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 Rb(e){let t=cu(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 lu()){let i=uu(r.path);if(i===null)continue;let o=!1;for(let[a,c]of Object.entries(i.servers)){if(!qt(c)||!(t.yes||await du(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let u=iu(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 fu=b(()=>{"use strict";se();Ue();su();s(cu,"parseFlags");s(lu,"targets");s(du,"confirm");s(uu,"loadConfig");s(Eb,"readFileSafeSync");s(xb,"runGatewayInstall");s(Rb,"runGatewayUninstall")});var mu={};B(mu,{runGatewayAttest:()=>Ab,runGatewayMode:()=>Tb,runGatewayPolicy:()=>Cb});async function Tb(e){let t=e[0];if(t===void 0){let n=Wt(),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 zd(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 Ab(e){let t=e[0];if(t===void 0){let n=cr(),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 Yd(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 Ib(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 Nb(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 Cb(e){let t=e.includes("--refresh"),n=Wt(),r=Vt();if(t){let o=await ur();o===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
246
|
+
`):(lr(r,o),process.stdout.write(`maind: policy refreshed (${o.length} rule(s)).
|
|
247
|
+
`))}let i=dr(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 (${Nb(i)}, ${r.mcpUrl}):
|
|
250
|
+
`),process.stdout.write(Ib(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 hu=b(()=>{"use strict";ro();so();ao();s(Tb,"runGatewayMode");s(Ab,"runGatewayAttest");s(Ib,"renderRules");s(Nb,"cacheAge");s(Cb,"runGatewayPolicy")});var _u={};B(_u,{gatewayEventsFile:()=>wu,parseGatewayArgs:()=>bu,runGateway:()=>Lb});import{spawn as Pb}from"node:child_process";import{appendFile as Db,mkdir as Ob}from"node:fs/promises";import{homedir as gu}from"node:os";import{basename as Mb,join as yu}from"node:path";import{createInterface as Fb}from"node:readline";function wu(){return yu(gu(),".maind","gateway","events.jsonl")}async function $b(e){try{let t=wu();await Ob(yu(gu(),".maind","gateway"),{recursive:!0}),await Db(t,JSON.stringify(e)+`
|
|
252
|
+
`,{mode:384})}catch{}}function bu(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 Lb(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:v,runGatewayUninstall:E}=await Promise.resolve().then(()=>(fu(),pu));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(()=>(hu(),mu));return e[0]==="mode"?E(e.slice(1)):e[0]==="attest"?v(e.slice(1)):R(e.slice(1))}let t=bu(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 G({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(_e(
|
|
270
|
-
`),a.warned[o]=c.current,await
|
|
271
|
-
`);let m=r.params?.name;process.stdout.write(
|
|
272
|
-
`);return}i
|
|
262
|
+
`),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r??Mb(i),c=Wt(),d=Xd(),u=d==="off"?null:Jt(),l=c==="off"?[]:dr(Vt())?.rules??[];c!=="off"&&ur().then(v=>{v!==null&&(l=v,lr(Vt(),v))}).catch(()=>{});let p=[],f=cr()&&C()!==null&&c!=="off",h=null;try{h=F()}catch{h=null}let m=s(v=>{$b(v),f&&p.push(v)},"record"),g=s(async()=>{if(!f)return;let v=Bd(p.splice(0),c,a,h);v!==null&&(await no(v)||await Wd(v))},"attestAndReset");f&&Vd().catch(()=>{});let w=setInterval(()=>{g()},30*6e4);w.unref();let y=Pb(i,o,{stdio:["pipe","pipe","inherit"]});y.stdout.pipe(process.stdout),y.on("error",v=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(v)}
|
|
263
|
+
`),process.exitCode=1});let _=Fb({input:process.stdin,terminal:!1});_.on("line",v=>{let E=So(v);if(E.kind==="request"&&E.method==="tools/call"&&E.toolName){if(n.has(E.toolName)&&E.id!==void 0){process.stdout.write(Fe(E.id,E.toolName)+`
|
|
264
|
+
`),m(fr("deny",a,E.toolName,Date.now()));return}let R=eu(E.toolName,a,l,c);if(R.kind==="deny"&&E.id!==void 0){process.stdout.write(Fe(E.id,E.toolName,tu(E.toolName,R.rule))+`
|
|
265
|
+
`),m(mr("policy_deny",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));return}(R.kind==="warn"||R.kind==="deny")&&m(mr("policy_warn",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));let U=zt(v,u);if(U.length>0){let A=U.find(Y=>Y.verdict==="fabricated");if(A!==void 0&&d==="enforce"&&c==="enforce"&&E.id!==void 0&&A!==void 0&&E.id!==void 0){process.stdout.write(Fe(E.id,E.toolName,$e(A,!0))+`
|
|
266
|
+
`),m(hr("sha_deny",a,E.toolName,Date.now()));return}let T=A??U[0];process.stderr.write(`[maind gateway] ${$e(T,!1)}
|
|
267
|
+
`),m(hr("sha_warn",a,E.toolName,Date.now()))}m(fr("tool_call",a,E.toolName,Date.now()))}y.stdin.write(v+`
|
|
268
|
+
`)}),_.on("close",()=>{y.stdin.end()});let S=await new Promise(v=>{y.on("exit",(E,R)=>{v(E??(R?1:0))})});return clearInterval(w),await g(),S}var ku=b(()=>{"use strict";gr();qd();ro();io();yr();so();ao();K();fe();s(wu,"gatewayEventsFile");s($b,"logEvent");s(bu,"parseGatewayArgs");s(Lb,"runGateway")});var ho={};B(ho,{MAX_ENTRIES:()=>co,TTL_MS:()=>po,crossSessionDir:()=>fo,decideCrossSession:()=>Eu,parseSessionDb:()=>Su,pruneDb:()=>mo,runGuardCrossCheck:()=>qb,runGuardCrossObserve:()=>Vb,staleReason:()=>lo});import{mkdir as jb,readFile as Hb,readdir as Ub,stat as vu,unlink as Kb,writeFile as Gb}from"node:fs/promises";import{homedir as Bb}from"node:os";import{join as uo}from"node:path";function fo(){return uo(Bb(),".maind","cross-session")}function Su(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 mo(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=po);return n.length>co&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-co)),{files:Object.fromEntries(n),warned:e.warned}}function Eu(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function lo(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 xu(e){let t=fo();return await jb(t,{recursive:!0}),uo(t,`${e}.json`)}async function Ru(e,t){try{let n=await Hb(await xu(e),"utf8");return mo(Su(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function Tu(e,t){try{await Gb(await xu(e),JSON.stringify(t),{mode:384})}catch{}}async function Wb(e){try{let t=fo();for(let n of await Ub(t)){if(!n.endsWith(".json"))continue;let r=uo(t,n),i=await vu(r).catch(()=>null);i&&e-i.mtimeMs>po&&await Kb(r).catch(()=>{})}}catch{}}async function Au(e){try{return(await vu(e)).mtimeMs}catch{return}}async function Vb(e,t=Date.now()){try{if(z().mode==="off")return 0;let r=e??await I(),i=typeof r.session_id=="string"?r.session_id:"",o=ne(r);if(!i||!o)return 0;let a=await Au(o);if(a===void 0)return 0;let c=await Ru(i,t);return c.files[o]={m:a,t},delete c.warned[o],await Tu(i,mo(c,t)),await Wb(t),0}catch{return 0}}async function qb(e,t=Date.now()){try{let n=z();if(n.mode==="off")return 0;let r=e??await I(),i=typeof r.session_id=="string"?r.session_id:"",o=ne(r);if(!i||!o)return 0;let a=await Ru(i,t),c=Eu(a.files[o]?.m,await Au(o));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(at(lo(o,c))+`
|
|
269
|
+
`),await G({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(_e(lo(o,c))+`
|
|
270
|
+
`),a.warned[o]=c.current,await Tu(i,a),await G({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o})),0)}catch{return 0}}var po,co,go=b(()=>{"use strict";re();ct();Oe();ft();po=48*3600*1e3,co=500;s(fo,"crossSessionDir");s(Su,"parseSessionDb");s(mo,"pruneDb");s(Eu,"decideCrossSession");s(lo,"staleReason");s(xu,"dbPath");s(Ru,"loadDb");s(Tu,"saveDb");s(Wb,"sweepStaleSessionFiles");s(Au,"fileMtime");s(Vb,"runGuardCrossObserve");s(qb,"runGuardCrossCheck")});var wo={};B(wo,{INDEX_REFRESH_WORKER:()=>Cu,acquireLock:()=>Du,releaseLock:()=>yo,runIndexRefreshWorker:()=>t_,runOnIndexRefresh:()=>e_});import{spawn as Jb}from"node:child_process";import{existsSync as zb,mkdirSync as Yb,rmdirSync as Iu,statSync as Xb}from"node:fs";import{join as Nu}from"node:path";function Pu(e){return Nu(e,".maind","index-refresh.lock")}function Zb(e){return Nu(e,".maind","code-index.sqlite")}function Du(e,t=Date.now()){let n=Pu(e);try{if(t-Xb(n).mtimeMs<Qb)return!1;Iu(n)}catch{}try{return Yb(n,{recursive:!1}),!0}catch{return!1}}function yo(e){try{Iu(Pu(e))}catch{}}async function e_(){try{let e=await I(),t=W(typeof e.cwd=="string"?e.cwd:process.cwd());if(!zb(Zb(t))||!Du(t))return 0;let n=process.argv[1];if(n===void 0)return yo(t),0;Jb(process.execPath,[n,Cu,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function t_(){let e=process.argv[3]??W();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(ki(),oc)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{yo(e)}return 0}var Qb,Cu,bo=b(()=>{"use strict";re();Ot();Qb=30*6e4,Cu="index-refresh-run";s(Pu,"lockPath");s(Zb,"indexDbPath");s(Du,"acquireLock");s(yo,"releaseLock");s(e_,"runOnIndexRefresh");s(t_,"runIndexRefreshWorker")});import{randomUUID as n_}from"node:crypto";import{createInterface as Zu}from"node:readline";var Ou=[["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 Mu(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of Ou)if(t.includes(n))return r;return null}s(Mu,"mapClientInfoNameToFamily");function vo(e){let t;try{t=JSON.parse(e)}catch{return null}if(!pr(t)||t.method!=="initialize")return null;let n=t.params;if(!pr(n))return null;let r=n.clientInfo;if(!pr(r))return null;let i=r.name,o=Mu(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(vo,"tryExtractInitializeClient");function pr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(pr,"isRecord");gr();yr();Le();var ep="https://mcp.maind.dev/mcp",mt=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},tn=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=Yt(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=tp(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=np(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=Jt(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??ep}async run(){let t=Zu({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 l=vo(t);l!==null&&(this.clientFamily=l.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=l.version))}this.initFrame===null&&Zt(t)&&(this.initFrame=t);let r=op(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let l=zt(t,this.shaRepoRoot);if(l.length>0){let p=l.find(h=>h.verdict==="fabricated"),f=p??l[0];if(p!==void 0&&Ro(p)&&r.id!==null){let h=$e(p,!0);process.stderr.write(`[maind] ${h}
|
|
271
|
+
`);let m=r.params?.name;process.stdout.write(Fe(r.id,typeof m=="string"?m:"unknown",h)+`
|
|
272
|
+
`);return}i=$e(f,!1),process.stderr.write(`[maind] ${i}
|
|
273
273
|
`)}}if(this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let l=await this.localRouter.handleToolCall(r?.id??null,r?.params);process.stdout.write(l+`
|
|
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(l){let p=
|
|
275
|
-
`);return}if(
|
|
276
|
-
`);return}if(i!==null){let l=u.startsWith("text/event-stream")?await
|
|
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 ${
|
|
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(l){let p=Qt(t);if(this.serveInitializeFromCache(t,p))return;en(p,-32603,`bridge network error: ${ap(l)}`);return}let d=c.headers.get("mcp-session-id");if(d&&d!==this.sessionId&&(this.sessionId=d),c.status===401){await this.handle401(c,t);return}if(c.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!Zt(t)){let l=await c.text().catch(()=>"");if(sp(l)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=Qt(t);en(p,-32603,`bridge upstream error (HTTP 404): ${l.slice(0,500)}`);return}if(!c.ok){let l=Qt(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,l))return;en(l,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let u=c.headers.get("content-type")??"";if(o&&this.localRouter){let l=u.startsWith("text/event-stream")?await br(c):await c.text(),p=this.localRouter.augmentToolsList(l);p.trim().length>0&&process.stdout.write(p+`
|
|
275
|
+
`);return}if(Zt(t)){let l=u.startsWith("text/event-stream")?await br(c):await c.text();this.cacheInitializeResult(l),this.presence?.onSessionReady(),l.trim().length>0&&process.stdout.write(l+`
|
|
276
|
+
`);return}if(i!==null){let l=u.startsWith("text/event-stream")?await br(c):await c.text(),p=ip(l,i);p.trim().length>0&&process.stdout.write(p+`
|
|
277
|
+
`);return}if(u.startsWith("text/event-stream"))await rp(c);else{if(c.status===202)return;{let l=await c.text();l.trim().length>0&&process.stdout.write(l+`
|
|
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 mt(cp(i));let a=Qt(n);en(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 lp(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=oe()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&No(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Zt(t))return!1;let r=Co(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(Po(n,r)+`
|
|
279
|
+
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${Xt(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function tp(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(tp,"normalizeClientFamily");function np(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(np,"normalizeClientVersion");async function rp(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
281
|
`)},"flushEvent");try{for(;;){let{value:a,done:c}=await t.read();if(c)break;r+=n.decode(a,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
282
|
-
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let l=u.endsWith("\r")?u.slice(0,-1):u;if(l===""){o();continue}l.startsWith(":")||l.startsWith("data:")&&i.push(l.slice(5).replace(/^\s/,""))}}}finally{o()}}s(
|
|
282
|
+
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let l=u.endsWith("\r")?u.slice(0,-1):u;if(l===""){o();continue}l.startsWith(":")||l.startsWith("data:")&&i.push(l.slice(5).replace(/^\s/,""))}}}finally{o()}}s(rp,"pipeSseToStdout");function ip(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(ip,"appendNoteToToolResult");function op(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(op,"parseRpc");async function br(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=[],a=s(()=>{if(o.length===0)return;let c=o.join(`
|
|
283
283
|
`).trim();o=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:d}=await t.read();if(d)break;r+=n.decode(c,{stream:!0});let u;for(;(u=r.indexOf(`
|
|
284
284
|
`))!==-1;){let l=r.slice(0,u);r=r.slice(u+1);let p=l.endsWith("\r")?l.slice(0,-1):l;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&o.push(p.slice(5).replace(/^\s/,""))}}}finally{a()}return i.join(`
|
|
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(
|
|
285
|
+
`)}s(br,"collectSseText");function Qt(e){try{return JSON.parse(e).id??null}catch{return null}}s(Qt,"tryExtractId");function Zt(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(Zt,"isInitializeRequest");function sp(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(sp,"isSessionLossBody");function ap(e){return e instanceof Error?e.message:String(e)}s(ap,"stringifyErr");function en(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
286
|
+
`)}s(en,"emitJsonRpcError");function cp(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(cp,"extractHint");function lp(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(lp,"parsePresenceToolResult");K();K();import{spawn as bp}from"node:child_process";import{platform as _p}from"node:os";var kp="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function vp(){let e=process.env.MAIND_FUNCTIONS_ORIGIN;return e&&e.length>0?e.replace(/\/+$/,""):kp}s(vp,"functionsOrigin");async function je(e,t=process.stderr){let n=vp(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,o=rn(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 d=await c.json();await Rp(d.verification_uri_complete).catch(()=>{}),xp(d,t);let u=Date.now()+d.expires_in*1e3,l=Math.max(d.interval,3)*1e3;for(;Date.now()<u;){await Ep(l);let p=await Sp(i,d.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
|
|
288
288
|
`),null));if(p){if(p.status==="approved")return ve(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(je,"runDeviceFlow");async function Sp(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(Sp,"pollOnce");function Ep(e){return new Promise(t=>setTimeout(t,e))}s(Ep,"sleep");function xp(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: ${$o(e.verification_uri,56)} \u2502`,` \u2502 Code: ${$o(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(
|
|
294
|
+
`)}s(xp,"printAuthInstructions");function $o(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}s($o,"pad");async function Rp(e){let t,n;switch(_p()){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=bp(t,n,{stdio:"ignore",detached:!0});o.on("error",i),o.unref(),r()}catch(o){i(o)}})}s(Rp,"openExternalBrowser");Se();fe();Se();import*as wc from"node:os";function Lo(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 X("--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 X("--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 X("--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 X("--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 X("--client requires a family argument (e.g. claude-code, cursor, windsurf, copilot, codex, claude-desktop)");t.client=i,n++;break}default:throw new X(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}s(Lo,"parseInstallFlags");var X=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function jo(){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(jo,"printInstallHelp");var on=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
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,l)=>u+" ".repeat(Math.max(0,l-u.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(o)} |`,d=[];d.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],i)} | ${a(t[3],o)} |`),d.push(c);for(let u of this.results)d.push(`| ${a(u.target,n)} | ${a(u.action,r)} | ${a(u.status,i)} | ${a(u.detail??"",o)} |`);return d.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 Ho from"node:fs/promises";import*as me from"node:path";import*as Uo from"node:readline";var Dp=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function Ko(e){let t=me.resolve(e),n=t;for(;;){if(await Bo(n))return n;let r=me.dirname(n);if(r===n)return t;n=r}}s(Ko,"detectProjectRoot");async function Go(e){let n=me.resolve(e),r=[];for(;;){await Bo(n)&&r.push(n);let i=me.dirname(n);if(i===n)break;n=i}return r}s(Go,"findAllProjectRoots");async function Bo(e){for(let t of Dp)try{return await Ho.access(me.join(e,t)),!0}catch{}return!1}s(Bo,"hasAnyMarker");async function Wo(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(l){return
|
|
305
|
+
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=Uo.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(Wo,"disambiguateProjectRoot");Ue();import*as q from"node:path";function zo(e){let t=e.launch??Q({entryPath:Z(),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(zo,"buildMaindServerEntry");function $p(e){switch(e.platform){case"darwin":return q.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??q.join(e.homeDir,"AppData","Roaming");return q.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??q.join(e.homeDir,".config");return q.join(t,"Claude","claude_desktop_config.json")}}}s($p,"claudeDesktopConfigPath");function Yo(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:q.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:q.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:$p(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:q.join(e.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:q.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:q.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}s(Yo,"getClientTargets");function Xo(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}s(Xo,"filterTargetsByFamily");function Qo(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Jo(e.env.XDG_CONFIG_HOME),appData:Jo(e.env.APPDATA)}}s(Qo,"makeDefaultContext");function Jo(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}s(Jo,"nonEmpty");Ue();se();var yt="maind";async function rs(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(l){return Er(e,"read",l)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{i=JSON.parse(r)}catch(l){return Er(e,"parse",l)}}if(!he(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"&&Hp(i),c,d=!1;if(a){let l=i[yt];he(l)&&ns(l,t)&&(d=!0),c={...i,[yt]:ts(l,t)}}else{let l=he(i.mcpServers)?i.mcpServers:{},p=l[yt];he(p)&&ns(p,t)&&(d=!0),c={...i,mcpServers:{...l,[yt]:ts(p,t)}}}if(d&&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(l){return Er(e,"write",l)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(rs,"mergeJsonConfig");function ts(e,t){let n=he(e)&&he(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(ts,"mergeEntry");function Hp(e){return!("mcpServers"in e||!(yt in e))}s(Hp,"hasRootShape");function ns(e,t){if(!he(e)||e.command!==t.command||!Up(e.args,t.args)||!he(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(ns,"serverEntriesEqual");function Up(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(Up,"arrayEquals");function he(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(he,"isObject");function Er(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(Er,"failed");se();import{parse as Kp,stringify as Gp}from"smol-toml";async function is(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 ln(e,"read",m)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{let m=Kp(r);if(!Ee(m))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=m}catch(m){return ln(e,"parse",m)}}let a=Ee(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(Ee(c)&&Bp(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let d=Ee(c)&&Ee(c.env)?c.env:{},u={...t.env};for(let[m,g]of Object.entries(d))!(m in u)&&typeof g=="string"&&(u[m]=g);let l={command:t.command,args:[...t.args],env:u},p={...i,mcp_servers:{...a,maind:l}},f;try{f=Gp(p),f.endsWith(`
|
|
308
308
|
`)||(f+=`
|
|
309
|
-
`)}catch(m){return
|
|
309
|
+
`)}catch(m){return ln(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 ln(e,"write",m)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(is,"mergeTomlConfig");function Bp(e,t){if(!Ee(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(!Ee(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(Bp,"tomlServerEntryEqual");function Ee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ee,"isObject");function ln(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(ln,"failed");import*as ae from"node:path";var Wp="__STACK__";var Vp="__INTENT__";var xr="https://mcp.maind.dev/mcp",qp=`?stack=${Wp}&intent=${Vp}`;function Jp(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(Jp,"buildStackAwareEndpoint");var gk=Jp(xr,{stack:["nextjs","supabase"],intent:"mixed"}),bt=`## 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 zp(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
|
+
${bt}`}s(zp,"buildAiPromptBody");function wt(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(wt,"buildJsonConfigInstaller");function Yp(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(Yp,"buildCodexTomlInstaller");function Xp(e=xr){let t=`${e}${qp}`;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:zp(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:wt(".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:wt("$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:Yp(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:wt(".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
|
+
${bt}
|
|
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:wt("$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:wt("$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(Xp,"buildSnippetTemplates");var yk=Xp(xr);se();var Qp="## maind MCP integration";function Zp(e){return[{key:"preamble:CLAUDE.md",path:ae.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:ae.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:ae.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:ae.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:ae.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:ae.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}s(Zp,"buildPreambleTargets");async function os(e,t=!1){let n=Zp(e),r=[];for(let i of n)r.push(await ef(i,t));return r}s(os,"writePreambleFiles");async function ef(e,t){try{if(e.mayNeedParentDir&&!t&&await Sr(ae.dirname(e.path)),await Zo(e.path,Qp))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?`${bt}
|
|
800
|
+
`:tf(r)+`${bt}
|
|
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(ef,"writeOnePreambleFile");function tf(e){return e.endsWith(`
|
|
802
802
|
|
|
803
803
|
`)?e:e.endsWith(`
|
|
804
804
|
`)?e+`
|
|
805
805
|
`:e+`
|
|
806
806
|
|
|
807
|
-
`}s(
|
|
807
|
+
`}s(tf,"ensureTrailingBlankLine");Dr();Ke();se();import*as ps from"node:readline";var xe="config:auto_working_paths",mf=`
|
|
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:
|
|
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 fs(e){let t=e.configPath??ce(),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:xe,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:xe,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??hf)(e.out,mf)}else return{target:xe,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:xe,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:xe,action:"merge",status:"would-merge",detail:t};try{await O(t,o,384)}catch(a){return{target:xe,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:xe,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}s(fs,"applyWorkingPathsConsent");async function hf(e,t){e.write(t);let n=ps.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(hf,"promptYesNoDefaultNo");K();async function ms(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(ms,"exchangeOneClickToken");async function ys(e){let t="browser-pair";if(e.token!==null)try{let o=gf(e.token);return e.dryRun?{apiKey:o,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(gt(),ve(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:hs(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=rn(e.bridgeVersion),a=await ms({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:o.device_id,label:Fo(),clientMeta:{...o}});if(a.ok)return gt(),ve(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,gs(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 je(e.bridgeVersion,gs(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:hs(o)}}}}s(ys,"pairOrUseToken");function gf(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(gf,"validateTokenShape");function hs(e){return e instanceof Error?e.message:String(e)}s(hs,"errMessage");function gs(e){return e.out??process.stdout}s(gs,"out");var yf="https://vsddmiosisvfrairepxv.supabase.co/functions/v1",wf="/install-completed";async function ws(e){if(!e.enabled||e.apiKey===null)return;let n=`${(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"")||yf}${wf}`,r={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:_f(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:bf(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(ws,"postInstallTelemetry");function bf(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(bf,"countStatuses");function _f(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}s(_f,"parseNodeMajor");Ot();var uh="https://mcp.maind.dev/mcp";async function bc(e){let t=Date.now(),n;try{n=Lo(e)}catch(_){if(_ instanceof X)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 jo(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,o=wc.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 Go(process.cwd());if(_.length===0)a=await Ko(process.cwd());else if(_.length===1)a=_[0];else{let S=await Wo(_,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 on,d=(process.env.MAIND_MCP_URL??"").trim()||uh;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
824
|
`),process.stdout.write(` \u2014 mcp endpoint: ${d}
|
|
825
825
|
|
|
826
|
-
`);let u=await
|
|
826
|
+
`);let u=await ys({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 l=
|
|
829
|
+
`),c.print(process.stdout),2;let l=Qo({projectRoot:a,homeDir:o,platform:process.platform,env:process.env}),p=Yo(l);if(p=Xo(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=zo({mcpUrl:d,clientFamily:_.clientFamilyEnv}),v;_.kind==="json"?v=await rs(_,S,n.dryRun):v=await is(_,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 ds(f));for(let _ of await us(f))c.add(_);c.add(await fs({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let h=pc();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 ws({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 w=Q({entryPath:Z(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),y=w.fallbackReason===null?`${
|
|
835
|
+
`);let w=Q({entryPath:Z(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),y=w.fallbackReason===null?`${He(w)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${y}
|
|
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(bc,"runInstall");Ot();import{readFileSync as ph}from"node:fs";import{join as _c}from"node:path";function Gn(e){return e?Math.ceil(e.length/4):0}s(Gn,"estimateTokens");var kc=1e6,Bn=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 vc(e){try{let t=ph(e,"utf8");return t.length>kc?t.slice(0,kc):t}catch{return""}}s(vc,"readFileCapped");function fh(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(fh,"distinctFilePaths");function Sc(e,t,n,r){try{let i=Gn(n);if(e==="codebase_search"){let o=fh(t);if(o.length===0)return 0;let a=0;for(let c of o)a+=Gn(vc(_c(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=Gn(vc(_c(r,o)));return Math.max(0,a-i)}return 0}catch{return 0}}s(Sc,"measureLocalToolSaved");Lt();Ot();import{createHash as Lh}from"node:crypto";function Wn(e){return Lh("sha256").update(e,"utf8").digest("hex")}s(Wn,"nodeKeyHash");var jh=["module","class","interface","function","method","type_alias","enum","variable"],Mi=[{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:jh,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."}}}}],Jc=new Set(Mi.map(e=>e.name));function L(e){return typeof e=="string"&&e.length>0?e:void 0}s(L,"str");var Hh=10;function Uh(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>=Hh&&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(Uh,"aggregateHistoryContext");function Ie(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Ie,"num");function Vc(e){if(e===void 0)return{repoRoot:W(),scanDirs:void 0};let t=Kn(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(Vc,"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 zc(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=hc(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 Te(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=Kn(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 Tt(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"),_=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.`)+_}}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=Kn(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=Mt(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=Vc(L(n.dir));if(r===null)return qc("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=$t(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=Vc(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=Oi(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:Ie(n.limit)})).map(o=>({...o,nodeKeyHash:Wn(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:Ie(n.max_depth),limit:Ie(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:Wn(r)}}case"codebase_map":return e.getArchitecture({topN:Ie(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:L(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Ie(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:Wn(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:Ie(n.limit)}),i;if(n.include_history!==!1)try{i=Uh(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:Wn(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:Wc},...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:Ie(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(zc,"dispatchLocalTool");var Vn=class{constructor(t=yc,n=null,r=W){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Mi}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Jc.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 zc(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=fc(a)?`${mc} (${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=Sc(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};var Kh="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function Yc(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:Kh}s(Yc,"functionsOrigin");var Gh="/mcp-client-metrics-ingest",Bh=4e3,Wh="codebase_search_tokens_saved";async function Xc(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Yc()}${Gh}`,n=new AbortController,r=setTimeout(()=>n.abort(),Bh);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:Wh,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(Xc,"postSavingsMetric");Li();Jn();Yn();import{execFile as Cg}from"node:child_process";var Pg=8,Dg=32;function Og(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,Dg)}s(Og,"parsePorcelain");function Mg(e,t=Pg){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(Mg,"condenseToDirs");async function yl(e=Fg){let t=await e();if(t===null)return null;let n=Mg(Og(t));return n.length>0?n:null}s(yl,"deriveWorkingPaths");async function Fg(){return await new Promise(e=>{Cg("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(Fg,"defaultGitStatus");var r_=1,i_=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function o_(e){return i_.includes(e)}s(o_,"isHookSubcommand");var s_=6e4;async function a_(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==C()&&ve(e),e;let t=C();if(t!==null)return t;let n=await je(P);return n===null&&(process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
|
|
840
|
+
`),process.exit(1)),n.apiKey}s(a_,"ensureApiKey");async function c_(){let e=await je(P);return e===null&&(process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
|
|
841
|
+
`),process.exit(1)),e.apiKey}s(c_,"reauth");async function l_(){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),w=await bc(g);process.exit(w)}if(e==="on-session-end"){let{runOnSessionEnd:m}=await Promise.resolve().then(()=>(fd(),pd));process.exit(await m())}if(e==="guard"){let m=process.argv.indexOf("guard"),{runGuard:g}=await Promise.resolve().then(()=>(vd(),kd));process.exit(await g(process.argv.slice(m+1)))}if(e==="guard-inject"){let{runGuardInject:m}=await Promise.resolve().then(()=>(Id(),Ad));process.exit(await m())}if(e==="guard-gate"){let{runGuardGate:m}=await Promise.resolve().then(()=>(Od(),Dd));process.exit(await m())}if(e==="guard-stop"){let{runGuardStop:m}=await Promise.resolve().then(()=>($d(),Fd));process.exit(await m())}if(e==="gateway"){let m=process.argv.indexOf("gateway"),{runGateway:g}=await Promise.resolve().then(()=>(ku(),_u));process.exit(await g(process.argv.slice(m+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:m}=await Promise.resolve().then(()=>(go(),ho));process.exit(await m())}if(e==="guard-cross-check"){let{runGuardCrossCheck:m}=await Promise.resolve().then(()=>(go(),ho));process.exit(await m())}if(e==="on-index-refresh"){let{runOnIndexRefresh:m}=await Promise.resolve().then(()=>(bo(),wo));process.exit(await m())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:m}=await Promise.resolve().then(()=>(bo(),wo));process.exit(await m())}if(e!==void 0&&o_(e)){let m=await Promise.resolve().then(()=>(eo(),ld)),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"))&&(d_(),process.exit(0)),process.argv.includes("--reauth")&&(gt(),await je(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 a_(),r=F(),o=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Bn:null,a=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new Vn(void 0,o),c=`bridge-${n_()}`,d=s(async()=>{if(!o)return;let m=o.takePending();m.tokens<=0||await Xc({apiKey:n,deviceId:t,sessionId:c,tokensSaved:m.tokens,bridgeVersion:P})},"flushSavings"),u=o?setInterval(()=>{d()},s_):null;u?.unref();let l=null,p=new qn({projectKey:r,identity:new zn({projectKey:r}),postToolCall:s((m,g)=>l===null?Promise.reject(new Error("presence: no active forwarder")):l.postPresenceToolCall(m,g),"postToolCall"),deriveWorkingPaths:s(()=>yl(),"deriveWorkingPaths"),snapshot:r!==null?ll({projectKey:r}):void 0}),f=p.isEnabled?setInterval(()=>{p.pollActivity()},el):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 tn({apiKey:n,deviceId:t,bridgeVersion:P,projectKey:r,localRouter:a,presence:p});l=m;try{await m.run();return}catch(g){if(g instanceof mt&&h<r_){h+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${g.message}; re-authorizing\u2026
|
|
844
|
+
`),n=await c_();continue}throw g}}}finally{u&&clearInterval(u),f&&clearInterval(f),await p.end(),await d()}}s(l_,"main");function d_(){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(d_,"printHelp");l_().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
|
|
846
846
|
`),process.exit(1)});
|