@maind-dev/mcp-bridge 0.43.0 → 0.45.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 +135 -135
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Li=Object.defineProperty;var a=(e,t)=>Li(e,"name",{value:t,configurable:!0});var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var J=(e,t)=>{for(var n in t)Li(e,n,{get:t[n],enumerable:!0})};import{execFileSync as Kd}from"node:child_process";import{createHash as Gd}from"node:crypto";import{mkdirSync as Bd,readFileSync as Wd,renameSync as Vd,writeFileSync as qd}from"node:fs";import{dirname as Jd,join as ji}from"node:path";function tt(e=process.cwd()){try{let t=Kd("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 Mt(e){return Gd("sha256").update(e).digest("hex").slice(0,16)}function Dt(e){return ji(e,zd)}function Hi(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Ui(e,t,n,r=new Date().toISOString()){try{if(!Hi(n))return;let i={version:Vn,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},o=Dt(e);Bd(Jd(o),{recursive:!0});let s=`${o}.${process.pid}.tmp`;qd(s,JSON.stringify(i,null,2),"utf8"),Vd(s,o)}catch{}}function Ki(e,t){try{let n=Wd(Dt(e),"utf8"),r=JSON.parse(n);return r.version!==Vn||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!Hi(r.result)?null:{version:Vn,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function Gi(e,t,n=new Date){let r=Yd(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{Vi(t,384)}catch{}return n}function
|
|
6
|
-
`,{encoding:"utf8",mode:384});try{Vi(n,384)}catch{}}function I(){let e=zn();if(!Ht(e))return null;let t=Wi(e,"utf8").trim();return t.length>0?t:null}function Ie(){let e=zn();Ht(e)&&Jn(e,"",{encoding:"utf8",mode:384})}function Ji(){try{return`mcp-bridge-${au()}`}catch{return"mcp-bridge"}}function Ut(e){return{os:`${qn()} ${cu()}`,ide:"mcp-bridge",ext_version:e,device_id:F()}}var du,uu,pu,U=w(()=>{"use strict";a(rt,"configDir");a(qi,"ensureDir");du="device-id",uu="api-key";a(F,"ensureDeviceId");pu=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;a(fu,"isUuid");a(zn,"apiKeyPath");a(ge,"writeApiKey");a(I,"readApiKey");a(Ie,"clearApiKey");a(Ji,"bridgeLabel");a(Ut,"clientMeta")});var N,ye=w(()=>{"use strict";N="0.43.0"});import{execFileSync as vu}from"node:child_process";import{createHash as Su}from"node:crypto";function Eu(e){return Su("sha256").update(e).digest("hex")}function xu(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 Ru(e){let t=xu(e);return t?Eu(t):null}function O(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&Tu.test(e))return e;let t;try{t=vu("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Ru(t):null}var Tu,le=w(()=>{"use strict";a(Eu,"sha256Hex");a(xu,"normalizeRemoteUrl");a(Ru,"projectKeyFromRemote");Tu=/^[a-f0-9]{64}$/;a(O,"computeProjectKey")});import Iu from"node:path";import{fileURLToPath as Nu}from"node:url";function Cu(e,t=Iu.sep){return e.split(t).includes("_npx")}function Y(e){let t=e.extraArgs??[],n=a(r=>({command:"npx",args:["-y",oo,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):Cu(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 X(){try{let e=Nu(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Ce(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${io(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:io(n)).join(" ")}function Gt(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(oo)}function Bt(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function io(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var oo,Pe=w(()=>{"use strict";oo="@maind-dev/mcp-bridge";a(Cu,"isEphemeralEntry");a(Y,"resolveBridgeLaunch");a(X,"currentBridgeEntry");a(Ce,"launchToShellCommand");a(Gt,"isNpxForm");a(Bt,"isLegacyHookForm");a(io,"shellQuote")});import*as P from"node:fs/promises";import*as Wt from"node:path";async function $(e){try{return await P.readFile(e,"utf8")}catch(t){if(Du(t))return null;throw t}}async function Yn(e){await P.mkdir(e,{recursive:!0})}async function D(e,t,n){let r=Wt.dirname(e);await Yn(r);let i=Wt.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await P.writeFile(i,t,{encoding:"utf8",mode:n});try{await P.rename(i,e)}catch(o){if(Ou(o))try{await P.copyFile(i,e),await P.unlink(i).catch(()=>{}),n!==void 0&&await P.chmod(e,n).catch(()=>{});return}catch(s){throw await P.unlink(i).catch(()=>{}),s}throw await P.unlink(i).catch(()=>{}),o}}async function po(e,t){let n=await $(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function Du(e){return fo(e)&&e.code==="ENOENT"}function Ou(e){return!fo(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function fo(e){return typeof e=="object"&&e!==null&&"code"in e}var ee=w(()=>{"use strict";a($,"readFileSafe");a(Yn,"ensureDir");a(D,"atomicWriteFile");a(po,"hasLinePrefix");a(Du,"isNoEnt");a(Ou,"isWindowsRenameFailure");a(fo,"isNodeError")});import{existsSync as Xu}from"node:fs";import*as wo from"node:path";function at(e,t={},n=er){let r=t.fileExists??Xu,i=t.expectedCommand??Qu,o={};if(e!==null&&e.trim().length>0)try{let s=JSON.parse(e);Zn(s)&&(o=s)}catch{}return n.map(s=>{let c={event:s.event,subcommand:s.subcommand},l=Zu(o,s.event,s.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${s.label} is not wired \u2014 this bridge can run '${s.subcommand}', but nothing calls it.`};let d=` Replace its command with: ${i(s.subcommand)}`;if(Bt(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${s.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+d};if(Gt(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${s.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+d};let u=ep(l);return u!==null&&!r(u)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${s.label} points at ${u}, which does not exist \u2014 the hook fails silently on every run.`+d}:{...c,status:"ok",command:l,remedy:"none",detail:`${s.label} is wired.`}})}function tr(e){return e.some(t=>t.status!=="ok")}function Jt(e){return e.some(t=>t.remedy==="run-install")}function Qu(e){return Ce(Y({entryPath:X(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function Zu(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Zn(i))continue;let o=i.hooks;if(Array.isArray(o))for(let s of o){if(!Zn(s))continue;let c=s.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function ep(e){for(let t of tp(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return wo.isAbsolute(t)?t:null;return null}function tp(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 Zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var er,qt,ct=w(()=>{"use strict";Pe();er=[{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:"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."}],qt=[{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."}];a(at,"inspectHookWiring");a(tr,"hasWiringDrift");a(Jt,"needsInstallRun");a(Qu,"defaultExpectedCommand");a(Zu,"findCommand");a(ep,"extractScriptPath");a(tp,"tokenize");a(Zn,"isObject")});import*as ir from"node:path";import*as ko from"node:readline";async function vo(e,t){let n=ir.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 $(n)}catch(m){return{target:r,action:"merge",status:"failed",detail:`read: ${nr(m)}`}}let o,s="create";if(i===null||i.trim().length===0)o={};else{s="merge";try{let m=JSON.parse(i);if(!rr(m))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};o=m}catch(m){return{target:r,action:"merge",status:"failed",detail:`parse: ${nr(m)}`}}}let c=rp(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:s==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await ip(e.out,`
|
|
4
|
+
${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:o})}function Yd(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${Xd(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function Xd(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 s=Math.floor(o/24);return`${s} day${s===1?"":"s"} ago`}var Vn,zd,Ot=w(()=>{"use strict";Vn=1,zd=ji(".maind","conventions-cache.json");a(tt,"resolveRepoRoot");a(Mt,"keyFingerprint");a(Dt,"cachePath");a(Hi,"hasInstructions");a(Ui,"writeConventionsCache");a(Ki,"readConventionsCache");a(Gi,"buildCachedInitializeResponse");a(Yd,"fallbackMarker");a(Xd,"relativeAge")});import{existsSync as Ht,mkdirSync as cu,readFileSync as Wi,writeFileSync as Jn,chmodSync as Vi}from"node:fs";import{homedir as lu,hostname as du,platform as qn,release as uu}from"node:os";import{randomUUID as pu}from"node:crypto";import{join as he}from"node:path";function rt(){let e=lu(),t=process.env;if(qn()==="darwin")return he(e,"Library","Application Support","maind");if(qn()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:he(e,"AppData","Roaming");return he(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:he(e,".config");return he(n,"maind")}function qi(e){Ht(e)||cu(e,{recursive:!0,mode:448})}function F(){let e=rt();qi(e);let t=he(e,fu);if(Ht(t)){let r=Wi(t,"utf8").trim();if(gu(r))return r}let n=pu();Jn(t,n+`
|
|
5
|
+
`,{encoding:"utf8",mode:384});try{Vi(t,384)}catch{}return n}function gu(e){return hu.test(e)}function zn(){return he(rt(),mu)}function ge(e){let t=rt();qi(t);let n=zn();Jn(n,e+`
|
|
6
|
+
`,{encoding:"utf8",mode:384});try{Vi(n,384)}catch{}}function I(){let e=zn();if(!Ht(e))return null;let t=Wi(e,"utf8").trim();return t.length>0?t:null}function Ie(){let e=zn();Ht(e)&&Jn(e,"",{encoding:"utf8",mode:384})}function Ji(){try{return`mcp-bridge-${du()}`}catch{return"mcp-bridge"}}function Ut(e){return{os:`${qn()} ${uu()}`,ide:"mcp-bridge",ext_version:e,device_id:F()}}var fu,mu,hu,U=w(()=>{"use strict";a(rt,"configDir");a(qi,"ensureDir");fu="device-id",mu="api-key";a(F,"ensureDeviceId");hu=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;a(gu,"isUuid");a(zn,"apiKeyPath");a(ge,"writeApiKey");a(I,"readApiKey");a(Ie,"clearApiKey");a(Ji,"bridgeLabel");a(Ut,"clientMeta")});var N,ye=w(()=>{"use strict";N="0.45.0"});import{execFileSync as xu}from"node:child_process";import{createHash as Ru}from"node:crypto";function Au(e){return Ru("sha256").update(e).digest("hex")}function Tu(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 Iu(e){let t=Tu(e);return t?Au(t):null}function D(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&Nu.test(e))return e;let t;try{t=xu("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Iu(t):null}var Nu,le=w(()=>{"use strict";a(Au,"sha256Hex");a(Tu,"normalizeRemoteUrl");a(Iu,"projectKeyFromRemote");Nu=/^[a-f0-9]{64}$/;a(D,"computeProjectKey")});import Pu from"node:path";import{fileURLToPath as Mu}from"node:url";function Du(e,t=Pu.sep){return e.split(t).includes("_npx")}function Y(e){let t=e.extraArgs??[],n=a(r=>({command:"npx",args:["-y",oo,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):Du(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 X(){try{let e=Mu(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Ce(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${io(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:io(n)).join(" ")}function Gt(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(oo)}function Bt(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function io(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var oo,Pe=w(()=>{"use strict";oo="@maind-dev/mcp-bridge";a(Du,"isEphemeralEntry");a(Y,"resolveBridgeLaunch");a(X,"currentBridgeEntry");a(Ce,"launchToShellCommand");a(Gt,"isNpxForm");a(Bt,"isLegacyHookForm");a(io,"shellQuote")});import*as P from"node:fs/promises";import*as Wt from"node:path";async function L(e){try{return await P.readFile(e,"utf8")}catch(t){if(Fu(t))return null;throw t}}async function Yn(e){await P.mkdir(e,{recursive:!0})}async function M(e,t,n){let r=Wt.dirname(e);await Yn(r);let i=Wt.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await P.writeFile(i,t,{encoding:"utf8",mode:n});try{await P.rename(i,e)}catch(o){if(Lu(o))try{await P.copyFile(i,e),await P.unlink(i).catch(()=>{}),n!==void 0&&await P.chmod(e,n).catch(()=>{});return}catch(s){throw await P.unlink(i).catch(()=>{}),s}throw await P.unlink(i).catch(()=>{}),o}}async function po(e,t){let n=await L(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function Fu(e){return fo(e)&&e.code==="ENOENT"}function Lu(e){return!fo(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function fo(e){return typeof e=="object"&&e!==null&&"code"in e}var ee=w(()=>{"use strict";a(L,"readFileSafe");a(Yn,"ensureDir");a(M,"atomicWriteFile");a(po,"hasLinePrefix");a(Fu,"isNoEnt");a(Lu,"isWindowsRenameFailure");a(fo,"isNodeError")});import{existsSync as ep}from"node:fs";import*as wo from"node:path";function at(e,t={},n=er){let r=t.fileExists??ep,i=t.expectedCommand??tp,o={};if(e!==null&&e.trim().length>0)try{let s=JSON.parse(e);Zn(s)&&(o=s)}catch{}return n.map(s=>{let c={event:s.event,subcommand:s.subcommand},l=np(o,s.event,s.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${s.label} is not wired \u2014 this bridge can run '${s.subcommand}', but nothing calls it.`};let d=` Replace its command with: ${i(s.subcommand)}`;if(Bt(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${s.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+d};if(Gt(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${s.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+d};let u=rp(l);return u!==null&&!r(u)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${s.label} points at ${u}, which does not exist \u2014 the hook fails silently on every run.`+d}:{...c,status:"ok",command:l,remedy:"none",detail:`${s.label} is wired.`}})}function tr(e){return e.some(t=>t.status!=="ok")}function Jt(e){return e.some(t=>t.remedy==="run-install")}function tp(e){return Ce(Y({entryPath:X(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function np(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Zn(i))continue;let o=i.hooks;if(Array.isArray(o))for(let s of o){if(!Zn(s))continue;let c=s.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function rp(e){for(let t of ip(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return wo.isAbsolute(t)?t:null;return null}function ip(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 Zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var er,qt,ct=w(()=>{"use strict";Pe();er=[{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:"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."}],qt=[{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."}];a(at,"inspectHookWiring");a(tr,"hasWiringDrift");a(Jt,"needsInstallRun");a(tp,"defaultExpectedCommand");a(np,"findCommand");a(rp,"extractScriptPath");a(ip,"tokenize");a(Zn,"isObject")});import*as ir from"node:path";import*as ko from"node:readline";async function vo(e,t){let n=ir.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 L(n)}catch(f){return{target:r,action:"merge",status:"failed",detail:`read: ${nr(f)}`}}let o,s="create";if(i===null||i.trim().length===0)o={};else{s="merge";try{let f=JSON.parse(i);if(!rr(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: ${nr(f)}`}}}let c=sp(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:s==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await ap(e.out,`
|
|
7
7
|
Merge a ${t.event} hook into ${n}?
|
|
8
8
|
${t.consentDescription}
|
|
9
9
|
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},d=o.hooks?.[t.event]??[],u={...o,hooks:{...o.hooks??{},[t.event]:[...d,l]}},p=JSON.stringify(u,null,2)+`
|
|
10
|
-
`;if(e.dryRun)return{target:r,action:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:n};try{await
|
|
11
|
-
`).slice(0,1e3)}var Vo=w(()=>{"use strict";a(Wo,"nodeEmbedText")});var lr,dr=w(()=>{"use strict";lr=["function","method","class","interface","enum","type_alias"]});function qo(e,t){let n=Math.min(e.length,t.length),r=0,i=0,o=0;for(let s=0;s<n;s++){let c=e[s],l=t[s];r+=c*l,i+=c*c,o+=l*l}return i===0||o===0?0:r/(Math.sqrt(i)*Math.sqrt(o))}var Jo=w(()=>{"use strict";a(qo,"cosineSimilarity")});import{posix as ur}from"node:path";function zo(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!
|
|
12
|
-
`));let n=[];return is(e,"",n),sn(n)}function is(e,t,n){let r;try{r=
|
|
13
|
-
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=es((l.length>=3?l[l.length-1]:l[1]).trim());u&&(d==="A"||d==="C"?s.set(u,"added"):d==="R"?s.set(u,"renamed"):s.set(u,"modified"))}if(n){let c=
|
|
14
|
-
`)){if(l.length<4)continue;let d=l[0],u=l[1];if(d==="D"||u==="D")continue;let p=l.slice(3),
|
|
15
|
-
`)){if(d.length<4||d[0]!=="?")continue;let u=d.slice(3);u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),!(!u||s.has(u))&&s.set(u,{path:u,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:s,coverage:c}}function
|
|
16
|
-
`)){if(l.startsWith("diff --git ")){c(),o=!1,s=!1;continue}if(l.startsWith("new file mode")){s=!0;continue}if(l.startsWith("rename to ")){o=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:s?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=
|
|
17
|
-
`),b=fs(g[0]??"");if(!b)continue;let y=g.slice(1).filter(_=>_.trim().length>0).length;
|
|
18
|
-
`))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
|
|
19
|
-
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}async function xs(e,t={}){if(re(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,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=re(k(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",o=i?null:r,s=
|
|
20
|
-
`).filter(
|
|
21
|
-
`).map(
|
|
22
|
-
`)){let s=o.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){i=!0;continue}if(i){let c=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);c?t.push(c[1]):s.trim().length>0&&!/^\s/.test(s)&&(i=!1)}}}else{let i=C.join(e,"package.json");if(j(i)){let o=JSON.parse(pt(i,"utf8")),s=Array.isArray(o.workspaces)?o.workspaces:o.workspaces?.packages;Array.isArray(s)&&t.push(...s.filter(c=>typeof c=="string"))}}}catch{return[]}let n=[];for(let r of t){if(n.length>=wr)break;if(!(r.startsWith("!")||r.includes("**")))try{if(r.endsWith("/*")){let i=r.slice(0,-2),o=C.join(e,i);if(!j(o))continue;for(let s of ks(o,{withFileTypes:!0}))if(s.isDirectory()&&!s.name.startsWith(".")&&n.push(C.join(i,s.name)),n.length>=wr)break}else r.includes("*")||n.push(r)}catch{}}return n.slice(0,wr)}function _s(e){let t=null,n=0,r=[e];for(;r.length>0&&n<ws;){let i=r.pop();if(i===void 0)break;let o;try{o=ks(i,{withFileTypes:!0})}catch{continue}for(let s of o){if(s.name.startsWith(".")||s.name==="node_modules")continue;let c=C.join(i,s.name);if(s.isDirectory())r.push(c);else if(s.isFile()){n+=1;try{let l=
|
|
23
|
-
`).filter(Boolean):[]}function
|
|
24
|
-
`,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 ht(e){return e==='"'||e==="'"||e==="`"}function hn(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function pn(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(ht(o)){i=fn(e,i);continue}if(hn(e,i)){i=mn(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function
|
|
25
|
-
`:i==="r"?"\r":i==="t"?" ":i)}function
|
|
26
|
-
specification: ${
|
|
27
|
-
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)
|
|
28
|
-
`):t.readUntracked(e)}var Qs=w(()=>{"use strict";
|
|
10
|
+
`;if(e.dryRun)return{target:r,action:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:n};try{await M(n,p,384)}catch(f){return{target:r,action:"merge",status:"failed",detail:`write: ${nr(f)}`}}return{target:r,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:n}}async function So(e){let t=ir.join(e.homeDir,_o);return vo(e,{event:"SessionStart",command:`cat ${t}`,timeout:5,matchPattern:/maind-session-start-reminder\.md/,targetKey:"hook:~/.claude/settings.json",skipDetail:a(()=>"SessionStart hook already references the reminder file","skipDetail"),consentDescription:`It 'cat's ${_o} into every new Claude Code session.`})}function op(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function we(e,t){let n=e.launch??Y({entryPath:X(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=Ce(n);return vo(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:op(t),skipDetail:a(i=>{let o=`${t.label} already runs maind ${t.subcommand}`;return Bt(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}`:Gt(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})}function lt(e){let t=er.find(n=>n.subcommand===e);if(!t)throw new Error(`no managed hook for subcommand ${e}`);return t}async function Eo(e){return we(e,lt("on-session-end"))}async function xo(e){return we(e,lt("on-session-start"))}async function Ro(e){return we(e,lt("on-tool-use"))}async function Ao(e){return we(e,lt("on-file-write"))}async function To(e){return we(e,lt("on-file-edit"))}function sp(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 s of o){if(!rr(s))continue;let c=s.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function ap(e,t){e.write(t);let n=ko.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 rr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nr(e){return e instanceof Error?e.message:String(e)}var _o,or=w(()=>{"use strict";ee();Pe();ct();_o=".claude/maind-session-start-reminder.md";a(vo,"mergeClaudeHook");a(So,"mergeSessionStartHook");a(op,"targetKeyFor");a(we,"mergeSubcommandHook");a(lt,"managed");a(Eo,"mergeStopHook");a(xo,"mergeSessionStartMetricsHook");a(Ro,"mergeToolUseHook");a(Ao,"mergeFileWriteHook");a(To,"mergeFileEditHook");a(sp,"findExistingHookCommand");a(ap,"promptYesNo");a(rr,"isObject");a(nr,"errMessage")});import{existsSync as cp,readFileSync as lp}from"node:fs";import{join as dp}from"node:path";function ne(){return dp(rt(),"config.json")}function Q(){try{let e=ne();if(!cp(e))return null;let t=JSON.parse(lp(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 Me=w(()=>{"use strict";U();a(ne,"bridgeConfigPath");a(Q,"readBridgeConfig")});function zt(e){return`${e}#<module>`}function Yt(e,t,n){return`${e}#${t}:${n}`}var dt=w(()=>{"use strict";a(zt,"moduleKey");a(Yt,"symbolKey")});function Xt(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 sr(e){return e.toLowerCase().endsWith(".d.ts")}var Qt=w(()=>{"use strict";a(Xt,"languageForPath");a(sr,"isSkippablePath")});function Wo(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
|
|
11
|
+
`).slice(0,1e3)}var Vo=w(()=>{"use strict";a(Wo,"nodeEmbedText")});var lr,dr=w(()=>{"use strict";lr=["function","method","class","interface","enum","type_alias"]});function qo(e,t){let n=Math.min(e.length,t.length),r=0,i=0,o=0;for(let s=0;s<n;s++){let c=e[s],l=t[s];r+=c*l,i+=c*c,o+=l*l}return i===0||o===0?0:r/(Math.sqrt(i)*Math.sqrt(o))}var Jo=w(()=>{"use strict";a(qo,"cosineSimilarity")});import{posix as ur}from"node:path";function zo(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!Cp.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 Yo(e,t){let n=new Set,r=[],i=new Set,o=a((s,c,l)=>{if(s===c)return;let d=`${s}\0${c}\0${l}`;n.has(d)||(n.add(d),r.push({srcKey:s,dstKey:c,kind:l}),i.add(s))},"push");for(let s of e.edges)o(s.srcKey,s.dstKey,s.kind);for(let s of e.nodes)i.add(s.nodeKey);for(let s of e.refs){let c=t.nameToKeys.get(s.targetName);!c||c.length!==1||o(s.fromKey,c[0],s.kind)}for(let s of e.imports){let c=Pp(e.filePath,s.specifier,t.files);c&&o(s.fromModuleKey,zt(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}function Pp(e,t,n){if(!t.startsWith("."))return null;let r=ur.normalize(ur.join(ur.dirname(e),t)),i=[],o=on.some(c=>r.endsWith(c));o&&i.push(r);let s=/\.(js|jsx|mjs|cjs)$/.exec(r);if(s){let c=r.slice(0,-s[0].length);for(let l of on)i.push(c+l)}if(!o){for(let c of on)i.push(r+c);for(let c of on)i.push(`${r}/index${c}`)}for(let c of i)if(n.has(c))return c;return null}var Cp,on,Xo=w(()=>{"use strict";dt();Cp=new Set(["function","method","class","interface","enum","type_alias"]),on=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];a(zo,"buildResolutionIndex");a(Yo,"resolveFileEdges");a(Pp,"resolveImportTarget")});import{execFileSync as Mp}from"node:child_process";import{createHash as Dp}from"node:crypto";import{readdirSync as Op,statSync as Fp}from"node:fs";import{posix as ts,sep as Qo}from"node:path";function k(e,t){try{return Mp("git",[...Lp,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function $p(e){return Qo==="/"?e:e.split(Qo).join("/")}function sn(e){let t=[];for(let n of e){let r=$p(n).trim();if(!r||sr(r))continue;let i=Xt(r);i&&t.push({path:r,language:i})}return t}function ns(e){return sn(e)}function rs(e){let t=Oe(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return sn(t.split(`
|
|
12
|
+
`));let n=[];return is(e,"",n),sn(n)}function is(e,t,n){let r;try{r=Op(ts.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&Zo.has(i.name)||Zo.has(i.name))continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?is(e,o,n):i.isFile()&&n.push(o)}}function pr(e,t){let r=k(e,["merge-base",t,"HEAD"])?.trim();return r&&r.length>0?r:t}function an(e,t={}){if(ut(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?pr(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=Oe(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let s=new Map;for(let c of o.split(`
|
|
13
|
+
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=es((l.length>=3?l[l.length-1]:l[1]).trim());u&&(d==="A"||d==="C"?s.set(u,"added"):d==="R"?s.set(u,"renamed"):s.set(u,"modified"))}if(n){let c=Oe(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
|
|
14
|
+
`)){if(l.length<4)continue;let d=l[0],u=l[1];if(d==="D"||u==="D")continue;let p=l.slice(3),f=p.indexOf(" -> ");f>=0&&(p=p.slice(f+4)),p=es(p),!(!p||s.has(p))&&(d==="?"||d==="A"||u==="A"?s.set(p,"added"):d==="R"?s.set(p,"renamed"):s.set(p,"modified"))}}return s}function es(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function os(e,t={}){let n=an(e,t);return n===null?null:sn(n.keys())}function ss(e,t){try{let n=Fp(ts.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function cn(e){return Dp("sha256").update(e).digest("hex")}function ut(e){return Oe(e,["rev-parse","HEAD"])?.trim()??null}function ln(e,t){return Oe(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function as(e){let t=Oe(e,["status","--porcelain","-uall"]);return t!==null&&t.trim().length>0}var Zo,Lp,Oe,V=w(()=>{"use strict";Qt();Zo=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),Lp=["-c","diff.renames=true","-c","core.quotePath=false"];a(k,"runGit");Oe=k;a($p,"toPosix");a(sn,"classify");a(ns,"classifyPaths");a(rs,"discoverSourceFiles");a(is,"walk");a(pr,"resolveDiffBase");a(an,"enumerateChangedPaths");a(es,"unquote");a(os,"changedSourceFiles");a(ss,"statFile");a(cn,"hashContent");a(ut,"headCommit");a(ln,"resolveCommitSha");a(as,"isWorktreeDirty")});function ls(e,t={}){if(k(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?pr(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 s=new Map,c="full";if(Buffer.byteLength(o,"utf8")>jp?c="none":Gp(o,s,()=>{c="partial"}),n){let l=k(e,["status","--porcelain","-uall"])??"";for(let d of l.split(`
|
|
15
|
+
`)){if(d.length<4||d[0]!=="?")continue;let u=d.slice(3);u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),!(!u||s.has(u))&&s.set(u,{path:u,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:s,coverage:c}}function Gp(e,t,n){let r=null,i=0,o=!1,s=!1,c=a(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
|
|
16
|
+
`)){if(l.startsWith("diff --git ")){c(),o=!1,s=!1;continue}if(l.startsWith("new file mode")){s=!0;continue}if(l.startsWith("rename to ")){o=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:s?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=Kp.exec(l);if(d){if(i++,i>Hp){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let u=Number(d[1]),p=d[2]===void 0?1:Number(d[2]);p>0?r.addedRanges.push({start:u,end:u+p-1}):r.deletionPoints.push(u);continue}l.startsWith("+")&&!l.startsWith("+++")&&!r.degraded&&r.addedLines.length<Up&&r.addedLines.push(l.slice(1))}c()}var jp,Hp,Up,cs,Kp,ds=w(()=>{"use strict";V();jp=16*1024*1024,Hp=500,Up=4e3,cs=256*1024,Kp=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;a(ls,"changedHunks");a(Gp,"parseUnifiedDiff")});function Vp(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function ps(e){return e.split(Bp).filter(t=>t.trim().length>0)}function fs(e){let[t,n,r,i,o]=e.replace(/\n+$/,"").split(Wp);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:o??""}}function qp(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 hs(e,t,n={}){let r=Vp(n.limit,20,100),i=n.includeOwnership!==!1,o=Math.max(r,ms),s=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=s.slice(0,fr),l=[];for(let u of c){let p=k(e,["log","-n",String(o),us,"--",u]),f=p===null?[]:ps(p).map(fs).filter(h=>h!==null);l.push({path:u,lastCommits:f.slice(0,r),ownership:i?{topAuthors:qp(f),commitsInWindow:f.length}:null})}let d=null;if(n.since){let u=ln(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],f=k(e,["log",...p,"-n",String(dn+1),us,"--name-only","--",...c]),h=[];if(f!==null)for(let m of ps(f)){let g=m.split(`
|
|
17
|
+
`),b=fs(g[0]??"");if(!b)continue;let y=g.slice(1).filter(_=>_.trim().length>0).length;h.push({sha:b.sha,dateIso:b.dateIso,authorName:b.authorName,subject:b.subject,filesTouched:y})}d={sinceInput:n.since,sinceResolved:u,commits:h.slice(0,dn),truncated:h.length>dn}}return{history:l,regression:d,ownershipWindowCommits:o,pathsTruncated:s.length>fr}}var Bp,Wp,ms,fr,dn,us,mr=w(()=>{"use strict";V();Bp="",Wp="\0",ms=200,fr=50,dn=100,us="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";a(Vp,"clamp");a(ps,"splitRecords");a(fs,"parseHistoryRecord");a(qp,"aggregateOwnership");a(hs,"readFileHistory")});import{execFileSync as Jp}from"node:child_process";import{readdirSync as zp,statSync as gs}from"node:fs";import{isAbsolute as Yp,join as hr,relative as Xp,resolve as Qp}from"node:path";function ef(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function tf(e,t){try{let n=Jp("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 nf(e){let t;try{t=zp(e)}catch{return null}for(let n of t.filter(ef))try{let r=gs(hr(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function rf(e){try{return gs(e).isDirectory()}catch{return!1}}function of(e,t){let n=Xp(e,t);return!n||n.startsWith("..")?t:n}function gr(e){let t=Zp.filter(c=>rf(hr(e,c))),n=tf(e,"core.hooksPath"),r=n?Yp(n)?n:Qp(e,n):hr(e,".git","hooks"),i=of(e,r),o=nf(r);if(o===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let s=n?o===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:s,hookDirs:t,hooksPath:n,effectiveDir:i}}function yr(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 Zp,br=w(()=>{"use strict";Zp=[".githooks",".husky"];a(ef,"isRealHook");a(tf,"gitConfig");a(nf,"hasExecutableHook");a(rf,"isDir");a(of,"displayPath");a(gr,"resolveHookState");a(yr,"describeHookState")});import{execFileSync as sf}from"node:child_process";import{existsSync as j,readFileSync as pt,readdirSync as ks,statSync as af}from"node:fs";import{posix as C}from"node:path";function Ss(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 s=e.upstream.split("/").slice(1).join("/");s&&s!==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 s=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${s} 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 (scripts/feature.sh start <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 s=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${s.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 ${_r}.`})}if(e.stalePackageBuilds.length>0){let s=e.stalePackageBuilds,c=a(d=>d.impact==="runtime"?`${d.packageDir} (runtime)`:d.packageDir,"label"),l=s.every(d=>d.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:s.some(d=>d.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${s.map(c).join(", ")}: src/ is newer than the built ${[...new Set(s.map(d=>d.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${l}`,hint:`Rebuild: pnpm --filter ./${s[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=cf(e.hooks);return o&&t.push(o),lf(t)}function cf(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:yr(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 lf(e){return[...e].sort((t,n)=>ys[t.status]-ys[n.status]||t.id.localeCompare(n.id))}function Es(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function re(e){let t=e?.trim();return t||null}function df(e){let t=re(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 uf(e){let t=re(k(e,["rev-parse","--git-dir"]));if(!t)return null;let n=C.isAbsolute(t)?t:C.join(e,t);return j(C.join(n,"rebase-merge"))||j(C.join(n,"rebase-apply"))?"rebase":j(C.join(n,"MERGE_HEAD"))?"merge":j(C.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function pf(e){let t=[],n=null,r=a(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
|
|
18
|
+
`))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 ff(e){let t=C.join(e,_r);if(!j(t))return[];try{return pt(t,"utf8").split(`
|
|
19
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}async function xs(e,t={}){if(re(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,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=re(k(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",o=i?null:r,s=df(e),c=re(k(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let T=re(k(e,["rev-parse","HEAD"])),A=re(k(e,["rev-parse","@{u}"]));l=T!=null&&A!=null?T===A:null,d=k(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,p=null;if(s){let T=re(k(e,["rev-list","--left-right","--count",`origin/${s}...HEAD`]));if(T){let[A,H]=T.split(/\s+/).map(R=>Number.parseInt(R,10));Number.isFinite(A)&&(p=A),Number.isFinite(H)&&(u=H)}}let h=(k(e,["status","--porcelain"])??"").split(`
|
|
20
|
+
`).filter(T=>T.trim().length>0).length,m=uf(e),g=re(k(e,["rev-parse","--show-toplevel"]))??e,b=pf(k(e,["worktree","list","--porcelain"])??""),y=b[0]?.path??null,_=y!=null&&bs(y,g),S=Math.max(0,b.length-1),v=null;if(y&&!bs(y,g)){let A=[...vs,...ff(g),...t.probePaths??[]].filter(H=>j(C.join(y,H))&&!j(C.join(g,H)));v={mainWorktreePath:y,currentWorktreePath:g,missing:[...new Set(A)]}}let E=t.includeRelease===!1?null:yf(e,o),x=[];return s&&(x=(k(e,["diff","--name-only","--diff-filter=A",`origin/${s}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
|
|
21
|
+
`).map(A=>A.trim()).filter(A=>A.length>0)),{isRepo:!0,branch:o,defaultBranch:s,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:p,uncommitted:h,detachedHead:i,inProgressOp:m,isSharedMainTree:_,otherWorktrees:S,worktreeParity:v,stalePackageBuilds:Rs(g),release:E,unmergedMigrations:x,hooks:gr(e)}}function bs(e,t){let n=a(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function hf(e){let t=[];try{let r=C.join(e,"pnpm-workspace.yaml");if(j(r)){let i=!1;for(let o of pt(r,"utf8").split(`
|
|
22
|
+
`)){let s=o.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){i=!0;continue}if(i){let c=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);c?t.push(c[1]):s.trim().length>0&&!/^\s/.test(s)&&(i=!1)}}}else{let i=C.join(e,"package.json");if(j(i)){let o=JSON.parse(pt(i,"utf8")),s=Array.isArray(o.workspaces)?o.workspaces:o.workspaces?.packages;Array.isArray(s)&&t.push(...s.filter(c=>typeof c=="string"))}}}catch{return[]}let n=[];for(let r of t){if(n.length>=wr)break;if(!(r.startsWith("!")||r.includes("**")))try{if(r.endsWith("/*")){let i=r.slice(0,-2),o=C.join(e,i);if(!j(o))continue;for(let s of ks(o,{withFileTypes:!0}))if(s.isDirectory()&&!s.name.startsWith(".")&&n.push(C.join(i,s.name)),n.length>=wr)break}else r.includes("*")||n.push(r)}catch{}}return n.slice(0,wr)}function _s(e){let t=null,n=0,r=[e];for(;r.length>0&&n<ws;){let i=r.pop();if(i===void 0)break;let o;try{o=ks(i,{withFileTypes:!0})}catch{continue}for(let s of o){if(s.name.startsWith(".")||s.name==="node_modules")continue;let c=C.join(i,s.name);if(s.isDirectory())r.push(c);else if(s.isFile()){n+=1;try{let l=af(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=ws)break}}}return t}function gf(e,t){let n=new Set;for(let r of t)try{let i=C.join(e,r,"package.json");if(!j(i))continue;let o=JSON.parse(pt(i,"utf8"));for(let s of["dependencies","devDependencies","peerDependencies"]){let c=o[s];if(!(c===null||typeof c!="object"))for(let[l,d]of Object.entries(c))typeof d=="string"&&d.startsWith("workspace:")&&n.add(l)}}catch{}return n}function Rs(e){let t=[],n=hf(e),r=gf(e,n);for(let i of n)try{let o=C.join(e,i,"package.json");if(!j(o))continue;let s=JSON.parse(pt(o,"utf8"));if(typeof s.name!="string"||!r.has(s.name))continue;let c=a(y=>{if(typeof y!="string")return null;let _=y.replace(/^\.\//,"").split("/")[0];return _==="build"||_==="dist"?_:null},"builtSeg"),l=c(s.types??s.typings),d=c(s.main),u=l??d;if(u===null)continue;let p=l!==null&&d!==null?"both":l!==null?"types":"runtime",f=C.join(e,i,"src"),h=C.join(e,i,u);if(!j(f)||!j(h))continue;let m=_s(f),g=_s(h);if(m===null||g===null)continue;let b=m-g;b>mf&&t.push({packageDir:i,buildDir:u,srcNewerByMs:Math.round(b),impact:p})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}function yf(e,t){if(!t)return null;let n=bf(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 bf(e,t){try{return sf("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function kr(e,t={}){let n=await xs(e,t),r=Ss(n);return{ok:Es(r),findings:r,facts:n}}var vs,_r,ys,mf,wr,ws,vr=w(()=>{"use strict";br();V();vs=["supabase/config.toml","supabase/.temp",".env"],_r=".maind/worktree-requirements";a(Ss,"computeDivergence");a(cf,"computeHookFinding");ys={open:0,warn:1,info:2,passed:3};a(lf,"sortFindings");a(Es,"isHealthy");a(re,"trimOrNull");a(df,"resolveDefaultBranch");a(uf,"detectInProgressOp");a(pf,"parseWorktrees");a(ff,"readWorktreeRequirements");a(xs,"gatherRepoHealthFacts");a(bs,"samePath");mf=2e3,wr=64,ws=4e3;a(hf,"listWorkspacePackageDirs");a(_s,"newestMtimeUnder");a(gf,"consumedWorkspaceNames");a(Rs,"gatherStalePackageBuilds");a(yf,"gatherReleaseFact");a(bf,"runGh");a(kr,"checkDivergence")});import{existsSync as Sr,readdirSync as As}from"node:fs";import{posix as Z}from"node:path";function Is(e,t={}){let n=t.minFiles??Er;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Ts)}function Le(e){return`${e.dir}#${e.prefix}`}function ft(e){let t=wf.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function Ns(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let o=Le(i),s=e.sightingsByNamespace.get(o);if(!s)continue;let c=new Set(s.keys());for(let[l,d]of s){let u=[...new Set(d.map(m=>m.path))];if(u.length<2)continue;let p=u.find(m=>n.has(m)),f=u.filter(m=>m!==p),h=`${i.prefix}${l}`;t.push(p?{id:`number.collision:${o}#${l}`,status:"open",namespace:i,number:l,title:`${h} is already taken`,detail:`This branch adds ${p}, but ${h} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${h} stop being unambiguous.`,ownPath:p,sightings:d.filter(m=>m.path!==p),suggestion:`${i.prefix}${xr(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${o}#${l}`,status:"info",namespace:i,number:l,title:`${h} is used more than once (pre-existing)`,detail:`${h} is carried by ${u.length} files: ${u.join(", ")}.`,sightings:d,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 Cs(e){return!e.some(t=>t.status==="open")}function xr(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 Rr(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Ps(e,t){let n=Rr(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=ft(Z.basename(n));if(!i)return r;let o=`${Z.dirname(n)}#${i.prefix}`,s=e.namespaces.find(u=>Le(u)===o)??null;if(!s)return{...r,number:i.number};let c=e.sightingsByNamespace.get(o)??new Map,l=new Set,d=[];for(let u of c.get(i.number)??[])u.path===n||l.has(u.path)||(l.add(u.path),d.push(u));return{path:n,namespace:s,number:i.number,taken:d.length>0,sightings:d,suggestion:xr(c.keys(),i.number)}}function un(e){let t=e?.trim();return t||null}function Fe(e){return e?e.split(`
|
|
23
|
+
`).filter(Boolean):[]}function _f(e){let t=un(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 Ms(e,t={}){let n=t.minFiles??Er,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 s of i.split("\0").filter(Boolean)){let c=Z.dirname(s),l=ft(Z.basename(s));if(!l)continue;let d=`${c}#${l.prefix}`,u=o.get(d);u?u.numbers.push(l.number):o.set(d,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...o.values()].filter(s=>Is(s.numbers,{...t,minFiles:n})).map(s=>({dir:s.dir,prefix:s.prefix,fileCount:s.numbers.length,distinctRatio:new Set(s.numbers).size/s.numbers.length})).sort((s,c)=>Le(s).localeCompare(Le(c)))}async function Ar(e,t={}){let n=[];if(un(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=Ms(e,t),o=new Map(i.map(h=>[Le(h),h])),s=[...new Set(i.map(h=>h.dir))],c=new Map,l=a((h,m,g)=>{let b=Z.dirname(h),y=ft(Z.basename(h));if(!y)return;let _=`${b}#${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"),d=a((h,m,g)=>{if(s.length===0)return;let b=k(e,["ls-tree","-r","--name-only",h,"--",...s]);if(b===null){n.push(`could not read ${g}`);return}for(let y of Fe(b))l(y,m,g)},"scanTree");for(let h of s){let m=Z.join(e,h);if(Sr(m))try{for(let g of As(m))l(`${h}/${g}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let u=_f(e);u?d(`origin/${u}`,"default_branch",`origin/${u}`):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let p=un(k(e,["rev-parse","--abbrev-ref","HEAD"]));for(let h of Fe(k(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))h!==p&&d(h,"branch",`Branch ${h}`);if(t.includeWorktrees!==!1){let h=un(k(e,["rev-parse","--show-toplevel"]));for(let m of Fe(k(e,["worktree","list","--porcelain"]))){if(!m.startsWith("worktree "))continue;let g=m.slice(9).trim();if(!(!g||g===h||!Sr(g)))for(let b of s){let y=Z.join(g,b);if(Sr(y))try{for(let _ of As(y))l(`${b}/${_}`,"worktree",`Worktree ${g}`)}catch{n.push(`could not read ${b} in ${g}`)}}}}let f=[];if(u&&s.length>0){let h=k(e,["diff","--name-only","--diff-filter=A",`origin/${u}...HEAD`,"--",...s]);h===null?n.push("could not diff against the default branch \u2014 everything reported as info"):f=Fe(h);let m=k(e,["ls-files","--others","--exclude-standard","--",...s]);m!==null&&(f=[...f,...Fe(m)]);let g=k(e,["diff","--cached","--name-only","--diff-filter=A","--",...s]);g!==null&&(f=[...f,...Fe(g)])}return{isRepo:!0,defaultBranch:u,namespaces:i,sightingsByNamespace:c,addedPaths:f,skipped:n}}async function mt(e,t={}){let n=await Ar(e,t),r=Ns(n);return{ok:Cs(r),findings:r,facts:n}}async function ke(e,t,n={}){let r=Rr(t);if(!ft(Z.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Ar(e,{...n,dirs:n.dirs??[Z.dirname(r)]});return Ps(i,r)}var wf,Er,Ts,Tr=w(()=>{"use strict";V();wf=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Er=3,Ts=.8;a(Is,"isCounterNamespace");a(Le,"namespaceKey");a(ft,"parseNumbered");a(Ns,"computeNumberCollisions");a(Cs,"isCollisionFree");a(xr,"suggestNextNumber");a(Rr,"normaliseRepoPath");a(Ps,"checkProposedNumber");a(un,"trimOrNull");a(Fe,"lines");a(_f,"resolveDefaultBranch");a(Ms,"detectNamespaces");a(Ar,"gatherNumberCollisionFacts");a(mt,"checkNumberCollisions");a(ke,"checkNumberForPath")});import{existsSync as kf,readFileSync as Ds}from"node:fs";import{posix as vf}from"node:path";function fn(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 mn(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
|
|
24
|
+
`,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 ht(e){return e==='"'||e==="'"||e==="`"}function hn(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function pn(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(ht(o)){i=fn(e,i);continue}if(hn(e,i)){i=mn(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function Sf(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(hn(e,t)){t=mn(e,t);continue}break}return e.slice(t)}function $e(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let o=e[i];if(ht(o)){i=fn(e,i);continue}if(hn(e,i)){i=mn(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=>Sf(o).trim()).filter(o=>o.length>0)}function js(e){let t=fn(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
|
|
25
|
+
`:i==="r"?"\r":i==="t"?" ":i)}function Ef(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nr(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${Ef(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,o=!1;for(;i<e.length;){let s=e[i];if(ht(s)){i=fn(e,i);continue}if(hn(e,i)){i=mn(e,i);continue}if(!o){if(s==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))o=!0;else if(s===";")return null;i++;continue}if(s==="[")return pn(e,i);if(s===";")return null;i++}return null}function Cr(e){let t={};if(!e.startsWith("{"))return t;for(let n of $e(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();ht(o[0]??"")&&(t[i]=js(o))}return t}function xf(e,t){if(!e.startsWith("{"))return null;for(let n of $e(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 Hs(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Us(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Ks(e,t){let n=Nr(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Us(),i=[],o=0;for(let s of $e(n.slice(1,-1))){if(!s.startsWith("{")){o++;continue}let c=Cr(s),l=c[t.key_field];if(!l){o++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");i.push({key:l,fields:Hs(c,t.fields),orderPath:d,ordinal:r(d)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function Gs(e,t){let n=Nr(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=Us(),i=[],o=0,s=a((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let f of $e(c.slice(1,-1))){let h={...d},m=null;if(u.shape==="object"){if(!f.startsWith("{")){o++;continue}let g=Cr(f);for(let[b,y]of Object.entries(u.fields??{}))h[b]=g[String(y)]??"";if(!p&&typeof u.children=="string"){let b=xf(f,u.children);m=b&&b.startsWith("[")?pn(b,0):null}}else{if(!f.startsWith("[")){o++;continue}let g=$e(f.slice(1,-1));for(let[b,y]of Object.entries(u.fields??{})){let _=g[Number(y)];h[b]=_!==void 0&&ht(_[0]??"")?js(_):""}if(!p&&typeof u.children=="number"){let b=g[u.children];m=b!==void 0&&b.startsWith("[")?pn(b,0):null}}if(p){let g=h[t.key_field];if(!g){o++;continue}let b=(t.partition_by??[]).map(y=>h[y]??"");i.push({key:g,fields:Hs(h,t.fields),orderPath:b,ordinal:r(b)});continue}m!==null&&s(m,l+1,h)}},"walk");return s(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 Os(e,t){return t.extractor==="object-array"?Ks(e,t):Gs(e,t)}function Bs(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 Ws(e,t,n){return`spec.drift:${e}#${t}:${n}`}function Rf(e){return e.orderPath.join(" / ")||"(flat)"}function Vs(e,t,n,r){let i=[],o=a((d,u,p,f,h,m)=>{i.push({id:Ws(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:f,detail:h,hint:m})},"push"),s=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=s.get(d.key);if(!u){o("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${Rf(d)}, position ${d.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=d.fields[p]??"",h=u.fields[p]??"";f!==h&&o("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${h||"\u2014"}", the specification says "${f||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),p=l.get(u);p?p.push(d):l.set(u,[d])}for(let[d,u]of l){let p=u.filter(g=>s.has(g.key)).map(g=>g.key),f=n.filter(g=>g.orderPath.join("\0")===d).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=d.split("\0").join(" / ")||"(flat)";o("order","open",g,`Partition ${g}: sequence differs from the specification`,`implementation: ${f.join(" \u2192 ")}
|
|
26
|
+
specification: ${m.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let d of n)c.has(d.key)||o("extra","warn",d.key,`${d.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 d of new Set([...s.keys(),...c.keys()])){if(Bs(d,e.grounding,r))continue;let u=s.has(d);o("unrealized",u?"open":"warn",d,u?`${d} is referenced by the implementation but has no artefact`:`${d} is declared by the specification but not built yet`,u?`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 Af(e,t,n){let r=[];for(let i of e.assertions??[]){let o=n.get(i.path);if(!o)continue;let s=o.indexOf(i.prefix);if(s===-1)continue;let c=/^\s*(\d+)/.exec(o.slice(s+i.prefix.length));if(!c)continue;let l=Number(c[1]),d=t[i.counts];l!==d&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${d}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function Fs(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 qs(e,t={}){let n=a(u=>({ok:!1,verdict:"no_opinion",reason:u,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(u=>t.contracts.includes(u.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(u=>`"${u}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=a(u=>{let p=[],f=[];for(let h of r){let m=u.get(h.spec.path),g=u.get(h.impl.path);if(m==null||g==null){let S=m==null?h.spec.path:h.impl.path;p.push(Fs(h.id,`Declared file could not be read: ${S}`)),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let b=Os(m,h.spec),y=Os(g,h.impl);if(b.error||y.error){p.push(Fs(h.id,b.error??y.error??"unknown")),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=b.dropped>0||y.dropped>0;f.push({id:h.id,measured:!0,specRecords:b.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:`${b.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(...Vs(h,b.records,y.records,e.files)),p.push(...Af(h,{spec:b.records.length,impl:y.records.length},u))}return{findings:p,contracts:f}},"runOnce"),o=i(e.sources),s=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let u of i(e.baselineSources).findings)u.id.startsWith("contract.unreadable:")||s.add(u.id);let c=new Map;for(let u of r)for(let p of u.exceptions??[])c.set(Ws(u.id,p.dimension,p.key),p);let l=o.findings.map(u=>{let p=c.get(u.id);return p?{...u,status:"info",exceptionReason:p.reason}:s.has(u.id)?{...u,status:"info",detail:`${u.detail}
|
|
27
|
+
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>Ls[u.status]-Ls[p.status]||u.id.localeCompare(p.id));let d=l.some(u=>u.status==="open");return{ok:!d,verdict:d?"drifted":"aligned",reason:null,findings:l,contracts:o.contracts}}function Ir(e){let t=e?.trim();return t||null}function Js(e){let t;try{t=JSON.parse(e)}catch(s){return{manifest:null,error:`manifest is not valid JSON: ${s.message}`}}let n=a(s=>s!==null&&typeof s=="object"&&!Array.isArray(s)?s:null,"obj"),r=a(s=>typeof s=="string"?s:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let o=a(s=>({manifest:null,error:s}),"bad");for(let[s,c]of i.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${s+1}`;if(!l)return o(`${u}: not an object`);if(!d)return o(`${u}: \`id\` is missing`);if(!r(l.reason))return o(`${u}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let p of["spec","impl"]){let f=n(l[p]);if(!f)return o(`${u}: \`${p}\` is missing`);let h=r(f.extractor);if(!h)return o(`${u}: \`${p}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return o(`${u}: unknown \`${p}.extractor\` "${h}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return o(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(f.levels))return o(`${u}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(l.exceptions)?l.exceptions:[]){let f=n(p);if(!f||!r(f.reason))return o(`${u}: 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 Tf(e){let t=Ir(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 If(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 zs(e,t={}){let n=a((m,g)=>vf.join(m,g),"join"),r=t.manifestPath??$s,i=[],o={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(Ir(k(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...o,manifestError:"not a git work tree"};let s=n(e,r);if(!kf(s))return{...o,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,l=null;try{({manifest:c,error:l}=Js(Ds(s,"utf8")))}catch(m){l=`manifest at ${r} could not be read: ${m.message}`}if(!c)return{...o,isRepo:!0,manifestError:l};let d=new Map;for(let m of If(c))try{d.set(m,Ds(n(e,m),"utf8"))}catch{d.set(m,null),i.push(`declared file unreadable in the working tree: ${m}`)}let u=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&&u.add(m);let f=null,h=new Map;if(t.includeBaseline!==!1){let m=Tf(e);if(!m)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(f=Ir(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 d.keys())h.set(g,k(e,["show",`${f}:${g}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:h,baseRef:f,files:u,skipped:i}}async function Pr(e,t={}){let n=await zs(e,t);return{...qs(n,t),facts:n}}var $s,Ls,Mr=w(()=>{"use strict";V();$s=".maind/spec-contracts.json";a(fn,"endOfString");a(mn,"skipComment");a(ht,"isQuote");a(hn,"isCommentStart");a(pn,"sliceBalanced");a(Sf,"stripLeadingTrivia");a($e,"splitTopLevel");a(js,"readStringLiteral");a(Ef,"escapeRe");a(Nr,"findSymbolArray");a(Cr,"parseObjectFields");a(xf,"objectFieldRaw");a(Hs,"pickFields");a(Us,"makeOrdinals");a(Ks,"extractObjectArray");a(Gs,"extractNestedList");a(Os,"extractRecords");a(Bs,"isGrounded");a(Ws,"findingId");a(Rf,"partitionOf");a(Vs,"compareContract");a(Af,"checkAssertions");a(Fs,"unreadable");Ls={open:0,warn:1,info:2,passed:3};a(qs,"computeSpecDrift");a(Ir,"trimOrNull");a(Js,"parseManifest");a(Tf,"resolveDefaultBranch");a(If,"declaredPaths");a(zs,"gatherSpecDriftFacts");a(Pr,"checkSpecDrift")});var Ys,Dr=w(()=>{"use strict";Ys=[{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 Xs(e){let t=new Set;for(let[n,r]of e.paths)for(let i of Ys){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let o=Nf(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function Nf(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
28
|
+
`):t.readUntracked(e)}var Qs=w(()=>{"use strict";Dr();a(Xs,"scanRiskFlags");a(Nf,"contentForPath")});var gt,Zs,yt,gn,Or,Fr,Lr,$r,bt=w(()=>{"use strict";gt="1",Zs=`
|
|
29
29
|
CREATE TABLE IF NOT EXISTS meta (
|
|
30
30
|
key TEXT PRIMARY KEY,
|
|
31
31
|
value TEXT NOT NULL
|
|
@@ -84,50 +84,50 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
84
84
|
vec BLOB NOT NULL,
|
|
85
85
|
content_hash TEXT NOT NULL
|
|
86
86
|
);
|
|
87
|
-
`,yt="schema_version",gn="last_index_commit",
|
|
87
|
+
`,yt="schema_version",gn="last_index_commit",Or="last_indexed_at",Fr="embed_recipe_version",Lr="embed_model",$r="embed_dim"});function jr(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 ea(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of jr(e.name))t.add(i);for(let i of jr(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function ta(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 jr(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var Hr=w(()=>{"use strict";a(jr,"splitIdentifier");a(ea,"buildSearchText");a(ta,"toFtsMatchQuery")});import{readFileSync as na}from"node:fs";import{posix as ra}from"node:path";function ia(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 ve(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function oa(e){return e==="added"?0:e==="modified"?1:2}function Cf(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 s of n.addedRanges){let c=Math.max(s.start,e.startLine),l=Math.min(s.end,e.endLine);l>=c&&(i+=l-c+1)}let o=n.deletionPoints.some(s=>s>=e.startLine-1&&s<=e.endLine);return i>0||o?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var wt,Ur=w(()=>{"use strict";Vo();dr();Jo();Xo();V();ds();mr();vr();Tr();Mr();Qs();bt();Hr();wt=class{static{a(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(yt),i=await this.store.countFiles()>0;(t.full||i&&r!==gt)&&await this.wipe();let o=rs(this.repoRoot),s=new Set(o.map(m=>m.path)),c=await this.store.getAllFiles(),l=new Map(c.map(m=>[m.path,m])),d=c.length>0&&!t.full,u={filesScanned:o.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:d};for(let m of c)s.has(m.path)||(await this.store.deleteFile(m.path),u.filesDeleted++);let p=[],f=0;for(let m of o){f++;let g=ss(this.repoRoot,m.path);if(!g){u.filesSkipped++;continue}let b=l.get(m.path);if(b&&b.mtimeMs===g.mtimeMs&&b.size===g.size){u.filesSkipped++;continue}let y=this.readRepoFile(m.path);if(y===null){u.filesSkipped++;continue}let _=cn(y);if(b&&b.contentHash===_){await this.store.upsertFile({...b,mtimeMs:g.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let S=await this.parser.parse(m.path,y,m.language),v=new Map;for(let x of S.nodes)v.set(x.nodeKey,ea(x));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),u.filesParsed++,t.onProgress?.({path:m.path,done:f,total:o.length})}if(p.length>0){let m=await this.store.getNameIndex(),g=zo(m);for(let b of p){let y=Yo(b,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(),b=[];for(let _ of m){let S=Wo(_),v=cn(`${this.embedder.recipeVersion}\0${S}`);g.get(_.nodeKey)!==v&&b.push({nodeKey:_.nodeKey,text:S,hash:v})}let y=64;for(let _=0;_<b.length;_+=y){let S=b.slice(_,_+y),v=await this.embedder.embedDocuments(S.map(x=>x.text));await this.store.upsertEmbeddings(S.map((x,T)=>({nodeKey:x.nodeKey,dim:this.embedder.dim,vec:v[T],contentHash:x.hash})));let E=Math.min(_+y,b.length);t.onProgress?.({path:"embedding symbols",done:E,total:b.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Fr,this.embedder.recipeVersion),await this.store.setMeta(Lr,this.embedder.model),await this.store.setMeta($r,String(this.embedder.dim))}await this.store.setMeta(yt,gt),await this.store.setMeta(Or,String(n));let h=ut(this.repoRoot);return h&&await this.store.setMeta(gn,h),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(t.now??Date.now())-n,u}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(Or);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(gn),schemaVersion:await this.store.getMeta(yt),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=ve(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),o=[];for(let s of i){let c=await this.store.getNode(s.nodeKey);c&&o.push({...ia(c),score:s.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=ve(n.limit,20,100),i=await this.embedder.embedQuery(t),s=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:qo(i,l.vec)})).sort((l,d)=>d.score-l.score).slice(0,r),c=[];for(let l of s){let d=await this.store.getNode(l.nodeKey);d&&c.push({...ia(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=ve(n.maxDepth,3,5),o=ve(n.limit,100,1e3),s=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<i&&u.length>0;p++){let f=[];for(let h of u){let m=await this.store.neighbors(h,r,s,o);for(let g of m){let b=`${g.srcKey} ${g.dstKey} ${g.kind}`;if(l.has(b))continue;if(l.add(b),c.push({srcKey:g.srcKey,dstKey:g.dstKey,kind:g.kind}),c.length>=o)return c;let y=r==="out"?g.dstKey:g.srcKey;d.has(y)||(d.add(y),f.push(y))}}u=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=na(ra.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 s of n)i[s.kind]=s.count;let o={};for(let s of r)o[s.language]=s.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(ve(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=os(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=ve(t.limit,64,200),i=[],o=0;for(let s of n){let c=await this.store.getNodesByFile(s.path);c.length>0&&o++,i.push(...c)}return i.sort((s,c)=>s.filePath.localeCompare(c.filePath)||s.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=an(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(ut(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return hs(this.repoRoot,n,t)}async checkDivergence(t={}){return kr(this.repoRoot,t)}async checkNumberCollisions(t={}){return mt(this.repoRoot,t)}async checkNumberForPath(t,n={}){return ke(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Pr(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=an(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=ls(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",s=Xs({paths:n,hunks:i,readUntracked:a(f=>this.readRepoFileHead(f,cs),"readUntracked")}),c=ns(n.keys()),l=ve(t.limit,64,200),d=[],u=0,p=0;for(let f of c){let h=await this.store.getNodesByFile(f.path);if(h.length===0)continue;u++;let m=await this.store.getFile(f.path),g=this.readRepoFile(f.path),b=m!==null&&g!==null&&cn(g)!==m.contentHash;b&&(p++,o==="full"&&(o="partial"));let y=n.get(f.path)??"modified",_=i.get(f.path);for(let S of h)d.push(Cf(S,y,_,b))}return d.sort((f,h)=>oa(f.change)-oa(h.change)||f.filePath.localeCompare(h.filePath)||f.startLine-h.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:s,hunkCoverage:o,baseKind:t.since?"ref":"uncommitted",headSha:ut(this.repoRoot),dirty:as(this.repoRoot),baseSha:t.since?ln(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 na(ra.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};a(ia,"toHit");a(ve,"clampLimit");a(oa,"changeRank");a(Cf,"classifyReviewSymbol")});var Ia=w(()=>{"use strict"});import{readFileSync as Vf}from"node:fs";import{join as Na}from"node:path";function Oa(e){let t=new Set;for(let n of e.matchAll(qf))t.add(n[1]);return t}function Gr(e){return new Set([...e].map(t=>t.split("-")[0]))}function Fa(e){return e.split(`
|
|
88
88
|
`).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
|
|
89
|
-
`)}function
|
|
90
|
-
`).filter(Boolean)}function Br(e,t={}){let n=t.maxFileBytes??
|
|
91
|
-
`;)n++;continue}if(i==="/"&&o==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let s=(i==="E"||i==="e")&&o==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||s){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 fe(e){let t=[],n="",r=!1,i=!1,o=a(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){o();continue}n+=l}o();let s=t.filter(c=>c.length>0);return s.length===0||s.length>2?null:s.length===2?{schema:s[0],name:s[1]}:{schema:"public",name:s[0]}}function St(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 Ba(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 s=i.trim();if(
|
|
92
|
-
`).filter(Boolean)){let[p,...
|
|
93
|
-
`).filter(Boolean).slice(-1)[0]}}function Ja(e,t,n){let r=e(t,
|
|
94
|
-
`).map(i=>i.trim()).filter(Boolean)}}function Za(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
|
|
95
|
-
`)){if(!o.startsWith("worktree "))continue;let s=o.slice(9).trim();if(!s||s===i||!zr(s))continue;let c=Yr(s,t);if(zr(c))try{for(let l of
|
|
96
|
-
`)),this.machineLabel=
|
|
97
|
-
`,{mode:384}),
|
|
98
|
-
`)}function
|
|
99
|
-
`)}function
|
|
89
|
+
`)}function La(e){let t=Gr(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let o=Fa(i),s=new Set;for(let c of o.matchAll(Jf)){let l=c[2],d=l.split("-")[0];if(!t.has(d)||e.tokens.has(l))continue;let u=`${c[1]}-${l}`;s.has(u)||(s.add(u),n.push({file:r,klass:u,token:l,namespace:d}))}}return n}function $a(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function ja(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Pa(e,t){let n=k(e,["ls-files","--",...t]);return n===null?[]:n.split(`
|
|
90
|
+
`).filter(Boolean)}function Br(e,t={}){let n=t.maxFileBytes??zf,r=new Set;for(let l of Pa(e,["*.css"])){let d=Ma(Na(e,l),n);if(d!==null)for(let u of Oa(d))r.add(u)}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(l=>Ca.map(d=>`${l.replace(/\/+$/,"")}/**/${d}`)):Ca,o=[];for(let l of Pa(e,i)){if(!ja(l))continue;let d=Ma(Na(e,l),n);d!==null&&o.push({path:l,content:d})}let s=La({tokens:r,sources:o}),c=$a(r.size,s.length);return{ok:c==="clean",verdict:c,tokenCount:r.size,namespaceCount:Gr(r).size,findings:s,scannedFiles:o.length}}function Ma(e,t){try{let n=Vf(e,"utf8");return n.length>t?null:n}catch{return null}}var Da,qf,Jf,Ca,zf,Ha=w(()=>{"use strict";V();Da=["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"],qf=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,Jf=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Da.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");a(Oa,"extractTokens");a(Gr,"deriveNamespaces");a(Fa,"stripCommentLines");a(La,"evaluateThemeClasses");a($a,"deriveThemeClassVerdict");Ca=["*.ts","*.tsx","*.js","*.jsx"],zf=15e5;a(ja,"isScannableSource");a(Pa,"listTracked");a(Br,"checkThemeClassDrift");a(Ma,"safeRead")});import{posix as Ua}from"node:path";function je(e){let t=Yf.exec(e);return t?t[1]:null}function oe(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function vt(e,t){let n=k(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=a(o=>!t||t.length===0?!0:t.some(s=>{let c=s.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 s=Ua.basename(o),c=je(s);if(c===null)continue;let l=Ua.dirname(o),d=i.get(l)??[];d.push({path:o,name:s,version:c}),i.set(l,d)}return[...i.entries()].map(([o,s])=>({dir:o,files:s.sort((c,l)=>oe(c.version,l.version))})).sort((o,s)=>o.dir.localeCompare(s.dir))}function Ka(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 Yf,Sn=w(()=>{"use strict";V();Yf=/^(\d+)_.+\.sql$/;a(je,"parseMigrationVersion");a(oe,"compareVersions");a(vt,"discoverSupabaseProjects");a(Ka,"resolveDefaultBranch")});import{readFileSync as Xf}from"node:fs";import{join as Qf,posix as Zf}from"node:path";function Ga(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]!==`
|
|
91
|
+
`;)n++;continue}if(i==="/"&&o==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let s=(i==="E"||i==="e")&&o==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||s){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 fe(e){let t=[],n="",r=!1,i=!1,o=a(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){o();continue}n+=l}o();let s=t.filter(c=>c.length>0);return s.length===0||s.length>2?null:s.length===2?{schema:s[0],name:s[1]}:{schema:"public",name:s[0]}}function St(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 Ba(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 s=i.trim();if(em.test(s))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(s);if(l){if(!St(l[1]).map(f=>fe(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=s.replace(/^TABLE\s+/i,""),f=St(p).map(h=>fe(h)).filter(h=>h!==null).filter(h=>h.schema==="public").map(h=>h.name);if(f.length===0)return null;c=f}let d=St(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>fe(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of St(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:d,writePrivs:[...Wr]};!m&&Wr.includes(h)&&u.push(h)}return{tables:c,roles:d,writePrivs:u}}function qr(e){let t=new Map,n=[...e].sort((r,i)=>oe(r.version,i.version));for(let r of n){let i=Ga(r.content);for(let o of i.split(";")){let s=o.trim();if(!s)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(s);if(c){if(/\bTEMP(?:ORARY)?\b/i.test(c[1]??""))continue;let u=fe(c[2]);if(!u||u.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(s)&&t.has(u.name))continue;t.set(u.name,{createdIn:r.version,anonAddressed:!1,authWritesRevoked:new Set});continue}let l=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(s);if(l){let u=l[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let p of St(u)){let f=fe(p);f&&f.schema==="public"&&t.delete(f.name)}continue}let d=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(s);if(d){let u=fe(d[1]),p=fe(d[2]);if(u&&p&&u.schema==="public"){let f=t.get(u.name);f&&(t.delete(u.name),t.set(p.name,f))}continue}if(/^REVOKE\b/i.test(s)){let u=Ba(s);if(!u)continue;let p=u.tables==="all_in_public"?[...t.keys()]:u.tables,f=u.roles.includes("anon"),h=u.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 b of u.writePrivs)g.authWritesRevoked.add(b)}continue}}}return t}function Vr(e){let t=[];for(let[n,r]of qr(e)){let i=[];r.anonAddressed||i.push("anon"),Wr.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 Wa(e){let t=Vr(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Vr(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),s=i!=null&&r.missing.every(l=>i.has(l))?"info":"open",c=r.missing.map(l=>l==="anon"?"kein Tabellen-REVOKE nennt anon":"authenticated beh\xE4lt Schreibrechte (kumulierte REVOKEs decken INSERT/UPDATE/DELETE nicht)").join("; ");return{id:`table.acl:${e.dir}#${r.table}`,status:s,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 Va(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function nm(e,t){try{let n=Xf(e,"utf8");return n.length>t?null:n}catch{return null}}function rm(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 s=new Set,c=[];for(let u of o.split(`
|
|
92
|
+
`).filter(Boolean)){let[p,...f]=u.split(" ");p.startsWith("A")?s.add(f[0]):p.startsWith("R")?(c.push(f[0]),s.add(f[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(f[0])}let l=[],d=new Set(c);for(let{ref:u,content:p}of n)!s.has(u.path)&&!d.has(u.path)&&l.push({name:u.name,version:u.version,content:p});for(let u of c){let p=Zf.basename(u),f=je(p);if(f===null)continue;let h=k(e,["show",`${r}:${u}`]);if(h===null)return i.push(`could not read ${u} at ${r} \u2014 baseline degraded`),null;l.push({name:p,version:f,content:h})}return l}function Jr(e,t={}){let n=t.maxFileBytes??tm,r=[],i=vt(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,s=null;if(o)if(t.baseRef)s=t.baseRef;else{let f=Ka(e);s=f?`origin/${f}`:null,s===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=[],l=[];for(let f of i){let h=[];for(let b of f.files){let y=nm(Qf(e,b.path),n);if(y===null){r.push(`could not read ${b.path} \u2014 excluded from the fold`);continue}h.push({ref:b,content:y})}let m=h.map(({ref:b,content:y})=>({name:b.name,version:b.version,content:y})),g=s===null?null:rm(e,f.dir,h,s,r);c.push(...Wa({dir:f.dir,files:m,baseFiles:g})),l.push({dir:f.dir,migrationCount:m.length,tableCount:qr(m).size})}let d=l.reduce((f,h)=>f+h.migrationCount,0),u=Va(d,c.length),p={open:0,info:1};return c.sort((f,h)=>p[f.status]-p[h.status]||f.id.localeCompare(h.id)),{ok:u!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:s,skipped:r}}}var Wr,em,tm,qa=w(()=>{"use strict";V();Sn();a(Ga,"stripSql");a(fe,"normalizeQualifiedIdent");a(St,"splitTopLevel");Wr=["INSERT","UPDATE","DELETE"],em=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;a(Ba,"parseTableRevoke");a(qr,"foldTableAcl");a(Vr,"evaluateTableAcl");a(Wa,"computeTableAclFindings");a(Va,"deriveTableAclVerdict");tm=5e6;a(nm,"safeRead");a(rm,"baseFilesFor");a(Jr,"checkTableAclLint")});import{existsSync as zr,readdirSync as im,readFileSync as om}from"node:fs";import{spawnSync as sm}from"node:child_process";import{dirname as am,join as Yr,posix as cm}from"node:path";function za(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 ${Xr} 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 ${Xr} 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),s=e.fileVersions.filter(p=>!i.has(p)).sort(oe);s.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${s.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${s.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:s});let c=r.versions.filter(p=>!o.has(p)).sort(oe),l=new Map,d=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let h=l.get(f)??[];h.push(p),l.set(f,h)}else d.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.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: ${d.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:d}),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(oe),h=e.remote.versions.filter(m=>!o.has(m)).sort(oe);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 u=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function Ya(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Qa(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(`
|
|
93
|
+
`).filter(Boolean).slice(-1)[0]}}function Ja(e,t,n){let r=e(t,lm,n);return r.ok===!1?Qa(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
|
|
94
|
+
`).map(i=>i.trim()).filter(Boolean)}}function Za(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 dm(e){let t=k(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=am(t);return n===e?null:n}function um(e,t,n){let r=cm.dirname(t),o=[{path:Yr(e,r,"config.toml"),source:"worktree"}],s=dm(e);s&&o.push({path:Yr(s,r,"config.toml"),source:"main_worktree"});for(let c of o)if(zr(c.path))try{let l=Za(om(c.path,"utf8"));if(l===null){n.push(`${c.path}: kein [db].port lesbar \u2014 Kandidat \xFCbersprungen`);continue}return{source:c.source,port:l}}catch{n.push(`${c.path}: nicht lesbar \u2014 Kandidat \xFCbersprungen`)}return{source:"missing"}}function pm(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(`
|
|
95
|
+
`)){if(!o.startsWith("worktree "))continue;let s=o.slice(9).trim();if(!s||s===i||!zr(s))continue;let c=Yr(s,t);if(zr(c))try{for(let l of im(c)){let d=je(l);d!==null&&!n.has(d)&&n.set(d,s)}}catch{}}return n}function Qr(e,t={}){let n=t.runPsql??Xa,r=t.timeoutMs??15e3,i=[],o=vt(e,t.dirs);if(o.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let s=[],c=[],l=[];for(let p of o){let f=um(e,p.dir,i),h=f.source==="missing"?null:Ja(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),m=t.remoteDbUrl!==void 0?Ja(n,t.remoteDbUrl,r):null,g=za({dir:p.dir,fileVersions:p.files.map(b=>b.version),config:f,ledger:h,siblingVersions:pm(e,p.dir),remote:m});s.push(...g.findings),l.push(g.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:g.verdict,db:g.db})}let d=Ya(l),u={open:0,warn:1,info:2};return s.sort((p,f)=>u[p.status]-u[f.status]||p.id.localeCompare(f.id)),{ok:d==="in_sync",verdict:d,findings:s,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var Xr,Xa,lm,ec=w(()=>{"use strict";V();Sn();Xr=54322;a(za,"evaluateLedgerProject");a(Ya,"deriveLedgerVerdict");Xa=a((e,t,n)=>{let r=sm("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"),lm="select version from supabase_migrations.schema_migrations order by version";a(Qa,"classifyLedgerError");a(Ja,"readLedger");a(Za,"parseDbPort");a(dm,"mainWorktreeRoot");a(um,"resolveConfig");a(pm,"gatherSiblingVersions");a(Qr,"checkMigrationLedgerDrift")});var tc,Zr=w(()=>{"use strict";Ia();Ur();mr();Dr();vr();br();Tr();Ha();Mr();Sn();qa();ec();Qt();dr();bt();tc="0.1.0"});import{execFile as km}from"node:child_process";import{randomUUID as vm}from"node:crypto";function Tm(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return ti.test(t)?t:vm()}function ni(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function Im(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 Nm(){return await new Promise(e=>{km("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 Cm(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function Pm(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=ti.test(r)&&r===t?"env":"random";return{current:a(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:a(()=>!1,"tryUpgrade"),adopt:a(o=>{ti.test(o)&&(n=o.trim().toLowerCase())},"adopt"),activityAtMs:a(()=>null,"activityAtMs")}}var cc,lc,Sm,Em,xm,Rm,Am,ti,Rn,ri=w(()=>{"use strict";Me();cc=45e3,lc=3e4,Sm=5,Em=120,xm=3e4,Rm=15*6e4,Am=1500,ti=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;a(Tm,"resolveClientSessionId");a(ni,"autoAnnounceDisabled");a(Im,"autoWorkingPathsEnabled");Rn=class{static{a(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;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??Q)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??Nm,this.log=t.log??(i=>process.stderr.write(i+`
|
|
96
|
+
`)),this.machineLabel=Cm(r?.machine_label),this.enabled=this.projectKey!==null&&!ni(n,r),this.workingPathsEnabled=Im(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??Pm(n,Tm(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<cc||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<cc||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<Sm||(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,Am).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(xm*2**(this.consecutiveFailures-1),Rm);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:Em,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,this.machineLabel&&(r.machine_label=this.machineLabel),this.workingPathsEnabled&&this.deriveWorkingPaths)try{let s=await this.deriveWorkingPaths();s&&s.length>0&&(r.working_paths=s)}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},s=typeof i=="object"?i:null;if(s!==null&&s.ok===!0)this.snapshot.write(i,o);else if(this.snapshot.markFailed){let c=s!==null&&typeof s.error=="string"?s.error:"announce_failed";this.snapshot.markFailed(c,o)}}}catch{}}};a(Nm,"defaultGitBranch");a(Cm,"normalizeMachineLabel");a(Pm,"staticIdentity")});import{mkdirSync as dc,readdirSync as mc,readFileSync as Mm,renameSync as uc,statSync as Dm,unlinkSync as hc,writeFileSync as pc}from"node:fs";import{homedir as Om}from"node:os";import{join as He}from"node:path";function gc(){return He(Om(),".maind","presence")}function yc(e,t){return He(e,t)}function bc(e){let t=e.baseDir??gc(),n=yc(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,o=e.cwd??process.cwd(),s=e.now??Date.now,c=null;return{write(l,d){try{if(typeof l!="object"||l===null)return;let u=l;if(u.ok!==!0)return;let p={v:1,written_at:new Date(s()).toISOString(),project_key:e.projectKey,own_session_id:d.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:d.branch,peers:Array.isArray(u.peers)?u.peers:[],conflicts:Array.isArray(u.conflicts)?u.conflicts:[]};dc(n,{recursive:!0,mode:448}),c=He(n,`${d.sessionId}.json`);let f=`${c}.tmp-${r}`;pc(f,JSON.stringify(p),{mode:384}),uc(f,c),fc(n,s(),c)}catch{}},endSession(){try{c&&hc(c)}catch{}},markFailed(l,d){try{let u={v:1,written_at:new Date(s()).toISOString(),project_key:e.projectKey,own_session_id:d.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:d.branch,peers:[],conflicts:[],announce_error:l};dc(n,{recursive:!0,mode:448}),c=He(n,`${d.sessionId}.json`);let p=`${c}.tmp-${r}`;pc(p,JSON.stringify(u),{mode:384}),uc(p,c),fc(n,s(),c)}catch{}}}}function fc(e,t,n){try{for(let r of mc(e)){if(!r.endsWith(".json"))continue;let i=He(e,r);if(i!==n)try{t-Dm(i).mtimeMs>Fm&&hc(i)}catch{}}}catch{}}function Ue(e,t=gc()){try{let n=yc(t,e),r=[];for(let i of mc(n))if(i.endsWith(".json"))try{let o=JSON.parse(Mm(He(n,i),"utf8")),s=Lm(o);s&&r.push(s)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function Lm(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 Fm,An=w(()=>{"use strict";Fm=120*6e4;a(gc,"presenceSnapshotBaseDir");a(yc,"projectDir");a(bc,"createSnapshotStore");a(fc,"pruneStale");a(Ue,"readSnapshots");a(Lm,"parseSnapshot")});import{execFileSync as $m}from"node:child_process";import{createHash as jm,randomUUID as Hm}from"node:crypto";import{existsSync as Um,mkdirSync as Km,readdirSync as Gm,readFileSync as Bm,renameSync as Wm,statSync as ii,unlinkSync as _c,writeFileSync as Vm}from"node:fs";import{homedir as qm}from"node:os";import{basename as Jm,join as me}from"node:path";function Ke(e){return me(e??me(qm(),".maind","presence"),"identity")}function kc(e,t){if(e){let n=Jm(e).replace(/\.jsonl$/i,"");if(Et.test(n))return n.toLowerCase()}return t&&Et.test(t)?t.toLowerCase():null}function vc(e){let t=e.nowMs??Date.now();Km(e.dir,{recursive:!0,mode:448});let n=me(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()};Vm(r,JSON.stringify(i,null,2)+`
|
|
97
|
+
`,{mode:384}),Wm(r,n),Zm(e.dir,t)}function Sc(e,t,n,r=Date.now()){try{let i=ii(me(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function Ec(e,t){try{_c(me(e,`${t}.json`))}catch{}}function Zm(e,t){try{for(let n of Gm(e))if(n.endsWith(".json"))try{let r=ii(me(e,n));t-r.mtimeMs>Ym&&_c(me(e,n))}catch{}}catch{}}function eh(e){return xc(e)?.file??null}function xc(e){let t=me(e.dir,`${e.agentPid}.json`);try{if(!Um(t))return null;let n=ii(t);if(n.mtimeMs<e.bridgeStartMs-Xm)return null;let r=JSON.parse(Bm(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Et.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!th(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function wc(e){return e.replace(/\/+$/,"")}function th(e,t){let n=wc(e),r=wc(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function nh(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=jm("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 rh(e){if(process.platform==="win32")return null;try{let t=$m("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function ih(){try{return F()}catch{return null}}var Et,zm,Ym,Xm,Qm,Tn,In=w(()=>{"use strict";U();Et=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,zm=8,Ym=48*60*6e4,Xm=6e4,Qm="9f3c72da-2f10-4b8f-9c31-ad291c0de291";a(Ke,"identityDirPath");a(kc,"transcriptStemOf");a(vc,"writeAgentIdentityFile");a(Sc,"identityFileStale");a(Ec,"deleteAgentIdentityFile");a(Zm,"pruneIdentityDir");a(eh,"readAgentIdentityFile");a(xc,"readAgentIdentityEntry");a(wc,"normDir");a(th,"sameSessionTree");a(nh,"uuidV5");a(rh,"processStartTime");Tn=class{static{a(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??Ke(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Et.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??ih)(),o=(t.ppidStart??rh)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=nh(`${i}|${this.agentPid}|${o}|${t.projectKey}`,Qm),this.source="derived";return}this.id=Hm(),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(!Et.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>zm&&this.aliases.shift())}activityAtMs(){return xc({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let t=eh({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()});return t===null?null:t.transcript_stem.toLowerCase()}};a(ih,"defaultDeviceId")});var oi=w(()=>{"use strict"});import{createReadStream as uh,existsSync as ph}from"node:fs";import{stat as fh}from"node:fs/promises";import{createInterface as mh}from"node:readline";async function si(e){if(!e||!ph(e))return null;let t;try{t=await fh(e)}catch{return null}let n=0,r=0,i=0;return await new Promise(o=>{let s=uh(e,{encoding:"utf-8"}),c=mh({input:s});c.on("line",l=>{let d=l.trim();if(d){i++;try{let p=JSON.parse(d).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)),s.on("error",()=>o(null))})}var Ac=w(()=>{"use strict";a(si,"summariseTranscript")});var Tc=w(()=>{"use strict"});function Nn(e){if(!e)return null;let t=null;for(let n of e.matchAll(gh)){let r=n[1].toLowerCase();hh.has(r)&&(t=r)}return t}var hh,gh,Cn=w(()=>{"use strict";hh=new Set(["low","medium","high","xhigh","max"]),gh=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;a(Nn,"detectEffortLevel")});import{createReadStream as yh,existsSync as bh}from"node:fs";import{createInterface as wh}from"node:readline";function xt(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Ah(e,t,n,r,i){let o=`${n?"s":"m"}:${t}`,s=e.get(o);if(!s){e.set(o,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}s.turns++,s.output_tokens+=r,i>0&&((s.first_ts===0||i<s.first_ts)&&(s.first_ts=i),i>s.last_ts&&(s.last_ts=i))}function ai(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function Th(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
98
|
+
`)}function Ih(e,t){let n=a(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(d=>d.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[o,s]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of o)s.has(l)&&c++;return c/o.size>=.8}function Nh(e,t,n){return _h.test(e)?{polarity:-1,magnitude:Ge.rework,kind:"rework"}:n&&kh.test(e)?{polarity:-1,magnitude:Ge.correction,kind:"correction"}:vh.test(e)?{polarity:1,magnitude:Ge.acceptance,kind:"acceptance"}:t!==null&&Ih(t,e)?{polarity:-1,magnitude:Ge.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function Ch(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:Nc}}async function ci(e){let t=Ch("");if(!e||!bh(e))return t;let n=[],r=new Map,i=null,o=!1,s=null;await new Promise(p=>{let f=yh(e,{encoding:"utf-8"}),h=wh({input:f}),m=a(g=>{let b=g.trim();if(!b)return;let y;try{y=JSON.parse(b)}catch{return}if(t.lines_seen++,!t.session_id){let R=y.sessionId??y.session_id;typeof R=="string"&&R&&(t.session_id=R)}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+=xt(v.input_tokens),t.output_tokens+=xt(v.output_tokens),t.cache_read_tokens+=xt(v.cache_read_input_tokens),t.cache_creation_tokens+=xt(v.cache_creation_input_tokens)),_==="assistant"&&typeof y.message?.model=="string"&&y.message.model&&y.message.model!==xh){let R=y.timestamp?Date.parse(y.timestamp):Number.NaN;Ah(r,y.message.model,S,xt(v?.output_tokens),Number.isFinite(R)?R:0)}if(_==="assistant")for(let R of ai(y.message?.content)){if(R.type!=="tool_use"||typeof R.name!="string"||!R.name.startsWith(Ic))continue;let ce=R.name.slice(Ic.length);ce&&(t.maind_tool_calls[ce]=(t.maind_tool_calls[ce]??0)+1)}if(S)return;if(_==="assistant"){t.assistant_turns++;let R=ai(y.message?.content),ce=!1;for(let Fi of R)Fi.type==="tool_use"&&(t.tool_calls++,ce=!0,Fi.name==="AskUserQuestion"&&t.agent_questions++);o=ce;return}if(_!=="user")return;let E=ai(y.message?.content),x=Th(E);if(x.includes(Sh)){t.interrupts++,n.push({polarity:-1,magnitude:Ge.interrupt,kind:"interrupt"});return}if(E.some(R=>R.type==="tool_result"&&R.is_error===!0&&typeof R.content=="string"&&R.content.includes(Eh))){t.tool_denials++,n.push({polarity:-1,magnitude:Ge.denial,kind:"denial"});return}if(E.some(R=>R.type==="tool_result")||!x.trim())return;t.user_turns++,t.user_chars+=x.length;let A=Nn(x);A&&(i=A);let H=Nh(x,s,o);s=x,H.kind==="correction"?t.corrections++:H.kind==="rework"?t.reworks++:H.kind==="repeat"?t.repeated_instructions++:H.kind==="acceptance"&&t.acceptances++,H.polarity!==0&&n.push(H),o=!1},"processLine");h.on("line",g=>{try{m(g)}catch{}}),h.on("close",()=>p()),h.on("error",()=>p()),f.on("error",()=>p())}),t.effort_at_end=i,t.model_mix=[...r.values()].sort((p,f)=>p.first_ts-f.first_ts||p.model.localeCompare(f.model)),t.user_token_estimate=Math.round(t.user_chars/4);let c=t.user_token_estimate+t.output_tokens;t.human_share=c>0?Number((t.user_token_estimate/c).toFixed(4)):0;let l=0,d=0,u=[];return n.forEach((p,f)=>{p.polarity>0?t.reactions_pos++:p.polarity<0&&t.reactions_neg++,l=l*Rh+p.polarity*p.magnitude;let h=Number(l.toFixed(3));u.push({t:f,value:h,...p.kind!=="neutral"?{kind:p.kind}:{}}),d+=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=u,t.momentum_final=u.length?u[u.length-1].value:0,t.momentum_auc=Number(d.toFixed(3)),t.ended_positive=t.momentum_final>0,Object.keys(t.maind_tool_calls).length>0&&(t.maind_connected="connected"),t}var Ic,Nc,_h,kh,vh,Sh,Eh,xh,Rh,Ge,Cc=w(()=>{"use strict";Cn();Ic="mcp__maind__",Nc="2026-08-16",_h=/(\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,kh=/(\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,vh=/(\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,Sh="[Request interrupted by user",Eh="The user doesn't want to proceed with this tool use",xh="<synthetic>",Rh=.7,Ge={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};a(xt,"num");a(Ah,"bumpModel");a(ai,"asBlocks");a(Th,"textOf");a(Ih,"isRepeat");a(Nh,"classifyGenuine");a(Ch,"emptyAnalysis");a(ci,"analyzeSession")});function li(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 Pc=w(()=>{"use strict";a(li,"ingestBody")});import{createReadStream as Ph,existsSync as Mh}from"node:fs";import{createInterface as Dh}from"node:readline";function Mc(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function Lh(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
99
|
+
`)}function Fc(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 $h(e){let t=e.message?.role;if(t==="assistant")return{holder:Mc(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Mc(e.message?.content),r=Lh(n);return r.includes(Oh)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes(Fh))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function di(e){let t=Fc("");if(!e||!Mh(e))return t;let n=null,r=0,i=0,o=null,s="human",c=[];return await new Promise(l=>{let d=Ph(e,{encoding:"utf-8"}),u=Dh({input:d}),p=a(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 b=$h(m);if(b!==null){if(t.event_count++,b.genuine&&t.turn_count++,n===null&&(n=g),r=g,o!==null){let y=g-o;s==="agent"?i+=y:y>=Dc*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(y/1e3),c.length<Oc&&c.push({offset_seconds:Math.round((o-n)/1e3),duration_seconds:Math.round(y/1e3)}))}o=g,s=b.holder}},"processLine");u.on("line",f=>{try{p(f)}catch{}}),u.on("close",()=>l()),u.on("error",()=>l()),d.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var Oh,Fh,Dc,Oc,Lc=w(()=>{"use strict";Oh="[Request interrupted by user",Fh="The user doesn't want to proceed with this tool use",Dc=60,Oc=200;a(Mc,"asBlocks");a(Lh,"textOf");a(Fc,"emptySpan");a($h,"classify");a(di,"analyzeSpan")});var $c=w(()=>{"use strict";Cn();oi()});var jc=w(()=>{"use strict"});import{homedir as jh}from"node:os";import{join as Hh}from"node:path";var Uh,Kh,Hc=w(()=>{"use strict";Uh=jh(),Kh=Hh(Uh,".claude","projects")});var ui=w(()=>{"use strict";oi();Ac();Tc();Cc();Pc();Lc();$c();Cn();jc();Hc()});function Gh(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":F()}}async function Uc(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:Gh(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 Pn,pi=w(()=>{"use strict";U();Pn=process.env.MAIND_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";a(Gh,"ingestHeaders");a(Uc,"postMetrics")});function Kc(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function Bc(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:[],s=[];for(let c of o){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let u=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;u<=0||s.push({path_prefix:l.path_prefix,note:typeof l.note=="string"?l.note:null,remaining_seconds:Math.round(u)})}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:s,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function Be(e,t){if(t.grandparentPid!==null){let r=e.find(i=>i.own_ppid===t.grandparentPid);if(r)return{snap:r,via:"ppid"}}let n=e.find(r=>r.cwd===t.cwd);return n?{snap:n,via:"cwd"}:null}function Rt(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function Wc(e,t,n){let r=n.maxAgeMs??Gc,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,s=Bc(e,o),c=[];for(let l of s)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let d of l.claims)Kc(t,d.path_prefix)&&c.push(`'${d.path_prefix}' is CLAIMED by peer session ${l.session_id_short}${l.branch?` (branch ${l.branch}`:" ("}${l.machine_label?`, ${l.machine_label}`:""}${l.focus?`, focus: "${l.focus}"`:""}, last seen ${Rt(l.last_seen_seconds+o)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${Rt(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(Kc(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${Rt(l.last_seen_seconds+o)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${Rt(o)} ago, advisory \u2014 never a lock):
|
|
100
100
|
`+c.map(l=>` \u2022 ${l}`).join(`
|
|
101
101
|
`)+`
|
|
102
|
-
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
|
|
103
|
-
${
|
|
104
|
-
`),
|
|
105
|
-
`)}}catch{}try{let r=at(
|
|
106
|
-
`)}}catch{}return 0}function
|
|
102
|
+
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 Vc(e,t,n,r=Gc,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 s=o/1e3,c=Bc(e,s),l=i!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${i}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let d=c.reduce((m,g)=>m+g.claims.length,0),u=c.filter(m=>m.focus===null&&m.working_paths.length===0&&m.claims.length===0).length,p=d>0?`${d} active claim${d===1?"":"s"}`:"no active claims",f=u>0?`, ${u} presence-only`:"",h=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${Rt(s)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
|
|
103
|
+
${h}`:h}var Gc,fi=w(()=>{"use strict";a(Kc,"prefixConflict");Gc=10*6e4;a(Bc,"parsePeers");a(Be,"selectOwnSnapshot");a(Rt,"ageDisplay");a(Wc,"adviseOnPath");a(Vc,"sessionStartSummary")});async function O(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=a(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 Mn(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function We(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var Ee=w(()=>{"use strict";a(O,"readHookInput");a(Mn,"transcriptPathOf");a(We,"toolFilePathOf")});function Ve(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function qe(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}var Dn=w(()=>{"use strict";a(Ve,"denyPayload");a(qe,"advisoryPayload")});import{mkdir as Bh,readFile as Wh,writeFile as Vh,rename as qh}from"node:fs/promises";import{existsSync as Jc}from"node:fs";import{homedir as Jh}from"node:os";import{join as zc}from"node:path";function qc(){return{config:null,sessions:{},pending_metrics:[]}}async function K(){if(!Jc(On))return qc();try{let e=await Wh(On,"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}}catch(e){return process.stderr.write(`[maind-mcp-bridge] state.json corrupt, resetting: ${e instanceof Error?e.message:String(e)}
|
|
104
|
+
`),qc()}}async function Je(e){Jc(xe)||await Bh(xe,{recursive:!0,mode:448});let t=`${On}.tmp`;await Vh(t,JSON.stringify(e,null,2),{mode:384}),await qh(t,On)}function mi(e){return e.thresholds??e.config?.thresholds??zh}var xe,On,zh,At=w(()=>{"use strict";xe=zc(Jh(),".maind"),On=zc(xe,"state.json"),zh={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};a(qc,"emptyState");a(K,"loadState");a(Je,"saveState");a(mi,"resolveThresholds")});var pl={};J(pl,{closeTrackedSession:()=>sl,effectiveConfig:()=>Re,grandparentPid:()=>se,recordGuardSignals:()=>ol,runFlush:()=>dg,runHookStatus:()=>ug,runOnFileEdit:()=>ag,runOnFileWrite:()=>sg,runOnSessionStart:()=>tg,runOnToolUse:()=>ig,runSessionEndMetrics:()=>hi,runSyncConfig:()=>fg});import{execFileSync as el}from"node:child_process";import{existsSync as Ln,readFileSync as tl,realpathSync as nl}from"node:fs";import{writeFile as Yh}from"node:fs/promises";import{homedir as rl}from"node:os";import{basename as Yc,dirname as Xc,isAbsolute as Fn,join as ze,relative as il}from"node:path";function ol(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 s=e.guard_signals??{},c=s[t]??{},l=new Date(r).toISOString();i&&(c.consulted_at=l),o&&(c.reviewed_at=l),s[t]=c,e.guard_signals=s}function sl(e,t,n=Date.now()){eg(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 eg(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>Qc&&delete e.guard_signals[n]}for(let[n,r]of Object.entries(e.sessions)){let i=Date.parse(r.started_at);!Number.isNaN(i)&&t-i>Qc&&delete e.sessions[n]}}function Re(e){if(e.config)return e.config;let t=I();return t===null?null:{api_key:t,endpoint:Pn}}function al(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 tg(){let e=await K();if(Re(e)===null)return 0;let t=await O(),n=ul(t);if(n===null)return 0;al(e,n),await Je(e);try{cl(t,n)}catch{}try{let r=D();if(r!==null){let i=Ue(r),o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),s=Be(i,{grandparentPid:se(),cwd:o}),c=Vc(s?.snap??i[0]??null,s?.snap.own_session_id??null,Date.now(),void 0,s?.snap.announce_error??null);c!==null&&process.stdout.write(c+`
|
|
105
|
+
`)}}catch{}try{let r=at(ng());if(tr(r)&&Jt(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).
|
|
106
|
+
`)}}catch{}return 0}function ng(){try{let e=ze(rl(),".claude","settings.json");return Ln(e)?tl(e,"utf8"):null}catch{return null}}function cl(e,t,n){let r=n??se();if(r==null)return;let i=kc(Mn(e)||null,t);i!==null&&vc({dir:Ke(),agentPid:r,sessionId:t,transcriptStem:i,cwd:typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd()})}function se(){try{if(process.platform==="win32")return null;let e=el("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}}async function ig(){let e=await K();if(Re(e)===null)return 0;let t=await O(),n=ul(t)??"unknown",r=al(e,n);r.tool_call_count+=1;try{let s=se();n!=="unknown"&&s!==null&&Sc(Ke(),s,rg)&&cl(t,n,s)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),ol(e,n,i);let o=t.transcript_path;if(typeof o=="string"&&o&&!r.transcript_path&&(r.transcript_path=o),r.transcript_path){let s=await si(r.transcript_path);s&&(r.token_count=s.total_tokens,await lg(e,r))}return await Je(e),0}function ll(e){let t=Xc(e),n=[Yc(e)];for(;;)try{let r=nl(t);return ze(r,...n.reverse())}catch{let r=Xc(t);if(r===t)return e;n.push(Yc(t)),t=r}}function og(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
|
|
107
107
|
`);return`${t.prefix}${e.number} is already taken:
|
|
108
108
|
${n}
|
|
109
109
|
|
|
110
110
|
Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
|
|
111
111
|
|
|
112
|
-
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
|
|
112
|
+
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 sg(){try{let e=await O();if((e.tool_name??"")!=="Write")return 0;let t=We(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=Fn(t)?t:ze(n,t);if(Ln(r))return 0;let i=tt(n),o=il(i,ll(r));if(o.length===0||o.startsWith("..")||Fn(o))return 0;let s=await ke(i,o);return!s.taken||s.namespace===null||process.stdout.write(Ve(og(s,s.namespace))),0}catch{return 0}}async function ag(){try{let e=await O(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=We(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=Fn(n)?n:ze(r,n),o=D();if(o===null)return 0;let s=Ue(o);if(s.length===0)return 0;let c=Be(s,{grandparentPid:se(),cwd:r});if(c===null)return 0;let l=tt(r),d=Ln(i)?nl(i):ll(i),u=il(l,d).replace(/\\/g,"/");if(u.length===0||u.startsWith("..")||Fn(u))return 0;let p=Wc(c.snap,u,{via:c.via,currentBranch:c.via==="cwd"?cg(r):null,nowMs:Date.now()});return p===null||process.stdout.write(qe(p)),0}catch{return 0}}function cg(e){try{let n=el("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 lg(e,t){let n=mi(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 s=Math.round(i*100),c={session_id:t.session_id,status:o,tokens:r,ratio:Number(i.toFixed(3)),pct:s,thresholds:n,suggested_next:o==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await Yh(ze(xe,`handoff_advisory_${t.session_id}.json`),JSON.stringify(c,null,2))}catch(l){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${l instanceof Error?l.message:String(l)}
|
|
113
113
|
`)}o==="warn"?process.stderr.write(`[maind] \u26A0 Token usage at ~${s}% (warn threshold ${n.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
|
|
114
114
|
`):process.stderr.write(`[maind] \u26D4 Token usage at ~${s}% (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.
|
|
115
|
-
`)}async function hi(e){try{let t=await K(),n=Re(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(
|
|
116
|
-
`)}}async function
|
|
117
|
-
`),n.ok?0:1}async function
|
|
115
|
+
`)}async function hi(e){try{let t=await K(),n=Re(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(sl(t,r),await Je(t)),await dl(n,Qh)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
|
|
116
|
+
`)}}async function dg(){let e=await K(),t=Re(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 dl(t,Zh);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
117
|
+
`),n.ok?0:1}async function dl(e,t){let n=await K();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=Uc(e.endpoint,e.api_key,r),o=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),s=await Promise.race([i,o]);if(s.ok){let c=await K();return c.pending_metrics=c.pending_metrics.slice(r.length),await Je(c),{ok:!0,flushed:r.length,remaining:c.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:s.error}}async function ug(){let e=await K(),t=Re(e),n=pg(),r=tr(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:mi(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})),...Jt(n.findings)?{remedy:Zc}:{}}},null,2)+`
|
|
118
118
|
`),r){process.stderr.write(`
|
|
119
119
|
[maind] Claude Code hook wiring is incomplete:
|
|
120
120
|
`);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
|
|
121
|
-
`);Jt(n.findings)&&process.stderr.write(` ${
|
|
122
|
-
`)}return 0}function
|
|
121
|
+
`);Jt(n.findings)&&process.stderr.write(` ${Zc}
|
|
122
|
+
`)}return 0}function pg(){let e=ze(rl(),".claude","settings.json"),t=null;try{Ln(e)&&(t=tl(e,"utf8"))}catch{}return{settingsPath:e,findings:at(t)}}async function fg(){let e=await K(),t=Re(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??Xh,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(s){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${s instanceof Error?s.message:String(s)}
|
|
123
123
|
`),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
|
|
124
124
|
`);let s=await r.text().catch(()=>"");return s&&process.stderr.write(s.slice(0,500)+`
|
|
125
125
|
`),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
|
|
126
126
|
`),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
|
|
127
127
|
`),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 Je(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
|
|
128
|
-
`),0)}function
|
|
129
|
-
`)}return await hi(n),0}var
|
|
130
|
-
`,384)}var
|
|
128
|
+
`),0)}function ul(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var Xh,Qh,Zh,Qc,rg,Zc,gi=w(()=>{"use strict";ui();Zr();Ot();U();ct();An();le();pi();fi();In();Ee();Dn();At();Xh=process.env.MAIND_THRESHOLDS_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds",Qh=1500,Zh=1e4,Qc=7*24*60*60*1e3;a(ol,"recordGuardSignals");a(sl,"closeTrackedSession");a(eg,"gcState");a(Re,"effectiveConfig");a(al,"getOrCreateSession");a(tg,"runOnSessionStart");a(ng,"readSettingsRaw");a(cl,"writeIdentitySideChannel");rg=6e4;a(se,"grandparentPid");a(ig,"runOnToolUse");a(ll,"realpathOfUnwritten");a(og,"denyReason");a(sg,"runOnFileWrite");a(ag,"runOnFileEdit");a(cg,"currentGitBranch");a(lg,"maybeEmitAdvisory");a(hi,"runSessionEndMetrics");a(dg,"runFlush");a(dl,"flushPending");a(ug,"runHookStatus");Zc="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.";a(pg,"readHookWiring");a(fg,"runSyncConfig");a(ul,"sessionIdOf")});function fl(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var ml=w(()=>{"use strict";a(fl,"resolveConnection")});var hl={};J(hl,{runOnSessionEnd:()=>bg});function hg(e,t){try{let n=D(),r=n!==null&&!ni(process.env,Q()),i=null;if(n!==null){let o=Be(Ue(n),{grandparentPid:se(),cwd:process.cwd()});if(o){let s=Date.parse(o.snap.written_at);i=Number.isFinite(s)?Math.max(0,t-s):null}}return fl({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function gg(){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=D();if(n!==null){let i=Be(Ue(n),{grandparentPid:se(),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 yg(e,t,n,r){let i=fetch(mg,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":N},body:JSON.stringify(n)}).then(()=>{}).catch(()=>{}),o=new Promise(s=>setTimeout(s,r));await Promise.race([i,o])}async function bg(){try{let i=se();i!==null&&Ec(Ke(),i)}catch{}let e=I();if(!e)return 0;let t=await O(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=Mn(t);if(r)try{let[i,o]=await Promise.all([ci(r),di(r)]);if(n&&(i.session_id=n,o.session_id=n),i.maind_connected=hg(i.maind_connected==="connected",Date.now()),i.session_id){let s=li(i,o,{client_session_id:gg(),client:"claude-code"},"live_bridge");await yg(e,F(),s,1500)}}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
|
|
129
|
+
`)}return await hi(n),0}var mg,gl=w(()=>{"use strict";ui();Me();U();pi();fi();Ee();gi();ri();An();le();In();ye();ml();mg=Pn;a(hg,"connectionVerdict");a(gg,"presenceSessionId");a(yg,"postWithTimeout");a(bg,"runOnSessionEnd")});function q(e=process.env,t=Q()){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 Ye(e,t=ne()){let n={};try{let i=await L(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 M(t,JSON.stringify(r,null,2)+`
|
|
130
|
+
`,384)}var Ae=w(()=>{"use strict";Me();ee();a(q,"resolveGuardConfig");a(Ye,"writeGuardConfig")});function wg(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 yl(e,t,n=process.stdout){let r=wg(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
|
|
131
131
|
`),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},o=[];for(let l of qt)o.push(await we(i,l));for(let l of o)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
|
|
132
132
|
`);let s=o.some(l=>l.detail==="user declined"),c=o.some(l=>l.status==="failed");return r.dryRun?(n.write(`
|
|
133
133
|
[dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
|
|
@@ -138,79 +138,79 @@ Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
|
|
|
138
138
|
check: maind-mcp-bridge guard status
|
|
139
139
|
Takes effect for NEW Claude Code sessions (hooks are read at session start).
|
|
140
140
|
`),s&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
|
|
141
|
-
`),c?1:0)}var
|
|
142
|
-
`;await
|
|
143
|
-
`);for(let l of i>0?c.slice(1):c)if(l.trim())try{let d=JSON.parse(l);typeof d.event=="string"&&d.event in t&&(t[d.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var Ze,et=w(()=>{"use strict";Qe();Ze=
|
|
141
|
+
`),c?1:0)}var bl=w(()=>{"use strict";ct();or();Ae();a(wg,"parseGuardInstallFlags");a(yl,"runGuardInstall")});import{existsSync as wl}from"node:fs";import{mkdir as _g,readFile as kg,readdir as vg,rename as Sg,stat as Eg,unlink as xg,writeFile as Rg}from"node:fs/promises";import{join as $n}from"node:path";function _l(e){return $n(Tt,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function ae(e){try{let t=_l(e);if(!wl(t))return{};let n=JSON.parse(await kg(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function B(e,t){await _g(Tt,{recursive:!0,mode:448});let n=_l(e),r=`${n}.tmp`;await Rg(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await Sg(r,n)}async function kl(e=7*24*60*60*1e3,t=Date.now()){try{if(!wl(Tt))return;for(let n of await vg(Tt)){if(!n.endsWith(".json"))continue;let r=$n(Tt,n);try{let i=await Eg(r);t-i.mtimeMs>e&&await xg(r)}catch{}}}catch{}}var Xe,Tt,Qe=w(()=>{"use strict";At();Xe=$n(xe,"guard"),Tt=$n(Xe,"sessions");a(_l,"sessionFile");a(ae,"loadGuardSession");a(B,"saveGuardSession");a(kl,"sweepOldGuardSessions")});import{existsSync as Ag}from"node:fs";import{appendFile as Tg,mkdir as Ig,open as Ng}from"node:fs/promises";import{join as Cg}from"node:path";async function G(e){try{await Ig(Xe,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
|
|
142
|
+
`;await Tg(Ze,t,{mode:384})}catch{}}async function vl(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(!Ag(Ze))return t;let n=await Ng(Ze,"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(`
|
|
143
|
+
`);for(let l of i>0?c.slice(1):c)if(l.trim())try{let d=JSON.parse(l);typeof d.event=="string"&&d.event in t&&(t[d.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var Ze,et=w(()=>{"use strict";Qe();Ze=Cg(Xe,"events.jsonl");a(G,"appendGuardEvent");a(vl,"readGuardEventCounts")});var El={};J(El,{runGuard:()=>Fg});import{existsSync as Pg,readFileSync as Mg}from"node:fs";import{homedir as Sl}from"node:os";import{join as Dg}from"node:path";async function Fg(e){let t=e[0],n=e.slice(1);switch(t){case"install":return yl(n,Sl());case"status":return $g();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
|
|
144
144
|
`),1):(await Ye({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
145
145
|
`),0)}case"off":return await Ye({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
|
|
146
146
|
`),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>
|
|
147
147
|
`),1):(await Ye({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
148
|
-
`),0)}case"skip":return
|
|
148
|
+
`),0)}case"skip":return Lg(n);default:return process.stdout.write(Og),t===void 0||t==="--help"||t==="-h"?0:1}}async function Lg(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>"
|
|
149
149
|
`),1;let r=n.trim().slice(0,500),i=await ae(t);return await B(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.
|
|
150
150
|
logged (auditable) in ${Ze}
|
|
151
|
-
`),0}async function
|
|
151
|
+
`),0}async function $g(){let e=q(),t=Dg(Sl(),".claude","settings.json"),n=null;try{Pg(t)&&(n=Mg(t,"utf8"))}catch{}let r=at(n,{},qt),i=await vl();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(s=>({event:s.event,subcommand:s.subcommand,status:s.status,detail:s.detail})),events:i,events_file:Ze},null,2)+`
|
|
152
152
|
`);let o=r.filter(s=>s.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(`
|
|
153
153
|
[maind] guard hook wiring is incomplete:
|
|
154
154
|
`);for(let s of o)process.stderr.write(` \u2022 ${s.detail}
|
|
155
|
-
`);o.some(s=>s.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var
|
|
156
|
-
`);a(
|
|
155
|
+
`);o.some(s=>s.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var Og,xl=w(()=>{"use strict";ct();Ae();bl();et();Qe();Og=["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(`
|
|
156
|
+
`);a(Fg,"runGuard");a(Lg,"runGuardSkip");a($g,"runGuardStatus")});async function Rl(e){return It("get_session_briefing",{tools:["claude-code"]},e)}async function It(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??yi,i=new AbortController,o=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let s={"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&&(s["x-maind-device-id"]=n.deviceId),n.projectKey&&(s["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:s,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:jg,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),l=c.headers.get("mcp-session-id");if(await c.text().catch(()=>""),!c.ok||!l)return null;let d={...s,"mcp-session-id":l};await fetch(r,{method:"POST",headers:d,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(g=>g.text().catch(()=>"")).catch(()=>"");let u=await fetch(r,{method:"POST",headers:d,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!u.ok)return null;let f=(u.headers.get("content-type")??"").startsWith("text/event-stream")?await Hg(u):await u.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 Hg(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o="",s=a(()=>{if(i.length===0)return;let c=i.join(`
|
|
157
157
|
`).trim();i=[],c.length>0&&(o=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
158
|
-
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){s();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return s(),o}var yi,
|
|
159
|
-
`),0):(process.stdout.write(
|
|
158
|
+
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){s();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return s(),o}var yi,jg,jn=w(()=>{"use strict";yi="https://mcp.maind.dev/mcp",jg="2025-06-18";a(Rl,"fetchSessionBriefing");a(It,"fetchToolText");a(Hg,"readSseMessage")});var Cl={};J(Cl,{BRIEFING_CACHE_FILE:()=>Tl,formatInjection:()=>Nl,resolveBriefingInjection:()=>Il,runGuardInject:()=>Yg});import{existsSync as Ug}from"node:fs";import{mkdir as Kg,readFile as Gg,rename as Bg,writeFile as Wg}from"node:fs/promises";import{dirname as Vg,join as qg}from"node:path";async function Il(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??Tl,o=n.fetcher??Rl,s=await Xg(i);if(s!==null&&r-Date.parse(s.fetched_at)<Jg&&s.project_key===e)return{text:s.text,via:"cache"};let l=await o({apiKey:t,deviceId:Zg(),projectKey:e,bridgeVersion:N,timeoutMs:zg});return l!==null?(await Qg(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:l}),{text:l,via:"fetch"}):s!==null?{text:s.text,via:"stale-cache"}:{text:null,via:"none"}}async function Yg(){try{if(q().mode==="off")return 0;let t=await O(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;await kl();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let d=await ae(n);return await B(n,{...d,carryover:!0}),0}let i=I();if(i===null)return 0;let o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),s=D(),c=await Il(s,i),l=await ae(n);return c.text===null?(await B(n,{...l,inject_failed:!0}),await G({event:"inject_fail",session_id:n,cwd:o,project_key:s??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.
|
|
159
|
+
`),0):(process.stdout.write(Nl(c.text,c.via)),await B(n,{...l,injected:!0}),await G({event:"inject_ok",session_id:n,cwd:o,project_key:s??void 0,detail:c.via}),0)}catch{return 0}}function Nl(e,t){let n=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=e;return Buffer.byteLength(r,"utf8")>Al&&(r=r.slice(0,Al)+`
|
|
160
160
|
\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:
|
|
161
161
|
|
|
162
162
|
`+r+`
|
|
163
|
-
`}async function
|
|
163
|
+
`}async function Xg(e){try{if(!Ug(e))return null;let t=JSON.parse(await Gg(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 Qg(e,t){try{await Kg(Vg(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await Wg(n,JSON.stringify(t,null,2),{mode:384}),await Bg(n,e)}catch{}}function Zg(){try{return F()}catch{return null}}var Tl,Jg,zg,Al,Pl=w(()=>{"use strict";U();Ee();le();ye();Ae();et();Qe();jn();Tl=qg(Xe,"briefing-cache.json"),Jg=12*60*60*1e3,zg=3e3,Al=10*1024;a(Il,"resolveBriefingInjection");a(Yg,"runGuardInject");a(Nl,"formatInjection");a(Xg,"readCache");a(Qg,"writeCache");a(Zg,"safeDeviceId")});var Fl={};J(Fl,{decideGate:()=>Ol,runGuardGate:()=>ty});function Ol(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:Ml(n)}:(n.deny_count??0)>=Dl?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. "+Ml(n)}:{kind:"deny",reason:ey(e.sessionId,n)}}function Ml(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 ey(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:
|
|
164
164
|
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
165
165
|
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
|
|
166
|
-
After ${
|
|
167
|
-
`,{mode:384}),await
|
|
168
|
-
`).filter(r=>r.trim());if(t.length<=
|
|
166
|
+
After ${Dl} denies this gate downgrades itself to warn.`}async function ty(){try{let e=q();if(e.mode==="off")return 0;let t=await O(),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 ae(r),o=(await K()).guard_signals?.[r]?.consulted_at!==void 0,s=Ol({mode:e.mode,session:i,consulted:o,sessionId:r}),c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),l=D()??void 0;return s.kind==="deny"?(process.stdout.write(Ve(s.reason)),await B(r,{...i,deny_count:(i.deny_count??0)+1}),await G({event:"deny",session_id:r,cwd:c,project_key:l}),0):s.kind==="warn"?(process.stdout.write(qe(s.context)),await B(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await G({event:"warn",session_id:r,cwd:c,project_key:l}),0):(await B(r,{...i,edits_seen:(i.edits_seen??0)+1}),0)}catch{return 0}}var Dl,Ll=w(()=>{"use strict";Ee();Dn();At();le();Ae();et();Qe();Dl=3;a(Ol,"decideGate");a(Ml,"warnText");a(ey,"denyText");a(ty,"runGuardGate")});var jl={};J(jl,{decideStopGate:()=>$l,runGuardStop:()=>ry});function $l(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function ry(){try{let e=q();if(e.mode==="off"||!e.stopGate)return 0;let t=await O(),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 ae(n),i=(await K()).guard_signals?.[n]?.reviewed_at!==void 0;return $l({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:ny})),await B(n,{...r,stop_blocked:!0}),await G({event:"stop_block",session_id:n})),0}catch{return 0}}var ny,Hl=w(()=>{"use strict";Ee();At();Ae();et();Qe();a($l,"decideStopGate");ny="[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.";a(ry,"runGuardStop")});function Ul(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 s=n.params;if(typeof s=="object"&&s!==null){let c=s.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 Hn(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 bi(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function wi(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function _i(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Kl=w(()=>{"use strict";a(Ul,"parseFrame");a(Hn,"denyResult");a(bi,"toolEvent");a(wi,"policyEvent");a(_i,"shaEvent")});import{appendFile as iy,mkdir as oy,readFile as Bl,rename as Wl,writeFile as Vl}from"node:fs/promises";import{homedir as ql}from"node:os";import{join as Jl}from"node:path";function zl(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},o=new Map,s=1/0,c=-1/0;for(let d of e){d.at<s&&(s=d.at),d.at>c&&(c=d.at);let u=i[d.tool]??={calls:0,warns:0,denies:0};if(d.event==="tool_call"?u.calls+=1:d.event==="policy_warn"||d.event==="sha_warn"?u.warns+=1:u.denies+=1,(d.event==="policy_warn"||d.event==="policy_deny")&&d.convention_id!==void 0&&d.convention_version!==void 0){let p=o.get(d.convention_id);(p===void 0||d.convention_version>p)&&o.set(d.convention_id,d.convention_version)}}let l=Object.entries(i).sort((d,u)=>u[1].calls+u[1].warns+u[1].denies-(d[1].calls+d[1].warns+d[1].denies)).slice(0,64);return{window_start:new Date(s).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...o.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function Te(){return Jl(ql(),".maind","gateway","attest-spool.jsonl")}async function ki(e){let t=I();if(t===null)return!1;let n=await It("gateway_attest",{...e},{apiKey:t,deviceId:F(),projectKey:e.project_key??null,bridgeVersion:N,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function Yl(e){try{await oy(Jl(ql(),".maind","gateway"),{recursive:!0}),await iy(Te(),JSON.stringify(e)+`
|
|
167
|
+
`,{mode:384}),await sy()}catch{}}async function sy(){try{let t=(await Bl(Te(),"utf8")).split(`
|
|
168
|
+
`).filter(r=>r.trim());if(t.length<=Gl)return;let n=`${Te()}.${process.pid}.tmp`;await Vl(n,t.slice(-Gl).join(`
|
|
169
169
|
`)+`
|
|
170
|
-
`,{mode:384}),await
|
|
171
|
-
`).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 ki(i)||(n=!0,t.push(r))}try{let r=`${
|
|
170
|
+
`,{mode:384}),await Wl(n,Te())}catch{}}async function Xl(){let e;try{e=(await Bl(Te(),"utf8")).split(`
|
|
171
|
+
`).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 ki(i)||(n=!0,t.push(r))}try{let r=`${Te()}.${process.pid}.tmp`;await Vl(r,t.length>0?t.join(`
|
|
172
172
|
`)+`
|
|
173
|
-
`:"",{mode:384}),await
|
|
174
|
-
`,384)}async function
|
|
175
|
-
`),2;let n=Y({entryPath:X(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of
|
|
176
|
-
`);continue}let s=
|
|
177
|
-
`);continue}if(!(t.yes||await
|
|
173
|
+
`:"",{mode:384}),await Wl(r,Te())}catch{}}var Gl,Ql=w(()=>{"use strict";U();jn();ye();Gl=256;a(zl,"aggregateWindow");a(Te,"attestSpoolPath");a(ki,"postAttestation");a(Yl,"spoolAttestation");a(sy,"capSpool");a(Xl,"flushAttestSpool")});function Nt(e=process.env,t=Q()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Un(e=process.env,t=Q()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function Zl(e,t=ne()){let n={};try{let i=await L(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 M(t,JSON.stringify(r,null,2)+`
|
|
174
|
+
`,384)}async function ed(e,t=ne()){await Zl({gateway_mode:e},t)}async function td(e,t=ne()){await Zl({gateway_attest:e},t)}function nd(e=process.env,t=Q()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var vi=w(()=>{"use strict";Me();ee();a(Nt,"resolveGatewayMode");a(Un,"resolveGatewayAttest");a(Zl,"writeGatewayConfigPatch");a(ed,"writeGatewayMode");a(td,"writeGatewayAttest");a(nd,"resolveShaProofMode")});function id(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 s=o;if(s.enabled!==!0)continue;let c=typeof i.id=="string"&&i.id.length>0&&i.id.length<=64?i.id:null,l=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||l===null)continue;let d=typeof i.severity=="string"&&ay.has(i.severity)?i.severity:"recommended",u=typeof i.summary=="string"?i.summary:"",p=Array.isArray(s.servers)?s.servers.filter(h=>typeof h=="string"&&h.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(s.deny_tools)?s.deny_tools.filter(h=>typeof h=="string"&&h.length>0):[];for(let h of f){if(n.length>=256)return n;n.push({tool:h,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function cy(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function od(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let o of n)cy(o,e,t)&&(i===null||rd[o.severity]>rd[i.severity])&&(i=o);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function sd(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 ay,rd,Si=w(()=>{"use strict";ay=new Set(["required","recommended","info"]);a(id,"extractGatewayRules");rd={required:2,recommended:1,info:0};a(cy,"ruleMatches");a(od,"decideToolCall");a(sd,"policyDenyText")});import{execFileSync as cd}from"node:child_process";function py(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 ly){let s=r[o];typeof s=="string"&&dy.test(s)&&i.push({field:o,sha:s})}return i}function fy(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,ad);for(let i=ad;i>=uy;i--){let o=r.slice(0,i),s=t(o);if(s!==null&&s.startsWith(o))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:s}}return{field:"",sha:e,verdict:"unknown"}}function Ei(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 ld(){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 dd(e=process.cwd()){try{let n=cd("git",["rev-parse","--show-toplevel"],{cwd:e,env:ld(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function my(e){return t=>{try{let r=cd("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:ld(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function ud(e,t){if(t===null)return[];let n=py(e);if(n.length===0)return[];let r=my(t),i=[];for(let{field:o,sha:s}of n){let c=fy(s,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var ly,dy,uy,ad,pd=w(()=>{"use strict";ly=["commit_sha","base_sha","head_sha"],dy=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,uy=7,ad=12;a(py,"extractShaArgs");a(fy,"classifySha");a(Ei,"shaFindingText");a(ld,"cleanGitEnv");a(dd,"resolveRepoRootForSha");a(my,"gitShaResolver");a(ud,"inspectLineForShas")});import{mkdirSync as hy,readFileSync as gy,renameSync as yy,writeFileSync as by}from"node:fs";import{homedir as wy}from"node:os";import{dirname as _y,join as ky}from"node:path";function fd(){return ky(wy(),".maind","gateway","policy-cache.json")}function Kn(e,t,n=new Date().toISOString()){try{let r={version:xi,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=fd();hy(_y(i),{recursive:!0});let o=`${i}.${process.pid}.tmp`;by(o,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),yy(o,i)}catch{}}function Gn(e){try{let t=gy(fd(),"utf8"),n=JSON.parse(t);return n.version!==xi||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:xi,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var xi,Ri=w(()=>{"use strict";xi=1;a(fd,"policyCachePath");a(Kn,"writePolicyCache");a(Gn,"readPolicyCache")});function Ct(e=process.env){let t=e.MAIND_MCP_URL??yi,n=I();return{mcpUrl:t,keyFp:n?Mt(n):"anon"}}async function Bn(e=6e3){let t=I();if(t===null)return null;let n=null;try{n=D()}catch{n=null}let r=await It("get_conventions",{},{apiKey:t,deviceId:F(),projectKey:n,bridgeVersion:N,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return id(i)}var Ai=w(()=>{"use strict";Ot();U();jn();le();ye();Si();a(Ct,"policyIdentity");a(Bn,"fetchGatewayRules")});function Pt(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 vy(e){if(Pt(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 Sy(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:Pt(e)?{action:"skip",reason:"already-wrapped"}:vy(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function md(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,s=o||t.env?{...o??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return s&&(c.env=s),c}function hd(e){if(!Pt(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 gd(e){return Object.entries(e).map(([t,n])=>{let r=Sy(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var yd=w(()=>{"use strict";a(Pt,"isGatewayWrapped");a(vy,"isMaindProxyEntry");a(Sy,"classifyServer");a(md,"wrapServerEntry");a(hd,"unwrapServerEntry");a(gd,"planRewrites")});var Sd={};J(Sd,{runGatewayInstall:()=>Iy,runGatewayUninstall:()=>Ny});import{existsSync as Ey,readFileSync as xy}from"node:fs";import{homedir as Ry}from"node:os";import{join as bd}from"node:path";import{createInterface as Ay}from"node:readline";function wd(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 _d(){return[{label:"Claude Code (project .mcp.json)",path:bd(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:bd(Ry(),".claude.json")}]}async function kd(e){let t=Ay({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 vd(e){let t=Ty(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 Ty(e){try{return Ey(e)?xy(e,"utf8"):null}catch{return null}}async function Iy(e){let t=wd(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
175
|
+
`),2;let n=Y({entryPath:X(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of _d()){let o=vd(i.path);if(o===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
|
|
176
|
+
`);continue}let s=gd(o.servers);for(let c of s){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
|
|
177
|
+
`);continue}if(!(t.yes||await kd(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
|
|
178
178
|
Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
|
|
179
179
|
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
|
|
180
|
-
`);continue}o.servers[c.key]=
|
|
181
|
-
`)}!t.dryRun&&s.some(c=>c.action==="wrap")&&await
|
|
180
|
+
`);continue}o.servers[c.key]=md(o.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
|
|
181
|
+
`)}!t.dryRun&&s.some(c=>c.action==="wrap")&&await M(i.path,JSON.stringify(o.raw,null,2)+`
|
|
182
182
|
`,384)}return process.stderr.write(r>0?`
|
|
183
183
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
|
|
184
184
|
`:`
|
|
185
185
|
Nothing to wrap.
|
|
186
|
-
`),0}async function
|
|
187
|
-
`),2;let n=0;for(let r of
|
|
186
|
+
`),0}async function Ny(e){let t=wd(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
187
|
+
`),2;let n=0;for(let r of _d()){let i=vd(r.path);if(i===null)continue;let o=!1;for(let[s,c]of Object.entries(i.servers)){if(!Pt(c)||!(t.yes||await kd(`Unwrap MCP server '${s}' in ${r.label}?`)))continue;let d=hd(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${s} \u2014 wrapped shape unrecognized, left untouched
|
|
188
188
|
`);continue}i.servers[s]=d,o=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${s}
|
|
189
|
-
`)}!t.dryRun&&o&&await
|
|
189
|
+
`)}!t.dryRun&&o&&await M(r.path,JSON.stringify(i.raw,null,2)+`
|
|
190
190
|
`,384)}return process.stderr.write(n>0?`
|
|
191
191
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
|
|
192
192
|
`:`
|
|
193
193
|
Nothing wrapped \u2014 nothing to restore.
|
|
194
|
-
`),0}var
|
|
194
|
+
`),0}var Ed=w(()=>{"use strict";ee();Pe();yd();a(wd,"parseFlags");a(_d,"targets");a(kd,"confirm");a(vd,"loadConfig");a(Ty,"readFileSafeSync");a(Iy,"runGatewayInstall");a(Ny,"runGatewayUninstall")});var xd={};J(xd,{runGatewayAttest:()=>Py,runGatewayMode:()=>Cy,runGatewayPolicy:()=>Oy});async function Cy(e){let t=e[0];if(t===void 0){let n=Nt(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
|
|
195
195
|
`),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
196
|
-
`),2):(await
|
|
196
|
+
`),2):(await ed(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
|
|
197
197
|
`:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
|
|
198
198
|
`:`Convention policy is off; only explicit --deny-tool flags apply.
|
|
199
|
-
`)),0)}async function
|
|
199
|
+
`)),0)}async function Py(e){let t=e[0];if(t===void 0){let n=Un(),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)":""}.
|
|
200
200
|
`+(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.
|
|
201
201
|
`)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
|
|
202
|
-
`),2):(await
|
|
202
|
+
`),2):(await td(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.
|
|
203
203
|
`:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
|
|
204
|
-
`),0)}function
|
|
204
|
+
`),0)}function My(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
|
|
205
205
|
`;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})
|
|
206
|
-
`}return t}function
|
|
206
|
+
`}return t}function Dy(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 Oy(e){let t=e.includes("--refresh"),n=Nt(),r=Ct();if(t){let o=await Bn();o===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
207
207
|
`):(Kn(r,o),process.stdout.write(`maind: policy refreshed (${o.length} rule(s)).
|
|
208
208
|
`))}let i=Gn(r);return process.stdout.write(`maind: gateway mode '${n}'
|
|
209
209
|
`),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
|
|
210
|
-
`),0):(process.stdout.write(`maind: policy from cache (${
|
|
211
|
-
`),process.stdout.write(
|
|
212
|
-
`),0)}var
|
|
213
|
-
`,{mode:384})}catch{}}function
|
|
210
|
+
`),0):(process.stdout.write(`maind: policy from cache (${Dy(i)}, ${r.mcpUrl}):
|
|
211
|
+
`),process.stdout.write(My(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.
|
|
212
|
+
`),0)}var Rd=w(()=>{"use strict";vi();Ri();Ai();a(Cy,"runGatewayMode");a(Py,"runGatewayAttest");a(My,"renderRules");a(Dy,"cacheAge");a(Oy,"runGatewayPolicy")});var Cd={};J(Cd,{gatewayEventsFile:()=>Id,parseGatewayArgs:()=>Nd,runGateway:()=>Ky});import{spawn as Fy}from"node:child_process";import{appendFile as Ly,mkdir as $y}from"node:fs/promises";import{homedir as Ad}from"node:os";import{basename as jy,join as Td}from"node:path";import{createInterface as Hy}from"node:readline";function Id(){return Td(Ad(),".maind","gateway","events.jsonl")}async function Uy(e){try{let t=Id();await $y(Td(Ad(),".maind","gateway"),{recursive:!0}),await Ly(t,JSON.stringify(e)+`
|
|
213
|
+
`,{mode:384})}catch{}}function Nd(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 Ky(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:v,runGatewayUninstall:E}=await Promise.resolve().then(()=>(Ed(),Sd));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:x}=await Promise.resolve().then(()=>(Rd(),xd));return e[0]==="mode"?E(e.slice(1)):e[0]==="attest"?v(e.slice(1)):x(e.slice(1))}let t=Nd(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
|
|
214
214
|
maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
215
215
|
maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
216
216
|
maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
@@ -220,50 +220,50 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
|
|
|
220
220
|
NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
|
|
221
221
|
install/uninstall rewrite Claude Code MCP configs (consent per server).
|
|
222
222
|
mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
|
|
223
|
-
`),2;let{denyTools:n,label:r,command:i,args:o}=t,s=r??
|
|
224
|
-
`),process.exitCode=1});let _=
|
|
225
|
-
`),
|
|
226
|
-
`),
|
|
227
|
-
`),
|
|
228
|
-
`),
|
|
229
|
-
`)}),_.on("close",()=>{y.stdin.end()});let S=await new Promise(v=>{y.on("exit",(E,x)=>{v(E??(x?1:0))})});return clearInterval(b),await g(),S}var
|
|
223
|
+
`),2;let{denyTools:n,label:r,command:i,args:o}=t,s=r??jy(i),c=Nt(),l=nd(),d=l==="off"?null:dd(),u=c==="off"?[]:Gn(Ct())?.rules??[];c!=="off"&&Bn().then(v=>{v!==null&&(u=v,Kn(Ct(),v))}).catch(()=>{});let p=[],f=Un()&&I()!==null&&c!=="off",h=null;try{h=D()}catch{h=null}let m=a(v=>{Uy(v),f&&p.push(v)},"record"),g=a(async()=>{if(!f)return;let v=zl(p.splice(0),c,s,h);v!==null&&(await ki(v)||await Yl(v))},"attestAndReset");f&&Xl().catch(()=>{});let b=setInterval(()=>{g()},30*6e4);b.unref();let y=Fy(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)}
|
|
224
|
+
`),process.exitCode=1});let _=Hy({input:process.stdin,terminal:!1});_.on("line",v=>{let E=Ul(v);if(E.kind==="request"&&E.method==="tools/call"&&E.toolName){if(n.has(E.toolName)&&E.id!==void 0){process.stdout.write(Hn(E.id,E.toolName)+`
|
|
225
|
+
`),m(bi("deny",s,E.toolName,Date.now()));return}let x=od(E.toolName,s,u,c);if(x.kind==="deny"&&E.id!==void 0){process.stdout.write(Hn(E.id,E.toolName,sd(E.toolName,x.rule))+`
|
|
226
|
+
`),m(wi("policy_deny",s,E.toolName,Date.now(),x.rule.conventionId,x.rule.conventionVersion));return}(x.kind==="warn"||x.kind==="deny")&&m(wi("policy_warn",s,E.toolName,Date.now(),x.rule.conventionId,x.rule.conventionVersion));let T=ud(v,d);if(T.length>0){let A=T.find(ce=>ce.verdict==="fabricated");if(A!==void 0&&l==="enforce"&&c==="enforce"&&E.id!==void 0&&A!==void 0&&E.id!==void 0){process.stdout.write(Hn(E.id,E.toolName,Ei(A,!0))+`
|
|
227
|
+
`),m(_i("sha_deny",s,E.toolName,Date.now()));return}let R=A??T[0];process.stderr.write(`[maind gateway] ${Ei(R,!1)}
|
|
228
|
+
`),m(_i("sha_warn",s,E.toolName,Date.now()))}m(bi("tool_call",s,E.toolName,Date.now()))}y.stdin.write(v+`
|
|
229
|
+
`)}),_.on("close",()=>{y.stdin.end()});let S=await new Promise(v=>{y.on("exit",(E,x)=>{v(E??(x?1:0))})});return clearInterval(b),await g(),S}var Pd=w(()=>{"use strict";Kl();Ql();vi();Si();pd();Ri();Ai();U();le();a(Id,"gatewayEventsFile");a(Uy,"logEvent");a(Nd,"parseGatewayArgs");a(Ky,"runGateway")});var Di={};J(Di,{MAX_ENTRIES:()=>Ti,TTL_MS:()=>Ci,crossSessionDir:()=>Pi,decideCrossSession:()=>Od,parseSessionDb:()=>Dd,pruneDb:()=>Mi,runGuardCrossCheck:()=>Xy,runGuardCrossObserve:()=>Yy,staleReason:()=>Ii});import{mkdir as Gy,readFile as By,readdir as Wy,stat as Md,unlink as Vy,writeFile as qy}from"node:fs/promises";import{homedir as Jy}from"node:os";import{join as Ni}from"node:path";function Pi(){return Ni(Jy(),".maind","cross-session")}function Dd(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,s]of Object.entries(n.files)){if(typeof s!="object"||s===null)continue;let c=s;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,s]of Object.entries(n.warned))typeof s=="number"&&Number.isFinite(s)&&(i[o]=s);return{files:r,warned:i}}function Mi(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Ci);return n.length>Ti&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-Ti)),{files:Object.fromEntries(n),warned:e.warned}}function Od(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Ii(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 Fd(e){let t=Pi();return await Gy(t,{recursive:!0}),Ni(t,`${e}.json`)}async function Ld(e,t){try{let n=await By(await Fd(e),"utf8");return Mi(Dd(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function $d(e,t){try{await qy(await Fd(e),JSON.stringify(t),{mode:384})}catch{}}async function zy(e){try{let t=Pi();for(let n of await Wy(t)){if(!n.endsWith(".json"))continue;let r=Ni(t,n),i=await Md(r).catch(()=>null);i&&e-i.mtimeMs>Ci&&await Vy(r).catch(()=>{})}}catch{}}async function jd(e){try{return(await Md(e)).mtimeMs}catch{return}}async function Yy(e,t=Date.now()){try{if(q().mode==="off")return 0;let r=e??await O(),i=typeof r.session_id=="string"?r.session_id:"",o=We(r);if(!i||!o)return 0;let s=await jd(o);if(s===void 0)return 0;let c=await Ld(i,t);return c.files[o]={m:s,t},delete c.warned[o],await $d(i,Mi(c,t)),await zy(t),0}catch{return 0}}async function Xy(e,t=Date.now()){try{let n=q();if(n.mode==="off")return 0;let r=e??await O(),i=typeof r.session_id=="string"?r.session_id:"",o=We(r);if(!i||!o)return 0;let s=await Ld(i,t),c=Od(s.files[o]?.m,await jd(o));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(Ve(Ii(o,c))+`
|
|
230
230
|
`),await G({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o}),0):(s.warned[o]===c.current||(process.stdout.write(qe(Ii(o,c))+`
|
|
231
|
-
`),s.warned[o]=c.current,await
|
|
232
|
-
`);return}let i=this.localRouter!==null&&r?.method==="tools/list",o=this.buildHeaders(!0),s;try{s=await fetch(this.mcpUrl,{method:"POST",headers:o,body:t})}catch(d){let u=Ft(t);if(this.serveInitializeFromCache(t,u))return
|
|
233
|
-
`);return}if(
|
|
234
|
-
`);return}if(l.startsWith("text/event-stream"))await
|
|
235
|
-
`)}}}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 nt(
|
|
236
|
-
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${
|
|
231
|
+
`),s.warned[o]=c.current,await $d(i,s),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 Ci,Ti,Oi=w(()=>{"use strict";Ee();Dn();Ae();et();Ci=48*3600*1e3,Ti=500;a(Pi,"crossSessionDir");a(Dd,"parseSessionDb");a(Mi,"pruneDb");a(Od,"decideCrossSession");a(Ii,"staleReason");a(Fd,"dbPath");a(Ld,"loadDb");a($d,"saveDb");a(zy,"sweepStaleSessionFiles");a(jd,"fileMtime");a(Yy,"runGuardCrossObserve");a(Xy,"runGuardCrossCheck")});import{randomUUID as Qy}from"node:crypto";import{createInterface as Qd}from"node:readline";var Hd=[["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 Ud(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of Hd)if(t.includes(n))return r;return null}a(Ud,"mapClientInfoNameToFamily");function $i(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Wn(t)||t.method!=="initialize")return null;let n=t.params;if(!Wn(n))return null;let r=n.clientInfo;if(!Wn(r))return null;let i=r.name,o=Ud(typeof i=="string"?i:null);if(o===null)return null;let s=r.version,c=typeof s=="string"&&s.length>0?s.slice(0,64):null;return{family:o,version:c}}a($i,"tryExtractInitializeClient");function Wn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Wn,"isRecord");Ot();var Zd="https://mcp.maind.dev/mcp",nt=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{a(this,"BridgeReauthNeeded")}},jt=class{static{a(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;presenceFrameId=0;sessionId=null;initFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=Mt(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=eu(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=tu(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.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??Zd}async run(){let t=Qd({input:process.stdin,crlfDelay:1/0});for await(let n of t){if(this.terminated)return;let r=n.trim();r.length!==0&&await this.forwardFrame(r)}}async forwardFrame(t,n=!1){if(!this.clientFamilyLocked&&this.clientFamily===null){let d=$i(t);d!==null&&(this.clientFamily=d.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=d.version))}this.initFrame===null&&Lt(t)&&(this.initFrame=t);let r=ru(t);if(r?.method==="tools/call"&&this.presence?.onActivity(),this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let d=await this.localRouter.handleToolCall(r?.id??null,r?.params);process.stdout.write(d+`
|
|
232
|
+
`);return}let i=this.localRouter!==null&&r?.method==="tools/list",o=this.buildHeaders(!0),s;try{s=await fetch(this.mcpUrl,{method:"POST",headers:o,body:t})}catch(d){let u=Ft(t);if(this.serveInitializeFromCache(t,u))return;$t(u,-32603,`bridge network error: ${ou(d)}`);return}let c=s.headers.get("mcp-session-id");if(c&&c!==this.sessionId&&(this.sessionId=c),s.status===401){await this.handle401(s,t);return}if(s.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!Lt(t)){let d=await s.text().catch(()=>"");if(iu(d)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let u=Ft(t);$t(u,-32603,`bridge upstream error (HTTP 404): ${d.slice(0,500)}`);return}if(!s.ok){let d=Ft(t),u=await s.text().catch(()=>"");if(this.serveInitializeFromCache(t,d))return;$t(d,-32603,`bridge upstream error (HTTP ${s.status}): ${u.slice(0,500)}`);return}let l=s.headers.get("content-type")??"";if(i&&this.localRouter){let d=l.startsWith("text/event-stream")?await Bi(s):await s.text(),u=this.localRouter.augmentToolsList(d);u.trim().length>0&&process.stdout.write(u+`
|
|
233
|
+
`);return}if(Lt(t)){let d=l.startsWith("text/event-stream")?await Bi(s):await s.text();this.cacheInitializeResult(d),this.presence?.onSessionReady(),d.trim().length>0&&process.stdout.write(d+`
|
|
234
|
+
`);return}if(l.startsWith("text/event-stream"))await nu(s);else{if(s.status===202)return;{let d=await s.text();d.trim().length>0&&process.stdout.write(d+`
|
|
235
|
+
`)}}}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 nt(su(i));let s=Ft(n);$t(s,-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 au(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=tt()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&Ui(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Lt(t))return!1;let r=Ki(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(Gi(n,r)+`
|
|
236
|
+
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${Dt(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function eu(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}a(eu,"normalizeClientFamily");function tu(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}a(tu,"normalizeClientVersion");async function nu(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=a(()=>{if(i.length===0)return;let s=i.join(`
|
|
237
237
|
`).trim();i=[],s.length>0&&process.stdout.write(s+`
|
|
238
238
|
`)},"flushEvent");try{for(;;){let{value:s,done:c}=await t.read();if(c)break;r+=n.decode(s,{stream:!0});let l;for(;(l=r.indexOf(`
|
|
239
|
-
`))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){o();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{o()}}a(
|
|
239
|
+
`))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){o();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{o()}}a(nu,"pipeSseToStdout");function ru(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}a(ru,"parseRpc");async function Bi(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=[],s=a(()=>{if(o.length===0)return;let c=o.join(`
|
|
240
240
|
`).trim();o=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
241
241
|
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){s();continue}p.startsWith(":")||p.startsWith("data:")&&o.push(p.slice(5).replace(/^\s/,""))}}}finally{s()}return i.join(`
|
|
242
|
-
`)}a(Bi,"collectSseText");function Ft(e){try{return JSON.parse(e).id??null}catch{return null}}a(Ft,"tryExtractId");function
|
|
243
|
-
`)}a(
|
|
244
|
-
`).map(s=>s.trim()).filter(s=>s.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}}a(
|
|
242
|
+
`)}a(Bi,"collectSseText");function Ft(e){try{return JSON.parse(e).id??null}catch{return null}}a(Ft,"tryExtractId");function Lt(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}a(Lt,"isInitializeRequest");function iu(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")}a(iu,"isSessionLossBody");function ou(e){return e instanceof Error?e.message:String(e)}a(ou,"stringifyErr");function $t(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
243
|
+
`)}a($t,"emitJsonRpcError");function su(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}a(su,"extractHint");function au(e){try{let t=e.trim();if(t.length===0)return null;let n=t;if(!t.startsWith("{")){let o=t.split(`
|
|
244
|
+
`).map(s=>s.trim()).filter(s=>s.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}}a(au,"parsePresenceToolResult");U();U();import{spawn as yu}from"node:child_process";import{platform as bu}from"node:os";var wu="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function _u(){let e=process.env.MAIND_FUNCTIONS_ORIGIN;return e&&e.length>0?e.replace(/\/+$/,""):wu}a(_u,"functionsOrigin");async function Ne(e,t=process.stderr){let n=_u(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,o=Ut(e),s=`mcp-bridge-${o.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:s,meta:o})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await Eu(l.verification_uri_complete).catch(()=>{}),Su(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await vu(u);let p=await ku(i,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
|
|
245
245
|
`),null));if(p){if(p.status==="approved")return ge(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
|
|
246
246
|
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
|
|
247
247
|
`),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
|
|
248
248
|
`),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
|
|
249
|
-
`),null}a(Ne,"runDeviceFlow");async function
|
|
249
|
+
`),null}a(Ne,"runDeviceFlow");async function ku(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()}a(ku,"pollOnce");function vu(e){return new Promise(t=>setTimeout(t,e))}a(vu,"sleep");function Su(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: ${zi(e.verification_uri,56)} \u2502`,` \u2502 Code: ${zi(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(`
|
|
250
250
|
`)+`
|
|
251
|
-
`)}a(
|
|
251
|
+
`)}a(Su,"printAuthInstructions");function zi(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}a(zi,"pad");async function Eu(e){let t,n;switch(bu()){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=yu(t,n,{stdio:"ignore",detached:!0});o.on("error",i),o.unref(),r()}catch(o){i(o)}})}a(Eu,"openExternalBrowser");ye();le();ye();import*as Sa from"node:os";function Yi(e){let t={projectRoot:null,full:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--no-preamble":t.noPreamble=!0;break;case"--no-hook":t.noHook=!0;break;case"--non-interactive":t.nonInteractive=!0;break;case"--telemetry":t.telemetry=!0;break;case"--skip-codex":t.skipCodex=!0;break;case"--dry-run":t.dryRun=!0;break;case"--auto-working-paths":t.autoWorkingPaths=!0;break;case"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new z("--project-root requires a path argument");t.projectRoot=i,n++;break}case"--token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new z("--token requires a token argument");t.token=i,n++;break}case"--one-click-token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new z("--one-click-token requires a token argument");t.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new z("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=i,n++;break}case"--client":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new z("--client requires a family argument (e.g. claude-code, cursor, windsurf, copilot, codex, claude-desktop)");t.client=i,n++;break}default:throw new z(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}a(Yi,"parseInstallFlags");var z=class extends Error{static{a(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function Xi(){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(`
|
|
252
252
|
`))}a(Xi,"printInstallHelp");var Kt=class{static{a(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_
|
|
253
253
|
`;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(d=>d.target.length)),r=Math.max(t[1].length,...this.results.map(d=>d.action.length)),i=Math.max(t[2].length,...this.results.map(d=>d.status.length)),o=Math.max(t[3].length,...this.results.map(d=>(d.detail??"").length)),s=a((d,u)=>d+" ".repeat(Math.max(0,u-d.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(o)} |`,l=[];l.push(`| ${s(t[0],n)} | ${s(t[1],r)} | ${s(t[2],i)} | ${s(t[3],o)} |`),l.push(c);for(let d of this.results)l.push(`| ${s(d.target,n)} | ${s(d.action,r)} | ${s(d.status,i)} | ${s(d.detail??"",o)} |`);return l.join(`
|
|
254
254
|
`)+`
|
|
255
255
|
`}print(t){let n=this.summary();t.write(`
|
|
256
256
|
`),t.write(this.toMarkdownTable()),t.write(`
|
|
257
257
|
Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
|
|
258
|
-
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as Qi from"node:fs/promises";import*as de from"node:path";import*as Zi from"node:readline";var
|
|
258
|
+
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as Qi from"node:fs/promises";import*as de from"node:path";import*as Zi from"node:readline";var Cu=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function eo(e){let t=de.resolve(e),n=t;for(;;){if(await no(n))return n;let r=de.dirname(n);if(r===n)return t;n=r}}a(eo,"detectProjectRoot");async function to(e){let n=de.resolve(e),r=[];for(;;){await no(n)&&r.push(n);let i=de.dirname(n);if(i===n)break;n=i}return r}a(to,"findAllProjectRoots");async function no(e){for(let t of Cu)try{return await Qi.access(de.join(e,t)),!0}catch{}return!1}a(no,"hasAnyMarker");async function ro(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
|
|
259
259
|
Multiple project roots found between cwd and the filesystem root:
|
|
260
260
|
`),e.forEach((o,s)=>{process.stdout.write(` [${s+1}] ${o}
|
|
261
261
|
`)}),process.stdout.write(`
|
|
262
262
|
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=Zi.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(o=>{n.question("",s=>o(s.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>.
|
|
263
|
-
`),null):e[i-1]}a(ro,"disambiguateProjectRoot");Pe();import*as W from"node:path";function ao(e){let t=e.launch??Y({entryPath:X(),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}}}a(ao,"buildMaindServerEntry");function
|
|
264
|
-
`;if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await
|
|
265
|
-
`)||(
|
|
266
|
-
`)}catch(
|
|
263
|
+
`),null):e[i-1]}a(ro,"disambiguateProjectRoot");Pe();import*as W from"node:path";function ao(e){let t=e.launch??Y({entryPath:X(),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}}}a(ao,"buildMaindServerEntry");function Ou(e){switch(e.platform){case"darwin":return W.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??W.join(e.homeDir,"AppData","Roaming");return W.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??W.join(e.homeDir,".config");return W.join(t,"Claude","claude_desktop_config.json")}}}a(Ou,"claudeDesktopConfigPath");function co(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:W.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:W.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:Ou(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:W.join(e.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:W.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:W.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}a(co,"getClientTargets");function lo(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}a(lo,"filterTargetsByFamily");function uo(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:so(e.env.XDG_CONFIG_HOME),appData:so(e.env.APPDATA)}}a(uo,"makeDefaultContext");function so(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}a(so,"nonEmpty");Pe();ee();var it="maind";async function go(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 L(e.path)}catch(u){return Xn(e,"read",u)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{i=JSON.parse(r)}catch(u){return Xn(e,"parse",u)}}if(!ue(i))return{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};let s=e.key==="claude-code-user"&&$u(i),c,l=!1;if(s){let u=i[it];ue(u)&&ho(u,t)&&(l=!0),c={...i,[it]:mo(u,t)}}else{let u=ue(i.mcpServers)?i.mcpServers:{},p=u[it];ue(p)&&ho(p,t)&&(l=!0),c={...i,mcpServers:{...u,[it]:mo(p,t)}}}if(l&&r!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let d=JSON.stringify(c,null,2)+`
|
|
264
|
+
`;if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await M(e.path,d)}catch(u){return Xn(e,"write",u)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}a(go,"mergeJsonConfig");function mo(e,t){let n=ue(e)&&ue(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}}a(mo,"mergeEntry");function $u(e){return!("mcpServers"in e||!(it in e))}a($u,"hasRootShape");function ho(e,t){if(!ue(e)||e.command!==t.command||!ju(e.args,t.args)||!ue(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}a(ho,"serverEntriesEqual");function ju(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}a(ju,"arrayEquals");function ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(ue,"isObject");function Xn(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}a(Xn,"failed");ee();import{parse as Hu,stringify as Uu}from"smol-toml";async function yo(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 L(e.path)}catch(m){return Vt(e,"read",m)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{let m=Hu(r);if(!be(m))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=m}catch(m){return Vt(e,"parse",m)}}let s=be(i.mcp_servers)?i.mcp_servers:{},c=s.maind;if(be(c)&&Ku(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=be(c)&&be(c.env)?c.env:{},d={...t.env};for(let[m,g]of Object.entries(l))!(m in d)&&typeof g=="string"&&(d[m]=g);let u={command:t.command,args:[...t.args],env:d},p={...i,mcp_servers:{...s,maind:u}},f;try{f=Uu(p),f.endsWith(`
|
|
265
|
+
`)||(f+=`
|
|
266
|
+
`)}catch(m){return Vt(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 M(e.path,f)}catch(m){return Vt(e,"write",m)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}a(yo,"mergeTomlConfig");function Ku(e,t){if(!be(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(!be(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}a(Ku,"tomlServerEntryEqual");function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(be,"isObject");function Vt(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}a(Vt,"failed");import*as te from"node:path";var Gu="__STACK__";var Bu="__INTENT__";var Qn="https://mcp.maind.dev/mcp",Wu=`?stack=${Gu}&intent=${Bu}`;function Vu(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}a(Vu,"buildStackAwareEndpoint");var ow=Vu(Qn,{stack:["nextjs","supabase"],intent:"mixed"}),st=`## maind MCP integration \u2014 Mandatory consultation
|
|
267
267
|
|
|
268
268
|
This project uses the maind MCP server (mcp.maind.dev/mcp) as
|
|
269
269
|
authoritative source for vetted coding conventions and lessons. The
|
|
@@ -332,7 +332,7 @@ For non-trivial changes, resolve documentation path in this order:
|
|
|
332
332
|
If no path is discoverable, provide a guided fallback:
|
|
333
333
|
\`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
|
|
334
334
|
|
|
335
|
-
Full tool set + provenance via \`get_conventions\`.`;function
|
|
335
|
+
Full tool set + provenance via \`get_conventions\`.`;function qu(e){return`I want to add the **maind MCP server** to my AI coding agent.
|
|
336
336
|
|
|
337
337
|
- My stack: \`__STACK__\`
|
|
338
338
|
- MCP endpoint: \`${e}\`
|
|
@@ -528,7 +528,7 @@ written config.
|
|
|
528
528
|
|
|
529
529
|
--- Preamble block ---
|
|
530
530
|
|
|
531
|
-
${st}`}a(
|
|
531
|
+
${st}`}a(qu,"buildAiPromptBody");function ot(e,t,n){let r=n?`
|
|
532
532
|
MAIND_CLIENT_FAMILY="${n}"`:"";return`#!/usr/bin/env bash
|
|
533
533
|
set -euo pipefail
|
|
534
534
|
|
|
@@ -563,7 +563,7 @@ ${n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":""}
|
|
|
563
563
|
config.mcpServers.maind = server;
|
|
564
564
|
fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
|
|
565
565
|
console.log("WROTE " + file);
|
|
566
|
-
NODE`}a(ot,"buildJsonConfigInstaller");function
|
|
566
|
+
NODE`}a(ot,"buildJsonConfigInstaller");function Ju(e){return`#!/usr/bin/env bash
|
|
567
567
|
set -euo pipefail
|
|
568
568
|
|
|
569
569
|
CONFIG_FILE="$HOME/.codex/config.toml"
|
|
@@ -616,7 +616,7 @@ if (serverCount !== 1 || envCount !== 1) {
|
|
|
616
616
|
|
|
617
617
|
fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
|
|
618
618
|
console.log("WROTE " + file);
|
|
619
|
-
NODE`}a(
|
|
619
|
+
NODE`}a(Ju,"buildCodexTomlInstaller");function zu(e=Qn){let t=`${e}${Wu}`;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:qu(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:`{
|
|
620
620
|
"mcpServers": {
|
|
621
621
|
"maind": {
|
|
622
622
|
"command": "npx",
|
|
@@ -644,7 +644,7 @@ args = ["-y", "@maind-dev/mcp-bridge"]
|
|
|
644
644
|
|
|
645
645
|
[mcp_servers.maind.env]
|
|
646
646
|
MAIND_CLIENT_FAMILY = "codex"
|
|
647
|
-
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:
|
|
647
|
+
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:Ju(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:`{
|
|
648
648
|
"mcpServers": {
|
|
649
649
|
"maind": {
|
|
650
650
|
"command": "npx",
|
|
@@ -753,15 +753,15 @@ const tools = await mcp.getTools();
|
|
|
753
753
|
"env": {
|
|
754
754
|
"MAIND_MCP_URL": "${t}"
|
|
755
755
|
}
|
|
756
|
-
}`}]}a(
|
|
757
|
-
`:
|
|
758
|
-
`;return await
|
|
756
|
+
}`}]}a(zu,"buildSnippetTemplates");var sw=zu(Qn);ee();var Yu="## maind MCP integration";function Xu(e){return[{key:"preamble:CLAUDE.md",path:te.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:te.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:te.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:te.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:te.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:te.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}a(Xu,"buildPreambleTargets");async function bo(e,t=!1){let n=Xu(e),r=[];for(let i of n)r.push(await Qu(i,t));return r}a(bo,"writePreambleFiles");async function Qu(e,t){try{if(e.mayNeedParentDir&&!t&&await Yn(te.dirname(e.path)),await po(e.path,Yu))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await L(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?`${st}
|
|
757
|
+
`:Zu(r)+`${st}
|
|
758
|
+
`;return await M(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}}}a(Qu,"writeOnePreambleFile");function Zu(e){return e.endsWith(`
|
|
759
759
|
|
|
760
760
|
`)?e:e.endsWith(`
|
|
761
761
|
`)?e+`
|
|
762
762
|
`:e+`
|
|
763
763
|
|
|
764
|
-
`}a(
|
|
764
|
+
`}a(Zu,"ensureTrailingBlankLine");or();Me();ee();import*as Io from"node:readline";var _e="config:auto_working_paths",up=`
|
|
765
765
|
Enable presence enrichment (auto working_paths)?
|
|
766
766
|
With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
|
|
767
767
|
locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
|
|
@@ -770,10 +770,10 @@ before editing the same area. Directory names only: never file contents, never
|
|
|
770
770
|
absolute paths. Server-side these paths are account-private (org members never
|
|
771
771
|
see them) and revocable any time on the dashboard consent page or via
|
|
772
772
|
{"auto_working_paths": false} in the bridge config.
|
|
773
|
-
[y/N]: `;async function No(e){let t=e.configPath??ne(),n={};try{let s=await
|
|
774
|
-
`;if(e.dryRun)return{target:_e,action:"merge",status:"would-merge",detail:t};try{await
|
|
775
|
-
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=I();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 Ne(e.bridgeVersion,
|
|
776
|
-
`,1)[0]??"").trim().slice(0,200)}a(en,"signatureOf");function hp(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}}a(hp,"calleeName");function gp(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=hp(r.childForFieldName("function"));i&&n.add(i)}return[...n]}a(gp,"collectCallTargets");function Oe(e,t,n,r){for(let i of gp(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}a(Oe,"addCallRefs");var Fo="call";function $o(e,t){let n=Zt();for(let r of e.namedChildren)yp(r,t,n);return n}a($o,"extractPython");function Lo(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}a(Lo,"unwrapDecorated");function yp(e,t,n){let r=Lo(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??wp(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=tn(r,t,i,i,"function");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let s=r.childForFieldName("body");s&&Oe(n,o.nodeKey,s,Fo);return}case"class_definition":bp(r,t,n);return;case"expression_statement":{let o=r.namedChildren.find(s=>s.type==="assignment")?.childForFieldName("left");if(o&&o.type==="identifier"){let s=tn(r,t,o.text,o.text,"variable");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}return}default:return}}a(yp,"handleTopLevel");function bp(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=tn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let o=e.childForFieldName("superclasses");if(o){for(let c of o.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let s=e.childForFieldName("body");if(s)for(let c of s.namedChildren){let l=Lo(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=tn(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let m=l.childForFieldName("body");m&&Oe(n,p.nodeKey,m,Fo)}}a(bp,"addClass");function tn(e,t,n,r,i){return{nodeKey:Yt(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:pe(e.startPosition.row),endLine:pe(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:en(e),doc:null}}a(tn,"makeNode");function wp(e){return e.descendantsOfType("dotted_name")[0]?.text??null}a(wp,"firstDottedName");dt();var Ho="call_expression";function Uo(e,t){let n=Zt();for(let r of e.namedChildren)kp(r,t,n);return n}a(Uo,"extractTypescript");function _p(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}a(_p,"unwrapExport");function kp(e,t,n){let r=_p(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:Sp(i)});return}case"function_declaration":case"generator_function_declaration":{jo(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{vp(r,t,n);return}case"interface_declaration":ar(r,t,n,"interface");return;case"type_alias_declaration":ar(r,t,n,"type_alias");return;case"enum_declaration":ar(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 s=i.childForFieldName("value"),c=s?.type==="arrow_function"||s?.type==="function_expression"||s?.type==="function";jo(i,t,n,c?"function":"variable",o,s)}return}default:return}}a(kp,"handleTopLevel");function jo(e,t,n,r,i,o){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=nn(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let d=o??e.childForFieldName("body")??e;r==="function"&&d&&Oe(n,l.nodeKey,d,Ho)}a(jo,"addFunctionLike");function ar(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=nn(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}a(ar,"addSimpleNamed");function vp(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=nn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let s of e.descendantsOfType("class_heritage"))for(let c of s.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let d of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:d.text});for(let d of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:d.text})}let o=e.childForFieldName("body");if(o)for(let s of o.namedChildren){if(s.type!=="method_definition")continue;let c=s.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,d=nn(s,t,c,l,"method");n.nodes.push(d),n.edges.push({srcKey:i.nodeKey,dstKey:d.nodeKey,kind:"contains"});let u=s.childForFieldName("body");u&&Oe(n,d.nodeKey,u,Ho)}}a(vp,"addClass");function nn(e,t,n,r,i){return{nodeKey:Yt(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:pe(e.startPosition.row),endLine:pe(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:en(e),doc:null}}a(nn,"makeNode");function Sp(e){return e.replace(/^["'`]|["'`]$/g,"")}a(Sp,"stripQuotes");import{createRequire as Ep}from"node:module";import{join as xp}from"node:path";var Ko={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Go="tree-sitter.wasm";function Bo(e,t){return t?xp(t,Ko[e]):Ep(import.meta.url).resolve(`tree-sitter-wasms/out/${Ko[e]}`)}a(Bo,"grammarPath");var Tp=["typescript","tsx","javascript","python"],rn=class{static{a(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await cr.init(this.assetDir?{locateFile:a(t=>Rp(this.assetDir,t||Go),"locateFile")}:void 0),this.parser=new cr,this.initialized=!0)}supports(t){return Tp.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 s=o.rootNode,c=zt(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:pe(s.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?$o(s,d):Uo(s,d);return o.delete(),{filePath:t,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await cr.Language.load(Bo(t,this.assetDir)),this.grammars.set(t,n)),n}};Ur();import{createRequire as If}from"node:module";var sa=If(import.meta.url);function aa(){return sa("node:sqlite")}a(aa,"loadBuiltin");var _t=null;function kt(){if(_t)return _t;try{let{DatabaseSync:e}=aa(),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(),_t={ok:!0}}finally{t.close()}}catch(e){_t={ok:!1,reason:e instanceof Error?e.message:String(e)}}return _t}a(kt,"probeBuiltinSqlite");function Nf(e){let{DatabaseSync:t}=aa(),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>n.exec(r),"exec"),close:a(()=>n.close(),"close"),transaction:a(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}a(Nf,"openBuiltin");function Cf(e){let t=sa("better-sqlite3"),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>{n.exec(r)},"exec"),close:a(()=>{n.close()},"close"),transaction:a(r=>n.transaction(r),"transaction")}}a(Cf,"openBetter");function Pf(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}a(Pf,"backendOverride");function Kr(e){let t=Pf(),n=a(i=>{let o=i==="node:sqlite"?Nf(e):Cf(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=kt();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=kt();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})`)}}a(Kr,"openSqliteDatabase");bt();Hr();function yn(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}}a(yn,"toNodeRow");var ca=400,bn=class{static{a(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Kr(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Zs)}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(),s=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),s.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 s of t)i.run(s);let o=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let s of n)o.run(s.srcKey,s.dstKey,s.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?yn(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(yn)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(yn)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(yn)}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=ta(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
773
|
+
[y/N]: `;async function No(e){let t=e.configPath??ne(),n={};try{let s=await L(t);if(s!==null&&s.trim().length>0){let c=JSON.parse(s);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(n=c)}}catch{}if(typeof n.auto_working_paths=="boolean")return{target:_e,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:_e,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??pp)(e.out,up)}else return{target:_e,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:_e,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)+`
|
|
774
|
+
`;if(e.dryRun)return{target:_e,action:"merge",status:"would-merge",detail:t};try{await M(t,o,384)}catch(s){return{target:_e,action:"merge",status:"failed",detail:`write: ${s instanceof Error?s.message:String(s)}`}}return{target:_e,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}a(No,"applyWorkingPathsConsent");async function pp(e,t){e.write(t);let n=Io.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"}a(pp,"promptYesNoDefaultNo");U();async function Co(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)}}a(Co,"exchangeOneClickToken");async function Do(e){let t="browser-pair";if(e.token!==null)try{let o=fp(e.token);return e.dryRun?{apiKey:o,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(Ie(),ge(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:Po(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=Ut(e.bridgeVersion),s=await Co({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:o.device_id,label:Ji(),clientMeta:{...o}});if(s.ok)return Ie(),ge(s.apiKey),{apiKey:s.apiKey,result:{target:t,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${s.plan})`}};n=s.reason,Mo(e).write(`[maind-mcp-bridge] one-click exchange failed (${s.reason}) \u2014 falling back to browser pairing.
|
|
775
|
+
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=I();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 Ne(e.bridgeVersion,Mo(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:Po(o)}}}}a(Do,"pairOrUseToken");function fp(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}a(fp,"validateTokenShape");function Po(e){return e instanceof Error?e.message:String(e)}a(Po,"errMessage");function Mo(e){return e.out??process.stdout}a(Mo,"out");var mp="https://vsddmiosisvfrairepxv.supabase.co/functions/v1",hp="/install-completed";async function Oo(e){if(!e.enabled||e.apiKey===null)return;let n=`${(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"")||mp}${hp}`,r={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:yp(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:gp(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)}}a(Oo,"postInstallTelemetry");function gp(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}a(gp,"countStatuses");function yp(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}a(yp,"parseNodeMajor");import{execFileSync as ua}from"node:child_process";import{existsSync as pa,realpathSync as fa}from"node:fs";import{createRequire as jf}from"node:module";import{basename as Hf,dirname as Uf,isAbsolute as ma,join as Kf,relative as ha,resolve as wn,sep as ga}from"node:path";import{mkdirSync as Lf}from"node:fs";import{posix as la}from"node:path";dt();Qt();import{join as Ip}from"node:path";import cr from"web-tree-sitter";dt();function Zt(){return{nodes:[],edges:[],refs:[],imports:[]}}a(Zt,"newResult");function pe(e){return e+1}a(pe,"line1");function en(e){return(e.text.split(`
|
|
776
|
+
`,1)[0]??"").trim().slice(0,200)}a(en,"signatureOf");function bp(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}}a(bp,"calleeName");function wp(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=bp(r.childForFieldName("function"));i&&n.add(i)}return[...n]}a(wp,"collectCallTargets");function De(e,t,n,r){for(let i of wp(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}a(De,"addCallRefs");var Fo="call";function Lo(e,t){let n=Zt();for(let r of e.namedChildren)_p(r,t,n);return n}a(Lo,"extractPython");function $o(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}a($o,"unwrapDecorated");function _p(e,t,n){let r=$o(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??vp(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=tn(r,t,i,i,"function");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let s=r.childForFieldName("body");s&&De(n,o.nodeKey,s,Fo);return}case"class_definition":kp(r,t,n);return;case"expression_statement":{let o=r.namedChildren.find(s=>s.type==="assignment")?.childForFieldName("left");if(o&&o.type==="identifier"){let s=tn(r,t,o.text,o.text,"variable");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}return}default:return}}a(_p,"handleTopLevel");function kp(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=tn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let o=e.childForFieldName("superclasses");if(o){for(let c of o.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let s=e.childForFieldName("body");if(s)for(let c of s.namedChildren){let l=$o(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=tn(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=l.childForFieldName("body");f&&De(n,p.nodeKey,f,Fo)}}a(kp,"addClass");function tn(e,t,n,r,i){return{nodeKey:Yt(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:pe(e.startPosition.row),endLine:pe(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:en(e),doc:null}}a(tn,"makeNode");function vp(e){return e.descendantsOfType("dotted_name")[0]?.text??null}a(vp,"firstDottedName");dt();var Ho="call_expression";function Uo(e,t){let n=Zt();for(let r of e.namedChildren)Ep(r,t,n);return n}a(Uo,"extractTypescript");function Sp(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}a(Sp,"unwrapExport");function Ep(e,t,n){let r=Sp(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:Rp(i)});return}case"function_declaration":case"generator_function_declaration":{jo(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{xp(r,t,n);return}case"interface_declaration":ar(r,t,n,"interface");return;case"type_alias_declaration":ar(r,t,n,"type_alias");return;case"enum_declaration":ar(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 s=i.childForFieldName("value"),c=s?.type==="arrow_function"||s?.type==="function_expression"||s?.type==="function";jo(i,t,n,c?"function":"variable",o,s)}return}default:return}}a(Ep,"handleTopLevel");function jo(e,t,n,r,i,o){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=nn(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let d=o??e.childForFieldName("body")??e;r==="function"&&d&&De(n,l.nodeKey,d,Ho)}a(jo,"addFunctionLike");function ar(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=nn(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}a(ar,"addSimpleNamed");function xp(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=nn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let s of e.descendantsOfType("class_heritage"))for(let c of s.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let d of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:d.text});for(let d of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:d.text})}let o=e.childForFieldName("body");if(o)for(let s of o.namedChildren){if(s.type!=="method_definition")continue;let c=s.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,d=nn(s,t,c,l,"method");n.nodes.push(d),n.edges.push({srcKey:i.nodeKey,dstKey:d.nodeKey,kind:"contains"});let u=s.childForFieldName("body");u&&De(n,d.nodeKey,u,Ho)}}a(xp,"addClass");function nn(e,t,n,r,i){return{nodeKey:Yt(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:pe(e.startPosition.row),endLine:pe(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:en(e),doc:null}}a(nn,"makeNode");function Rp(e){return e.replace(/^["'`]|["'`]$/g,"")}a(Rp,"stripQuotes");import{createRequire as Ap}from"node:module";import{join as Tp}from"node:path";var Ko={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},Go="tree-sitter.wasm";function Bo(e,t){return t?Tp(t,Ko[e]):Ap(import.meta.url).resolve(`tree-sitter-wasms/out/${Ko[e]}`)}a(Bo,"grammarPath");var Np=["typescript","tsx","javascript","python"],rn=class{static{a(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await cr.init(this.assetDir?{locateFile:a(t=>Ip(this.assetDir,t||Go),"locateFile")}:void 0),this.parser=new cr,this.initialized=!0)}supports(t){return Np.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 s=o.rootNode,c=zt(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:pe(s.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?Lo(s,d):Uo(s,d);return o.delete(),{filePath:t,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await cr.Language.load(Bo(t,this.assetDir)),this.grammars.set(t,n)),n}};Ur();import{createRequire as Pf}from"node:module";var sa=Pf(import.meta.url);function aa(){return sa("node:sqlite")}a(aa,"loadBuiltin");var _t=null;function kt(){if(_t)return _t;try{let{DatabaseSync:e}=aa(),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(),_t={ok:!0}}finally{t.close()}}catch(e){_t={ok:!1,reason:e instanceof Error?e.message:String(e)}}return _t}a(kt,"probeBuiltinSqlite");function Mf(e){let{DatabaseSync:t}=aa(),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>n.exec(r),"exec"),close:a(()=>n.close(),"close"),transaction:a(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}a(Mf,"openBuiltin");function Df(e){let t=sa("better-sqlite3"),n=new t(e);return{prepare:a(r=>n.prepare(r),"prepare"),exec:a(r=>{n.exec(r)},"exec"),close:a(()=>{n.close()},"close"),transaction:a(r=>n.transaction(r),"transaction")}}a(Df,"openBetter");function Of(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}a(Of,"backendOverride");function Kr(e){let t=Of(),n=a(i=>{let o=i==="node:sqlite"?Mf(e):Df(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=kt();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=kt();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})`)}}a(Kr,"openSqliteDatabase");bt();Hr();function yn(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}}a(yn,"toNodeRow");var ca=400,bn=class{static{a(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Kr(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Zs)}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(),s=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),s.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 s of t)i.run(s);let o=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let s of n)o.run(s.srcKey,s.dstKey,s.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?yn(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(yn)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(yn)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(yn)}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=ta(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
777
777
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
778
778
|
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
779
779
|
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
@@ -796,32 +796,32 @@ see them) and revocable any time on the dashboard consent page or via
|
|
|
796
796
|
content_hash = excluded.content_hash,
|
|
797
797
|
mtime_ms = excluded.mtime_ms,
|
|
798
798
|
size = excluded.size,
|
|
799
|
-
indexed_at = excluded.indexed_at`)),this._upsertFile}};bt();var
|
|
799
|
+
indexed_at = excluded.indexed_at`)),this._upsertFile}};bt();var $f=".maind/code-index.sqlite";function da(e){let t=e.dbPath??la.join(e.repoRoot,$f);Lf(la.dirname(t),{recursive:!0});let n=new bn(t),r=new rn;return new wt({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}a(da,"createNodeCodeIndex");function ya(){let e=kt();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return jf(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}`}}}a(ya,"probeNativeStore");function ba(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)}a(ba,"isNativeStoreUnavailable");var wa="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.";function ie(e=process.cwd()){try{let t=ua("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}}a(ie,"resolveRepoRoot");function _a(e,t=ie(),n=process.cwd()){let r=ma(e)?[e]:[wn(t,e),wn(n,e)];for(let i of r){let o=Uf(i);if(!pa(o))continue;let s;try{s=fa(o)}catch{continue}let c=ka(s);if(c===null)continue;let l=ha(c,Kf(s,Hf(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(ga).join("/")}}return null}a(_a,"resolveRepoRootForPath");function _n(e,t=ie(),n=process.cwd()){let r=ma(e)?[e]:[wn(t,e),wn(n,e)];for(let i of r){if(!pa(i))continue;let o;try{o=fa(i)}catch{continue}let s=ka(o);if(s===null)continue;let c=ha(s,o);if(!c.startsWith(".."))return{repoRoot:s,repoRelDir:c===""?"":c.split(ga).join("/")}}return null}a(_n,"resolveRepoRootForDir");function ka(e){try{let t=ua("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}}a(ka,"gitToplevelOf");function va(){return da({repoRoot:ie()})}a(va,"defaultEngineFactory");var Gf="https://mcp.maind.dev/mcp";async function Ea(e){let t=Date.now(),n;try{n=Yi(e)}catch(_){if(_ instanceof z)return process.stderr.write(`error: ${_.message}
|
|
800
800
|
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw _}if(n.help)return Xi(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,o=Sa.homedir();if(o.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
|
|
801
801
|
`),2;let s;if(n.projectRoot!==null)s=n.projectRoot;else{let _=await to(process.cwd());if(_.length===0)s=await eo(process.cwd());else if(_.length===1)s=_[0];else{let S=await ro(_,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.
|
|
802
802
|
`);for(let v of _)process.stderr.write(` candidate: ${v}
|
|
803
|
-
`);return 2}s=S}}let c=new Kt,l=(process.env.MAIND_MCP_URL??"").trim()||
|
|
803
|
+
`);return 2}s=S}}let c=new Kt,l=(process.env.MAIND_MCP_URL??"").trim()||Gf;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
|
|
804
804
|
`),process.stdout.write(`maind install \u2014 project root: ${s}
|
|
805
805
|
`),process.stdout.write(` \u2014 mcp endpoint: ${l}
|
|
806
806
|
|
|
807
|
-
`);let d=await
|
|
807
|
+
`);let d=await Do({bridgeVersion:N,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(c.add(d.result),d.result.status==="failed")return process.stderr.write(`
|
|
808
808
|
pairing failed: ${d.result.detail??"unknown"}
|
|
809
809
|
Skipping remaining steps.
|
|
810
810
|
`),c.print(process.stdout),2;let u=uo({projectRoot:s,homeDir:o,platform:process.platform,env:process.env}),p=co(u);if(p=lo(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.
|
|
811
811
|
`:`error: no client targets selected (did you skip all of them?)
|
|
812
|
-
`),c.print(process.stdout),2;for(let _ of p){let S=ao({mcpUrl:l,clientFamily:_.clientFamilyEnv}),v;_.kind==="json"?v=await go(_,S,n.dryRun):v=await yo(_,S,n.dryRun),c.add(v)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let _=await bo({projectRoot:s,homeDir:o},n.dryRun);for(let S of _)c.add(S)}let
|
|
812
|
+
`),c.print(process.stdout),2;for(let _ of p){let S=ao({mcpUrl:l,clientFamily:_.clientFamilyEnv}),v;_.kind==="json"?v=await go(_,S,n.dryRun):v=await yo(_,S,n.dryRun),c.add(v)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let _=await bo({projectRoot:s,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 So(f)),c.add(await xo(f)),c.add(await Ro(f)),c.add(await Ao(f)),c.add(await To(f)),c.add(await Eo(f)),c.add(await No({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let h=ya();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 Oo({enabled:n.telemetry||n.full,installerVersion:N,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:d.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let m=c.exitCode(),g=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
|
|
813
813
|
DRY RUN finished in ${g}s. No files were modified. Re-run without --dry-run to apply.
|
|
814
814
|
`):process.stdout.write(`
|
|
815
815
|
Finished in ${g}s. Restart your MCP client so it picks up the new server entry.
|
|
816
816
|
`);let b=Y({entryPath:X(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),y=b.fallbackReason===null?`${Ce(b)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${y}
|
|
817
|
-
`),
|
|
818
|
-
`),h}a(Ea,"runInstall");import{readFileSync as Uf}from"node:fs";import{join as xa}from"node:path";function kn(e){return e?Math.ceil(e.length/4):0}a(kn,"estimateTokens");var Ra=1e6,vn=class{static{a(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 Ta(e){try{let t=Uf(e,"utf8");return t.length>Ra?t.slice(0,Ra):t}catch{return""}}a(Ta,"readFileCapped");function Kf(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]}a(Kf,"distinctFilePaths");function Aa(e,t,n,r){try{let i=kn(n);if(e==="codebase_search"){let o=Kf(t);if(o.length===0)return 0;let s=0;for(let c of o)s+=kn(Ta(xa(r,c)));return Math.max(0,s-i)}if(e==="codebase_snippet"){let o=t?.filePath;if(typeof o!="string"||o.length===0)return 0;let s=kn(Ta(xa(r,o)));return Math.max(0,s-i)}return 0}catch{return 0}}a(Aa,"measureLocalToolSaved");Zr();import{createHash as dm}from"node:crypto";function En(e){return dm("sha256").update(e,"utf8").digest("hex")}a(En,"nodeKeyHash");var um=["module","class","interface","function","method","type_alias","enum","variable"],ei=[{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:um,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.",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.",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.'}}}},{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."}}}}],ic=new Set(ei.map(e=>e.name));function L(e){return typeof e=="string"&&e.length>0?e:void 0}a(L,"str");var pm=10;function fm(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,o=0;for(let s of e.history){let c=s.ownership?.commitsInWindow??s.lastCommits.length;c>=pm&&r++,c>i&&(i=c);for(let d of s.ownership?.topAuthors??[])n.add(d.email.toLowerCase()||d.name);let l=s.lastCommits[0]?.dateIso;if(l){let d=Date.parse(l);Number.isFinite(d)&&d>o&&(o=d)}}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}}a(fm,"aggregateHistoryContext");function Se(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}a(Se,"num");function nc(e){if(e===void 0)return{repoRoot:ie(),scanDirs:void 0};let t=_n(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}a(nc,"anchorRepo");function rc(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}.`}}a(rc,"dirNotFound");async function oc(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(s=>typeof s=="string"):void 0}),i=r.findings.filter(s=>s.status==="open").length,o=r.findings.filter(s=>s.status==="warn").length;return{ok:r.ok,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 u=_a(i);if(u===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 ke(u.repoRoot,u.repoRelPath,{minFiles:r}),m=p.namespace,f=a(g=>g===null?null:`${m?.prefix??""}${g}`,"full"),h=m===null?"no_opinion":p.taken?"taken":"free";return{ok:h==="free",mode:"proposed_path",verdict:h,reason:h==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:u.repoRoot,namespace:m===null?null:{dir:m.dir,prefix:m.prefix,file_count:m.fileCount},number:f(p.number),taken:h==="no_opinion"?null:p.taken,suggestion:f(p.suggestion),held_by:p.sightings.map(g=>({kind:g.kind,where:g.where,path:g.path})),hint:h==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${f(p.number)} is already held (see held_by). Create the file as ${f(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${f(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let o=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(o!==void 0&&o.length>0){let u=new Map,p=[];for(let S of o){let v=_n(S);if(v===null){p.push(S);continue}let E=u.get(v.repoRoot)??new Set;E.add(v.repoRelDir),u.set(v.repoRoot,E)}if(u.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let m=[],f=[],h=[],g=[];for(let[S,v]of u){let E=[...v],x=E.includes(""),A=await mt(S,{dirs:x?void 0:E,minFiles:r});m.push({repo_root:S,dirs:x?null:E}),f.push(...A.findings),h.push(...A.facts.namespaces.map(T=>({repo_root:S,dir:T.dir,prefix:T.prefix,file_count:T.fileCount}))),g.push(...A.facts.skipped)}let b=f.filter(S=>S.status==="open"),y=f.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:b.length===0,open_count:b.length,preexisting_count:y.length,findings:b,preexisting:y.map(S=>`${S.namespace.prefix}${S.number}`),namespaces:h,skipped:g,scanned:m,...p.length>0?{unresolved_dirs:p}:{},hint:(b.length===0?h.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${b.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 s=ie(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(u=>u.status==="open"),d=c.findings.filter(u=>u.status==="info");return{ok:c.ok,repo_root:s,open_count:l.length,preexisting_count:d.length,findings:l,preexisting:d.map(u=>`${u.namespace.prefix}${u.number}`),namespaces:c.facts.namespaces.map(u=>({dir:u.dir,prefix:u.prefix,file_count:u.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:L(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=a(p=>r.findings.filter(m=>m.status===p),"of"),o=i("open"),s=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let d="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.",u=o.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:s.length,preexisting_count:c.length,findings:[...o,...s],preexisting:c.map(p=>p.id),coverage_note:d,hint:(r.ok?"The declared entries agree.":u.length>0?`${u.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${o.length-u.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.`)+" "+d}}case"check_theme_class_drift":{let r=L(n.dir),i,o;if(r!==void 0){let l=_n(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=ie(),o=void 0;let s=Br(i,{dirs:o});return s.verdict==="no_opinion"?{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."}:{ok:s.ok,verdict:s.verdict,repo_root:i,token_count:s.tokenCount,namespace_count:s.namespaceCount,scanned_files:s.scannedFiles,findings:s.findings.map(l=>({file:l.file,class:l.klass,missing_token:l.token,namespace:l.namespace})),hint:(s.ok?`All house-namespace classes are covered (${s.tokenCount} tokens, ${s.namespaceCount} namespaces).`:`${s.findings.length} dead class(es): 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=nc(L(n.dir));if(r===null)return rc("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Jr(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 s=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:s.length,preexisting_count:c.length,findings:s,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(s.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.`:`${s.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=nc(L(n.dir));if(r===null)return rc("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=Qr(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 s=a(p=>i.findings.filter(m=>m.status===p),"of"),c=s("open"),l=s("warn"),d=s("info"),u=o.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:o,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:u,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" 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:Se(n.limit)})).map(o=>({...o,nodeKeyHash:En(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:Se(n.max_depth),limit:Se(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:En(r)}}case"codebase_map":return e.getArchitecture({topN:Se(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:L(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Se(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:En(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:Se(n.limit)}),i;if(n.include_history!==!1)try{i=fm(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:En(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:tc},...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:Se(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(o=>({path:o.path,last_commits:o.lastCommits.map(s=>({sha:s.sha,author_name:s.authorName,author_email:s.authorEmail,date_iso:s.dateIso,subject:s.subject})),ownership:o.ownership?{top_authors:o.ownership.topAuthors.map(s=>({name:s.name,email:s.email,commits:s.commits,last_date_iso:s.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}`)}}a(oc,"dispatchLocalTool");var xn=class{constructor(t=va,n=null,r=ie){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{a(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return ei}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&ic.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 s=await oc(this.getEngine(),i,o),c=JSON.stringify(s,null,2);return this.recordSavings(i,s,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(s){let c=s instanceof Error?s.message:String(s),l=ba(s)?`${wa} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(o=>o&&typeof o=="object"?o.name:void 0).filter(o=>typeof o=="string")),i=this.descriptors().filter(o=>!r.has(o.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=Aa(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};var mm="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function sc(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:mm}a(sc,"functionsOrigin");var hm="/mcp-client-metrics-ingest",gm=4e3,ym="codebase_search_tokens_saved";async function ac(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${sc()}${hm}`,n=new AbortController,r=setTimeout(()=>n.abort(),gm);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:ym,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)}
|
|
819
|
-
`),!1}finally{clearTimeout(r)}}a(ac,"postSavingsMetric");ri();
|
|
820
|
-
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,
|
|
821
|
-
`),process.exit(1)),n.apiKey}a(
|
|
822
|
-
`),process.exit(1)),e.apiKey}a(
|
|
823
|
-
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(
|
|
824
|
-
`),process.exit(0));let t=F(),n=await
|
|
825
|
-
`),n=await
|
|
826
|
-
`))}a(
|
|
817
|
+
`),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.
|
|
818
|
+
`),m}a(Ea,"runInstall");import{readFileSync as Bf}from"node:fs";import{join as xa}from"node:path";function kn(e){return e?Math.ceil(e.length/4):0}a(kn,"estimateTokens");var Ra=1e6,vn=class{static{a(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 Aa(e){try{let t=Bf(e,"utf8");return t.length>Ra?t.slice(0,Ra):t}catch{return""}}a(Aa,"readFileCapped");function Wf(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]}a(Wf,"distinctFilePaths");function Ta(e,t,n,r){try{let i=kn(n);if(e==="codebase_search"){let o=Wf(t);if(o.length===0)return 0;let s=0;for(let c of o)s+=kn(Aa(xa(r,c)));return Math.max(0,s-i)}if(e==="codebase_snippet"){let o=t?.filePath;if(typeof o!="string"||o.length===0)return 0;let s=kn(Aa(xa(r,o)));return Math.max(0,s-i)}return 0}catch{return 0}}a(Ta,"measureLocalToolSaved");Zr();import{createHash as fm}from"node:crypto";function En(e){return fm("sha256").update(e,"utf8").digest("hex")}a(En,"nodeKeyHash");var mm=["module","class","interface","function","method","type_alias","enum","variable"],ei=[{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:mm,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.",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.",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.'}}}},{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."}}}}],ic=new Set(ei.map(e=>e.name));function $(e){return typeof e=="string"&&e.length>0?e:void 0}a($,"str");var hm=10;function gm(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,o=0;for(let s of e.history){let c=s.ownership?.commitsInWindow??s.lastCommits.length;c>=hm&&r++,c>i&&(i=c);for(let d of s.ownership?.topAuthors??[])n.add(d.email.toLowerCase()||d.name);let l=s.lastCommits[0]?.dateIso;if(l){let d=Date.parse(l);Number.isFinite(d)&&d>o&&(o=d)}}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}}a(gm,"aggregateHistoryContext");function Se(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}a(Se,"num");function nc(e){if(e===void 0)return{repoRoot:ie(),scanDirs:void 0};let t=_n(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}a(nc,"anchorRepo");function rc(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}.`}}a(rc,"dirNotFound");async function oc(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(s=>typeof s=="string"):void 0}),i=r.findings.filter(s=>s.status==="open").length,o=r.findings.filter(s=>s.status==="warn").length;return{ok:r.ok,open_count:i,warn_count:o,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${o} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=$(n.for_path);if(i!==void 0){let u=_a(i);if(u===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 ke(u.repoRoot,u.repoRelPath,{minFiles:r}),f=p.namespace,h=a(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:u.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(u=>typeof u=="string"):void 0;if(o!==void 0&&o.length>0){let u=new Map,p=[];for(let S of o){let v=_n(S);if(v===null){p.push(S);continue}let E=u.get(v.repoRoot)??new Set;E.add(v.repoRelDir),u.set(v.repoRoot,E)}if(u.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 u){let E=[...v],x=E.includes(""),T=await mt(S,{dirs:x?void 0:E,minFiles:r});f.push({repo_root:S,dirs:x?null:E}),h.push(...T.findings),m.push(...T.facts.namespaces.map(A=>({repo_root:S,dir:A.dir,prefix:A.prefix,file_count:A.fileCount}))),g.push(...T.facts.skipped)}let b=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:b.length===0,open_count:b.length,preexisting_count:y.length,findings:b,preexisting:y.map(S=>`${S.namespace.prefix}${S.number}`),namespaces:m,skipped:g,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(b.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.":`${b.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 s=ie(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(u=>u.status==="open"),d=c.findings.filter(u=>u.status==="info");return{ok:c.ok,repo_root:s,open_count:l.length,preexisting_count:d.length,findings:l,preexisting:d.map(u=>`${u.namespace.prefix}${u.number}`),namespaces:c.facts.namespaces.map(u=>({dir:u.dir,prefix:u.prefix,file_count:u.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:$(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=a(p=>r.findings.filter(f=>f.status===p),"of"),o=i("open"),s=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let d="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.",u=o.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:s.length,preexisting_count:c.length,findings:[...o,...s],preexisting:c.map(p=>p.id),coverage_note:d,hint:(r.ok?"The declared entries agree.":u.length>0?`${u.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${o.length-u.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.`)+" "+d}}case"check_theme_class_drift":{let r=$(n.dir),i,o;if(r!==void 0){let l=_n(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=ie(),o=void 0;let s=Br(i,{dirs:o});return s.verdict==="no_opinion"?{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."}:{ok:s.ok,verdict:s.verdict,repo_root:i,token_count:s.tokenCount,namespace_count:s.namespaceCount,scanned_files:s.scannedFiles,findings:s.findings.map(l=>({file:l.file,class:l.klass,missing_token:l.token,namespace:l.namespace})),hint:(s.ok?`All house-namespace classes are covered (${s.tokenCount} tokens, ${s.namespaceCount} namespaces).`:`${s.findings.length} dead class(es): 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=nc($(n.dir));if(r===null)return rc("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Jr(r.repoRoot,{dirs:r.scanDirs,baseRef:$(n.base_ref),includeBaseline:n.include_baseline!==!1}),o="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let s=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:s.length,preexisting_count:c.length,findings:s,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(s.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.`:`${s.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=nc($(n.dir));if(r===null)return rc("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=Qr(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:$(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 s=a(p=>i.findings.filter(f=>f.status===p),"of"),c=s("open"),l=s("warn"),d=s("info"),u=o.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:o,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:u,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=$(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:$(n.kind),limit:Se(n.limit)})).map(o=>({...o,nodeKeyHash:En(o.nodeKey)}))}case"codebase_trace":{let r=$(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:i,maxDepth:Se(n.max_depth),limit:Se(n.limit)})}case"codebase_snippet":{let r=$(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await e.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:En(r)}}case"codebase_map":return e.getArchitecture({topN:Se(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:$(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Se(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:En(i.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:$(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Se(n.limit)}),i;if(n.include_history!==!1)try{i=gm(await e.fileHistory({since:$(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:En(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:tc},...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:$(n.since),limit:Se(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(o=>({path:o.path,last_commits:o.lastCommits.map(s=>({sha:s.sha,author_name:s.authorName,author_email:s.authorEmail,date_iso:s.dateIso,subject:s.subject})),ownership:o.ownership?{top_authors:o.ownership.topAuthors.map(s=>({name:s.name,email:s.email,commits:s.commits,last_date_iso:s.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}`)}}a(oc,"dispatchLocalTool");var xn=class{constructor(t=va,n=null,r=ie){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{a(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return ei}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&ic.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 s=await oc(this.getEngine(),i,o),c=JSON.stringify(s,null,2);return this.recordSavings(i,s,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(s){let c=s instanceof Error?s.message:String(s),l=ba(s)?`${wa} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(o=>o&&typeof o=="object"?o.name:void 0).filter(o=>typeof o=="string")),i=this.descriptors().filter(o=>!r.has(o.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=Ta(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};var ym="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function sc(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:ym}a(sc,"functionsOrigin");var bm="/mcp-client-metrics-ingest",wm=4e3,_m="codebase_search_tokens_saved";async function ac(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${sc()}${bm}`,n=new AbortController,r=setTimeout(()=>n.abort(),wm);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:_m,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)}
|
|
819
|
+
`),!1}finally{clearTimeout(r)}}a(ac,"postSavingsMetric");ri();An();In();import{execFile as oh}from"node:child_process";var sh=8,ah=32;function ch(e){return e.split(`
|
|
820
|
+
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,ah)}a(ch,"parsePorcelain");function lh(e,t=sh){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}a(lh,"condenseToDirs");async function Rc(e=dh){let t=await e();if(t===null)return null;let n=lh(ch(t));return n.length>0?n:null}a(Rc,"deriveWorkingPaths");async function dh(){return await new Promise(e=>{oh("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}a(dh,"defaultGitStatus");var Zy=1,eb=["on-session-start","on-tool-use","on-file-write","on-file-edit","sync-config","flush","status"];function tb(e){return eb.includes(e)}a(tb,"isHookSubcommand");var nb=6e4;async function rb(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==I()&&ge(e),e;let t=I();if(t!==null)return t;let n=await Ne(N);return n===null&&(process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
|
|
821
|
+
`),process.exit(1)),n.apiKey}a(rb,"ensureApiKey");async function ib(){Ie();let e=await Ne(N);return e===null&&(process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
|
|
822
|
+
`),process.exit(1)),e.apiKey}a(ib,"reauth");async function ob(){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),b=await Ea(g);process.exit(b)}if(e==="on-session-end"){let{runOnSessionEnd:m}=await Promise.resolve().then(()=>(gl(),hl));process.exit(await m())}if(e==="guard"){let m=process.argv.indexOf("guard"),{runGuard:g}=await Promise.resolve().then(()=>(xl(),El));process.exit(await g(process.argv.slice(m+1)))}if(e==="guard-inject"){let{runGuardInject:m}=await Promise.resolve().then(()=>(Pl(),Cl));process.exit(await m())}if(e==="guard-gate"){let{runGuardGate:m}=await Promise.resolve().then(()=>(Ll(),Fl));process.exit(await m())}if(e==="guard-stop"){let{runGuardStop:m}=await Promise.resolve().then(()=>(Hl(),jl));process.exit(await m())}if(e==="gateway"){let m=process.argv.indexOf("gateway"),{runGateway:g}=await Promise.resolve().then(()=>(Pd(),Cd));process.exit(await g(process.argv.slice(m+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:m}=await Promise.resolve().then(()=>(Oi(),Di));process.exit(await m())}if(e==="guard-cross-check"){let{runGuardCrossCheck:m}=await Promise.resolve().then(()=>(Oi(),Di));process.exit(await m())}if(e!==void 0&&tb(e)){let m=await Promise.resolve().then(()=>(gi(),pl)),g={"on-session-start":m.runOnSessionStart,"on-tool-use":m.runOnToolUse,"on-file-write":m.runOnFileWrite,"on-file-edit":m.runOnFileEdit,"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(N+`
|
|
823
|
+
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(sb(),process.exit(0)),process.argv.includes("--reauth")&&(Ie(),await Ne(N,process.stdout)===null&&process.exit(1),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
|
|
824
|
+
`),process.exit(0));let t=F(),n=await rb(),r=D(),o=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new vn:null,s=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new xn(void 0,o),c=`bridge-${Qy()}`,l=a(async()=>{if(!o)return;let m=o.takePending();m.tokens<=0||await ac({apiKey:n,deviceId:t,sessionId:c,tokensSaved:m.tokens,bridgeVersion:N})},"flushSavings"),d=o?setInterval(()=>{l()},nb):null;d?.unref();let u=null,p=new Rn({projectKey:r,identity:new Tn({projectKey:r}),postToolCall:a((m,g)=>u===null?Promise.reject(new Error("presence: no active forwarder")):u.postPresenceToolCall(m,g),"postToolCall"),deriveWorkingPaths:a(()=>Rc(),"deriveWorkingPaths"),snapshot:r!==null?bc({projectKey:r}):void 0}),f=p.isEnabled?setInterval(()=>{p.pollActivity()},lc):null;if(f?.unref(),p.isEnabled){let m=a(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 jt({apiKey:n,deviceId:t,bridgeVersion:N,projectKey:r,localRouter:s,presence:p});u=m;try{await m.run();return}catch(g){if(g instanceof nt&&h<Zy){h+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${g.message}; re-authorizing\u2026
|
|
825
|
+
`),n=await ib();continue}throw g}}}finally{d&&clearInterval(d),f&&clearInterval(f),await p.end(),await l()}}a(ob,"main");function sb(){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-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(`
|
|
826
|
+
`))}a(sb,"printHelp");ob().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
|
|
827
827
|
`),process.exit(1)});
|