@maind-dev/mcp-bridge 0.64.0 → 0.65.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 +140 -140
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -1,39 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var gs=Object.defineProperty;var s=(e,t)=>gs(e,"name",{value:t,configurable:!0});var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=(e,t)=>{for(var n in t)gs(e,n,{get:t[n],enumerable:!0})};function bs(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let o={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(o.toolName=c)}}return o}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function We(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 Mr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Fr(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function Lr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var $r=_(()=>{"use strict";s(bs,"parseFrame");s(We,"denyResult");s(Mr,"toolEvent");s(Fr,"policyEvent");s(Lr,"shaEvent")});import{execFileSync as
|
|
2
|
+
var gs=Object.defineProperty;var s=(e,t)=>gs(e,"name",{value:t,configurable:!0});var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=(e,t)=>{for(var n in t)gs(e,n,{get:t[n],enumerable:!0})};function bs(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let o={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(o.toolName=c)}}return o}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function We(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 Mr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Fr(e,t,n,r,i,o){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:o}}function Lr(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var $r=_(()=>{"use strict";s(bs,"parseFrame");s(We,"denyResult");s(Mr,"toolEvent");s(Fr,"policyEvent");s(Lr,"shaEvent")});import{execFileSync as ks}from"node:child_process";function vs(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=of}function sf(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 tf){let a=r[o];typeof a=="string"&&_s.test(a)&&i.push({field:o,sha:a})}for(let[o,a]of nf){let c=r[o];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&_s.test(l)&&i.push({field:`${o}.${a}`,sha:l})}return i}function af(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,ws);for(let i=ws;i>=rf;i--){let o=r.slice(0,i),a=t(o);if(a!==null&&a.startsWith(o))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function Ve(e,t){return e.verdict==="fabricated"?[`${t?"DENIED":"WARNING"}: the ${e.field} you passed (${e.sha}) does not exist in this repository,`,`but its prefix resolves to a real commit (${e.matchedPrefixOf}).`,"That combination cannot come from an unfetched object \u2014 it comes from completing an abbreviated hash.","Read the full hash instead of reconstructing it: `git rev-parse HEAD`, `git rev-parse <ref>`,","or `gh pr view <n> --json mergeCommit --jq .mergeCommit.oid`.",t?"The call was not forwarded.":"The call was forwarded \u2014 the record will carry an unverifiable hash."].join(" "):[`NOTE: the ${e.field} you passed (${e.sha}) could not be resolved in this repository.`,"That is often harmless \u2014 a fresh squash-merge commit, an unfetched branch, or a different repo in this workspace.","If you reconstructed it from an abbreviated hash, read the full one instead (`git rev-parse`, `gh --json`).","The call was forwarded."].join(" ")}function Ss(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"])delete e[t];return e}function un(e=process.cwd()){try{let n=ks("git",["rev-parse","--show-toplevel"],{cwd:e,env:Ss(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function cf(e){return t=>{try{let r=ks("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Ss(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function pn(e,t){if(t===null)return[];let n=sf(e);if(n.length===0)return[];let r=cf(t),i=[];for(let{field:o,sha:a}of n){let c=af(a,r);c.verdict!=="proven"&&i.push({...c,field:o})}return i}var tf,nf,_s,rf,ws,of,jr=_(()=>{"use strict";tf=["commit_sha","base_sha","head_sha"],nf=[["diff_stats","head_sha"],["diff_stats","base_sha"]],_s=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,rf=7,ws=12,of=10;s(vs,"isDenyGrade");s(sf,"extractShaArgs");s(af,"classifySha");s(Ve,"shaFindingText");s(Ss,"cleanGitEnv");s(un,"resolveRepoRootForSha");s(cf,"gitShaResolver");s(pn,"inspectLineForShas")});import{execFileSync as lf}from"node:child_process";import{createHash as df}from"node:crypto";import{mkdirSync as uf,readFileSync as pf,renameSync as ff,writeFileSync as mf}from"node:fs";import{dirname as hf,join as Es}from"node:path";function ae(e=process.cwd()){try{let t=lf("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function fn(e){return df("sha256").update(e).digest("hex").slice(0,16)}function mn(e){return Es(e,gf)}function xs(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function Rs(e,t,n,r=new Date().toISOString()){try{if(!xs(n))return;let i={version:Hr,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},o=mn(e);uf(hf(o),{recursive:!0});let a=`${o}.${process.pid}.tmp`;mf(a,JSON.stringify(i,null,2),"utf8"),ff(a,o)}catch{}}function Ts(e,t){try{let n=pf(mn(e),"utf8"),r=JSON.parse(n);return r.version!==Hr||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!xs(r.result)?null:{version:Hr,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function As(e,t,n=new Date){let r=yf(t.cached_at,n),i=t.result.instructions??"",o={...t.result,instructions:`${r}
|
|
3
3
|
|
|
4
|
-
${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:o})}function
|
|
5
|
-
`,{encoding:"utf8",mode:384});try{
|
|
6
|
-
`,{encoding:"utf8",mode:384});try{Is(n,384)}catch{}}function O(){let e=Br();if(!_n(e))return null;let t=As(e,"utf8").trim();return t.length>0?t:null}function At(){let e=Br();_n(e)&&Kr(e,"",{encoding:"utf8",mode:384})}function Ns(){try{return`mcp-bridge-${Nf()}`}catch{return"mcp-bridge"}}function wn(e){return{os:`${Gr()} ${Pf()}`,ide:"mcp-bridge",ext_version:e,device_id:U()}}var Df,Mf,Ff,B=_(()=>{"use strict";s(Tt,"configDir");s(Cs,"ensureDir");Df="device-id",Mf="api-key";s(U,"ensureDeviceId");Ff=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s(Lf,"isUuid");s(Br,"apiKeyPath");s(Ee,"writeApiKey");s(O,"readApiKey");s(At,"clearApiKey");s(Ns,"bridgeLabel");s(wn,"clientMeta")});var P,xe=_(()=>{"use strict";P="0.64.0"});import{execFileSync as Vf}from"node:child_process";import{createHash as qf}from"node:crypto";function Jf(e){return qf("sha256").update(e).digest("hex")}function zf(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 Yf(e){let t=zf(e);return t?Jf(t):null}function D(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&Xf.test(e))return e;let t;try{t=Vf("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Yf(t):null}var Xf,ge=_(()=>{"use strict";s(Jf,"sha256Hex");s(zf,"normalizeRemoteUrl");s(Yf,"projectKeyFromRemote");Xf=/^[a-f0-9]{64}$/;s(D,"computeProjectKey")});import Zf from"node:path";import{fileURLToPath as em}from"node:url";function tm(e,t=Zf.sep){return e.split(t).includes("_npx")}function ee(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",Gs,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):tm(e.entryPath,e.sep)?n("bridge is running from the npx cache (install it globally to pin a path)"):e.nodePath?{command:e.nodePath,args:[e.entryPath,...t],env:e.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},fallbackReason:null}:n("node executable path unavailable")}function te(){try{let e=em(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function ze(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Us(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Us(n)).join(" ")}function vn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Gs)}function Sn(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Us(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Gs,Ye=_(()=>{"use strict";Gs="@maind-dev/mcp-bridge";s(tm,"isEphemeralEntry");s(ee,"resolveBridgeLaunch");s(te,"currentBridgeEntry");s(ze,"launchToShellCommand");s(vn,"isNpxForm");s(Sn,"isLegacyHookForm");s(Us,"shellQuote")});import*as M from"node:fs/promises";import*as En from"node:path";async function G(e){try{return await M.readFile(e,"utf8")}catch(t){if(rm(t))return null;throw t}}async function Wr(e){await M.mkdir(e,{recursive:!0})}async function F(e,t,n){let r=En.dirname(e);await Wr(r);let i=En.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await M.writeFile(i,t,{encoding:"utf8",mode:n});try{await M.rename(i,e)}catch(o){if(im(o))try{await M.copyFile(i,e),await M.unlink(i).catch(()=>{}),n!==void 0&&await M.chmod(e,n).catch(()=>{});return}catch(a){throw await M.unlink(i).catch(()=>{}),a}throw await M.unlink(i).catch(()=>{}),o}}async function Js(e,t){let n=await G(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function rm(e){return zs(e)&&e.code==="ENOENT"}function im(e){return!zs(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function zs(e){return typeof e=="object"&&e!==null&&"code"in e}var ce=_(()=>{"use strict";s(G,"readFileSafe");s(Wr,"ensureDir");s(F,"atomicWriteFile");s(Js,"hasLinePrefix");s(rm,"isNoEnt");s(im,"isWindowsRenameFailure");s(zs,"isNodeError")});import{existsSync as km}from"node:fs";import*as ta from"node:path";function Pt(e,t={},n=zr){let r=t.fileExists??km,i=t.expectedCommand??vm,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Jr(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=Sm(o,a.event,a.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let u=` Replace its command with: ${i(a.subcommand)}`;if(Sn(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+u};if(vn(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+u};let d=Em(l);return d!==null&&!r(d)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${d}, which does not exist \u2014 the hook fails silently on every run.`+u}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function Yr(e){return e.some(t=>t.status!=="ok")}function Tn(e){return e.some(t=>t.remedy==="run-install")}function vm(e){return ze(ee({entryPath:te(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function Sm(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Jr(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Jr(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function Em(e){for(let t of xm(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return ta.isAbsolute(t)?t:null;return null}function xm(e){let t=[],n="",r=!1;for(let i of e){if(i==="'"){r=!r;continue}if(!r&&/\s/.test(i)){n.length>0&&t.push(n),n="";continue}n+=i}return n.length>0&&t.push(n),t}function Jr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zr,Rn,Ot=_(()=>{"use strict";Ye();zr=[{event:"SessionStart",subcommand:"on-session-start",label:"SessionStart hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-session-start' \u2014 opens a tracked session so duration and tool-call counts can be measured. Writes only to ~/.maind/state.json; nothing leaves the machine here."},{event:"PreToolUse",subcommand:"on-tool-use",label:"PreToolUse hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-tool-use' before every tool call \u2014 counts calls, and warns you on stderr when the session's token usage crosses your handoff thresholds (ADR-039). Only the tool NAME is read, never its arguments."},{event:"PreToolUse",subcommand:"on-file-write",label:"PreToolUse write-guard hook",timeout:5,matcher:"Write",consentDescription:"It runs 'maind-mcp-bridge on-file-write' before the Write tool creates a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents, never any other tool's arguments \u2014 to check whether a numbered filename (ADR-262-\u2026, 0001-\u2026, RFC-12-\u2026) would claim a number a sibling branch or worktree already holds, and blocks that one Write while naming the next free number (ADR-263). Runs entirely on this machine (git + fs); nothing is uploaded. This is a SEPARATE hook from on-tool-use precisely because it reads an argument, which that one promises not to."},{event:"PreToolUse",subcommand:"on-file-edit",label:"PreToolUse edit-guard hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-file-edit' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares it LOCALLY against the cached peer view from this machine's own presence announces (~/.maind/presence/): when another of your sessions holds a claim or works on the same directory, it INFORMS the agent with who/where/how-fresh. The path never leaves the machine; the hook never blocks a tool call (advisory only, ADR-277). This is a SEPARATE hook from on-file-write because that one's consent covers Write alone and may deny; this one covers Edit+Write and never does."},{event:"PreToolUse",subcommand:"on-repo-health",label:"PreToolUse repo-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-repo-health' before the Edit and Write tools, and before those only \u2014 at most ONCE per session and repository, not on every call. It reads the target file PATH (never the file's contents) to find which repository you are editing, then inspects THAT repository with git and the filesystem: is a machine-local tooling file present in the main checkout but missing in this worktree, were dependencies never installed here, is a build older than its source, are you mid-rebase, on a detached HEAD, editing the shared base tree, or are checked-in git hooks not actually wired? Everything stays on this machine; no network call, and no file contents are read or stored. It only ever adds a note for the model and NEVER blocks a tool call. Separately consented from the other Edit/Write hooks because it inspects the repository, not just the path."},{event:"PostToolUse",subcommand:"on-write-health",label:"PostToolUse write-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-write-health' AFTER the Edit and Write tools, and after those only. It reads the target file PATH to decide which checks that path makes relevant, and then \u2014 this is the wider promise, which is why it is consented separately \u2014 READS THE REPOSITORY'S TRACKED SOURCE FILES FROM DISK to run them: is a registry still consistent with the design artefact it implements (only if this repo declares such a contract in .maind/spec-contracts.json), does a Tailwind class point at a theme token that does not exist (only if this repo declares theme tokens), does a new Supabase migration leave default grants in place (only if this repo has migrations). A repository without those things stays silent. File contents are read, parsed and discarded; nothing is stored and nothing is uploaded. Each finding is reported to the model at most ONCE per session, only for findings THIS branch introduces, and the hook can never block or undo an edit \u2014 PostToolUse fires after the tool has already run."},{event:"Stop",subcommand:"on-session-end",label:"Stop hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end, and flushes the session's Tier-3 counters. Gated by Tier-3 consent server-side."},{event:"Stop",subcommand:"on-index-refresh",label:"Stop index-refresh hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-index-refresh' at the end of a turn, and refreshes this repository's local code index so codebase search, trace, map, history and review answer from the current tree instead of a stale snapshot. This one READS YOUR SOURCE FILES \u2014 the ones git reports as changed \u2014 parses them, and writes symbol names and line spans to .maind/code-index.sqlite inside the repository. That is a wider promise than the other hooks make, which is why it is consented separately. Everything stays on this machine; nothing is uploaded, and no file contents are stored. It returns immediately (the work runs detached), holds one run per repository at a time, and only refreshes an index that already exists \u2014 the first build stays an explicit 'codebase_index' call."}],Rn=[{event:"SessionStart",subcommand:"guard-inject",label:"Guard inject hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-inject' when a session starts (ADR-284 guard). UNLIKE every other hook, this one talks to the maind server: it fetches your session briefing from mcp.maind.dev \u2014 sending your API key, device id, project key, and the client family 'claude-code'; never file contents, never paths \u2014 and injects the result into the session context, so the briefing no longer depends on the model remembering to ask. Cache-first (~12h), so most session starts add no network call. Inactive (exit 0, no output) while guard mode is off."},{event:"PreToolUse",subcommand:"guard-gate",label:"Guard gate hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-gate' before the Edit and Write tools, and before those only. It reads the tool NAME and the session id \u2014 never the tool's arguments, never file contents \u2014 and checks LOCALLY whether this session has been briefed (injection or a maind consultation call). Warn mode (default) adds one reminder line for the model and never blocks; block mode (explicit opt-in via 'guard mode block') may DENY an un-briefed edit, naming the reason and a logged override command. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-stop",label:"Guard stop hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-stop' when the session tries to finish. Only with the strict stop-gate enabled ('guard_stop_gate': true \u2014 off by default) and edits made without a review_changes run, it blocks the FIRST stop attempt with a reason so the review can happen; it never blocks twice. Reads only local state; nothing leaves the machine. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-cross-observe",label:"Guard cross-session observe hook",timeout:5,matcher:"Read|Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-observe' after the Read, Edit and Write tools, and after those only. It reads the target file PATH \u2014 never the file's contents \u2014 stats its modification time, and records it as this session's baseline in ~/.maind/cross-session/ (local file, TTL-pruned). That baseline is what lets the check hook detect when a parallel session, an editor, or git changes a file under you. Nothing leaves the machine. Inactive while guard mode is off."},{event:"PreToolUse",subcommand:"guard-cross-check",label:"Guard cross-session check hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-check' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares the file's current modification time against the baseline this session last observed. If the file changed outside the session (parallel session, editor, git checkout/pull), warn mode adds one advisory telling the model to re-read and reconcile; block mode ('guard mode block') DENIES that one edit with the same instruction. Runs entirely on this machine. Inactive while guard mode is off."}];s(Pt,"inspectHookWiring");s(Yr,"hasWiringDrift");s(Tn,"needsInstallRun");s(vm,"defaultExpectedCommand");s(Sm,"findCommand");s(Em,"extractScriptPath");s(xm,"tokenize");s(Jr,"isObject")});import*as Zr from"node:path";import*as ra from"node:readline";async function ia(e,t){let n=Zr.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let i;try{i=await G(n)}catch(f){return{target:r,action:"merge",status:"failed",detail:`read: ${Xr(f)}`}}let o,a="create";if(i===null||i.trim().length===0)o={};else{a="merge";try{let f=JSON.parse(i);if(!Qr(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: ${Xr(f)}`}}}let c=Tm(o,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:a==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await Am(e.out,`
|
|
4
|
+
${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:o})}function yf(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${bf(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function bf(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i} minute${i===1?"":"s"} ago`;let o=Math.floor(i/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let a=Math.floor(o/24);return`${a} day${a===1?"":"s"} ago`}var Hr,gf,qe=_(()=>{"use strict";Hr=1,gf=Es(".maind","conventions-cache.json");s(ae,"resolveRepoRoot");s(fn,"keyFingerprint");s(mn,"cachePath");s(xs,"hasInstructions");s(Rs,"writeConventionsCache");s(Ts,"readConventionsCache");s(As,"buildCachedInitializeResponse");s(yf,"fallbackMarker");s(bf,"relativeAge")});import{existsSync as _n,mkdirSync as Cf,readFileSync as Is,writeFileSync as Kr,chmodSync as Cs}from"node:fs";import{homedir as Nf,hostname as Pf,platform as Gr,release as Df}from"node:os";import{randomUUID as Of}from"node:crypto";import{join as Se}from"node:path";function Tt(){let e=Nf(),t=process.env;if(Gr()==="darwin")return Se(e,"Library","Application Support","maind");if(Gr()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:Se(e,"AppData","Roaming");return Se(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:Se(e,".config");return Se(n,"maind")}function Ns(e){_n(e)||Cf(e,{recursive:!0,mode:448})}function U(){let e=Tt();Ns(e);let t=Se(e,Mf);if(_n(t)){let r=Is(t,"utf8").trim();if($f(r))return r}let n=Of();Kr(t,n+`
|
|
5
|
+
`,{encoding:"utf8",mode:384});try{Cs(t,384)}catch{}return n}function $f(e){return Lf.test(e)}function Br(){return Se(Tt(),Ff)}function Ee(e){let t=Tt();Ns(t);let n=Br();Kr(n,e+`
|
|
6
|
+
`,{encoding:"utf8",mode:384});try{Cs(n,384)}catch{}}function D(){let e=Br();if(!_n(e))return null;let t=Is(e,"utf8").trim();return t.length>0?t:null}function At(){let e=Br();_n(e)&&Kr(e,"",{encoding:"utf8",mode:384})}function Ps(){try{return`mcp-bridge-${Pf()}`}catch{return"mcp-bridge"}}function wn(e){return{os:`${Gr()} ${Df()}`,ide:"mcp-bridge",ext_version:e,device_id:U()}}var Mf,Ff,Lf,B=_(()=>{"use strict";s(Tt,"configDir");s(Ns,"ensureDir");Mf="device-id",Ff="api-key";s(U,"ensureDeviceId");Lf=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;s($f,"isUuid");s(Br,"apiKeyPath");s(Ee,"writeApiKey");s(D,"readApiKey");s(At,"clearApiKey");s(Ps,"bridgeLabel");s(wn,"clientMeta")});var P,xe=_(()=>{"use strict";P="0.65.0"});import{execFileSync as qf}from"node:child_process";import{createHash as Jf}from"node:crypto";function zf(e){return Jf("sha256").update(e).digest("hex")}function Yf(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function Xf(e){let t=Yf(e);return t?zf(t):null}function O(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&Qf.test(e))return e;let t;try{t=qf("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Xf(t):null}var Qf,ge=_(()=>{"use strict";s(zf,"sha256Hex");s(Yf,"normalizeRemoteUrl");s(Xf,"projectKeyFromRemote");Qf=/^[a-f0-9]{64}$/;s(O,"computeProjectKey")});import em from"node:path";import{fileURLToPath as tm}from"node:url";function nm(e,t=em.sep){return e.split(t).includes("_npx")}function ee(e){let t=e.extraArgs??[],n=s(r=>({command:"npx",args:["-y",Ks,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):nm(e.entryPath,e.sep)?n("bridge is running from the npx cache (install it globally to pin a path)"):e.nodePath?{command:e.nodePath,args:[e.entryPath,...t],env:e.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},fallbackReason:null}:n("node executable path unavailable")}function te(){try{let e=tm(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function ze(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Gs(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Gs(n)).join(" ")}function vn(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Ks)}function Sn(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Gs(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Ks,Ye=_(()=>{"use strict";Ks="@maind-dev/mcp-bridge";s(nm,"isEphemeralEntry");s(ee,"resolveBridgeLaunch");s(te,"currentBridgeEntry");s(ze,"launchToShellCommand");s(vn,"isNpxForm");s(Sn,"isLegacyHookForm");s(Gs,"shellQuote")});import*as M from"node:fs/promises";import*as En from"node:path";async function G(e){try{return await M.readFile(e,"utf8")}catch(t){if(im(t))return null;throw t}}async function Wr(e){await M.mkdir(e,{recursive:!0})}async function F(e,t,n){let r=En.dirname(e);await Wr(r);let i=En.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await M.writeFile(i,t,{encoding:"utf8",mode:n});try{await M.rename(i,e)}catch(o){if(om(o))try{await M.copyFile(i,e),await M.unlink(i).catch(()=>{}),n!==void 0&&await M.chmod(e,n).catch(()=>{});return}catch(a){throw await M.unlink(i).catch(()=>{}),a}throw await M.unlink(i).catch(()=>{}),o}}async function zs(e,t){let n=await G(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function im(e){return Ys(e)&&e.code==="ENOENT"}function om(e){return!Ys(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function Ys(e){return typeof e=="object"&&e!==null&&"code"in e}var ce=_(()=>{"use strict";s(G,"readFileSafe");s(Wr,"ensureDir");s(F,"atomicWriteFile");s(zs,"hasLinePrefix");s(im,"isNoEnt");s(om,"isWindowsRenameFailure");s(Ys,"isNodeError")});import{existsSync as vm}from"node:fs";import*as na from"node:path";function Pt(e,t={},n=zr){let r=t.fileExists??vm,i=t.expectedCommand??Sm,o={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Jr(a)&&(o=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=Em(o,a.event,a.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let u=` Replace its command with: ${i(a.subcommand)}`;if(Sn(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+u};if(vn(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+u};let d=xm(l);return d!==null&&!r(d)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${d}, which does not exist \u2014 the hook fails silently on every run.`+u}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function Yr(e){return e.some(t=>t.status!=="ok")}function Tn(e){return e.some(t=>t.remedy==="run-install")}function Sm(e){return ze(ee({entryPath:te(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function Em(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Jr(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Jr(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function xm(e){for(let t of Rm(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return na.isAbsolute(t)?t:null;return null}function Rm(e){let t=[],n="",r=!1;for(let i of e){if(i==="'"){r=!r;continue}if(!r&&/\s/.test(i)){n.length>0&&t.push(n),n="";continue}n+=i}return n.length>0&&t.push(n),t}function Jr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zr,Rn,Dt=_(()=>{"use strict";Ye();zr=[{event:"SessionStart",subcommand:"on-session-start",label:"SessionStart hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-session-start' \u2014 opens a tracked session so duration and tool-call counts can be measured. Writes only to ~/.maind/state.json; nothing leaves the machine here."},{event:"PreToolUse",subcommand:"on-tool-use",label:"PreToolUse hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-tool-use' before every tool call \u2014 counts calls, and warns you on stderr when the session's token usage crosses your handoff thresholds (ADR-039). Only the tool NAME is read, never its arguments."},{event:"PreToolUse",subcommand:"on-file-write",label:"PreToolUse write-guard hook",timeout:5,matcher:"Write",consentDescription:"It runs 'maind-mcp-bridge on-file-write' before the Write tool creates a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents, never any other tool's arguments \u2014 to check whether a numbered filename (ADR-262-\u2026, 0001-\u2026, RFC-12-\u2026) would claim a number a sibling branch or worktree already holds, and blocks that one Write while naming the next free number (ADR-263). Runs entirely on this machine (git + fs); nothing is uploaded. This is a SEPARATE hook from on-tool-use precisely because it reads an argument, which that one promises not to."},{event:"PreToolUse",subcommand:"on-file-edit",label:"PreToolUse edit-guard hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-file-edit' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares it LOCALLY against the cached peer view from this machine's own presence announces (~/.maind/presence/): when another of your sessions holds a claim or works on the same directory, it INFORMS the agent with who/where/how-fresh. The path never leaves the machine; the hook never blocks a tool call (advisory only, ADR-277). This is a SEPARATE hook from on-file-write because that one's consent covers Write alone and may deny; this one covers Edit+Write and never does."},{event:"PreToolUse",subcommand:"on-repo-health",label:"PreToolUse repo-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-repo-health' before the Edit and Write tools, and before those only \u2014 at most ONCE per session and repository, not on every call. It reads the target file PATH (never the file's contents) to find which repository you are editing, then inspects THAT repository with git and the filesystem: is a machine-local tooling file present in the main checkout but missing in this worktree, were dependencies never installed here, is a build older than its source, are you mid-rebase, on a detached HEAD, editing the shared base tree, or are checked-in git hooks not actually wired? Everything stays on this machine; no network call, and no file contents are read or stored. It only ever adds a note for the model and NEVER blocks a tool call. Separately consented from the other Edit/Write hooks because it inspects the repository, not just the path."},{event:"PostToolUse",subcommand:"on-write-health",label:"PostToolUse write-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-write-health' AFTER the Edit and Write tools, and after those only. It reads the target file PATH to decide which checks that path makes relevant, and then \u2014 this is the wider promise, which is why it is consented separately \u2014 READS THE REPOSITORY'S TRACKED SOURCE FILES FROM DISK to run them: is a registry still consistent with the design artefact it implements (only if this repo declares such a contract in .maind/spec-contracts.json), does a Tailwind class point at a theme token that does not exist (only if this repo declares theme tokens), does a new Supabase migration leave default grants in place (only if this repo has migrations). A repository without those things stays silent. File contents are read, parsed and discarded; nothing is stored and nothing is uploaded. Each finding is reported to the model at most ONCE per session, only for findings THIS branch introduces, and the hook can never block or undo an edit \u2014 PostToolUse fires after the tool has already run."},{event:"Stop",subcommand:"on-session-end",label:"Stop hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end, and flushes the session's Tier-3 counters. Gated by Tier-3 consent server-side."},{event:"Stop",subcommand:"on-index-refresh",label:"Stop index-refresh hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-index-refresh' at the end of a turn, and refreshes this repository's local code index so codebase search, trace, map, history and review answer from the current tree instead of a stale snapshot. This one READS YOUR SOURCE FILES \u2014 the ones git reports as changed \u2014 parses them, and writes symbol names and line spans to .maind/code-index.sqlite inside the repository. That is a wider promise than the other hooks make, which is why it is consented separately. Everything stays on this machine; nothing is uploaded, and no file contents are stored. It returns immediately (the work runs detached), holds one run per repository at a time, and only refreshes an index that already exists \u2014 the first build stays an explicit 'codebase_index' call."}],Rn=[{event:"SessionStart",subcommand:"guard-inject",label:"Guard inject hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-inject' when a session starts (ADR-284 guard). UNLIKE every other hook, this one talks to the maind server: it fetches your session briefing from mcp.maind.dev \u2014 sending your API key, device id, project key, and the client family 'claude-code'; never file contents, never paths \u2014 and injects the result into the session context, so the briefing no longer depends on the model remembering to ask. Cache-first (~12h), so most session starts add no network call. Inactive (exit 0, no output) while guard mode is off."},{event:"PreToolUse",subcommand:"guard-gate",label:"Guard gate hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-gate' before the Edit and Write tools, and before those only. It reads the tool NAME and the session id \u2014 never the tool's arguments, never file contents \u2014 and checks LOCALLY whether this session has been briefed (injection or a maind consultation call). Warn mode (default) adds one reminder line for the model and never blocks; block mode (explicit opt-in via 'guard mode block') may DENY an un-briefed edit, naming the reason and a logged override command. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-stop",label:"Guard stop hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-stop' when the session tries to finish. Only with the strict stop-gate enabled ('guard_stop_gate': true \u2014 off by default) and edits made without a review_changes run, it blocks the FIRST stop attempt with a reason so the review can happen; it never blocks twice. Reads only local state; nothing leaves the machine. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-cross-observe",label:"Guard cross-session observe hook",timeout:5,matcher:"Read|Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-observe' after the Read, Edit and Write tools, and after those only. It reads the target file PATH \u2014 never the file's contents \u2014 stats its modification time, and records it as this session's baseline in ~/.maind/cross-session/ (local file, TTL-pruned). That baseline is what lets the check hook detect when a parallel session, an editor, or git changes a file under you. Nothing leaves the machine. Inactive while guard mode is off."},{event:"PreToolUse",subcommand:"guard-cross-check",label:"Guard cross-session check hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-check' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares the file's current modification time against the baseline this session last observed. If the file changed outside the session (parallel session, editor, git checkout/pull), warn mode adds one advisory telling the model to re-read and reconcile; block mode ('guard mode block') DENIES that one edit with the same instruction. Runs entirely on this machine. Inactive while guard mode is off."}];s(Pt,"inspectHookWiring");s(Yr,"hasWiringDrift");s(Tn,"needsInstallRun");s(Sm,"defaultExpectedCommand");s(Em,"findCommand");s(xm,"extractScriptPath");s(Rm,"tokenize");s(Jr,"isObject")});import*as Zr from"node:path";import*as ia from"node:readline";async function oa(e,t){let n=Zr.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let i;try{i=await G(n)}catch(f){return{target:r,action:"merge",status:"failed",detail:`read: ${Xr(f)}`}}let o,a="create";if(i===null||i.trim().length===0)o={};else{a="merge";try{let f=JSON.parse(i);if(!Qr(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: ${Xr(f)}`}}}let c=Am(o,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:a==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await Im(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}]},u=o.hooks?.[t.event]??[],d={...o,hooks:{...o.hooks??{},[t.event]:[...u,l]}},p=JSON.stringify(d,null,2)+`
|
|
10
|
-
`;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:n};try{await F(n,p,384)}catch(f){return{target:r,action:"merge",status:"failed",detail:`write: ${Xr(f)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function
|
|
11
|
-
`,1)[0]??"").trim().slice(0,200)}function
|
|
12
|
-
`).slice(0,1e3)}var
|
|
13
|
-
`));let n=[];return
|
|
14
|
-
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let u=l[0][0],d
|
|
15
|
-
`)){if(l.length<4)continue;let u=l[0],d=l[1];if(u==="D"||d==="D")continue;let p=l.slice(3),f=p.indexOf(" -> ");f>=0&&(p=p.slice(f+4)),p
|
|
16
|
-
`)){if(u.length<4||u[0]!=="?")continue;let d=u.slice(3);d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),!(!d||a.has(d))&&a.set(d,{path:d,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:a,coverage:c}}function
|
|
17
|
-
`)){if(l.startsWith("diff --git ")){c(),o=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){o=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let d=l.slice(4).trim();if(d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),d.startsWith("b/")&&(d=d.slice(2)),d==="/dev/null")continue;r={path:d,status:a?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let u=
|
|
18
|
-
`),y=Ya(g[0]??"");if(!y)continue;let b=g.slice(1).filter(w=>w.trim().length>0).length;m.push({sha:y.sha,dateIso:y.dateIso,authorName:y.authorName,subject:y.subject,filesTouched:b})}u={sinceInput:n.since,sinceResolved:d,commits:m.slice(0,Kn),truncated:m.length>Kn}}return{history:l,regression:u,ownershipWindowCommits:o,pathsTruncated:a.length>ui}}var yh,bh,Xa,ui,Kn,Ja,pi=_(()=>{"use strict";q();yh="",bh="\0",Xa=200,ui=50,Kn=100,Ja="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";s(_h,"clamp");s(za,"splitRecords");s(Ya,"parseHistoryRecord");s(wh,"aggregateOwnership");s(Qa,"readFileHistory")});import{execFileSync as kh}from"node:child_process";import{readdirSync as vh,statSync as Za}from"node:fs";import{isAbsolute as Sh,join as fi,relative as Eh,resolve as xh}from"node:path";function Th(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function Ah(e,t){try{let n=kh("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 Ih(e){let t;try{t=vh(e)}catch{return null}for(let n of t.filter(Th))try{let r=Za(fi(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function Ch(e){try{return Za(e).isDirectory()}catch{return!1}}function Nh(e,t){let n=Eh(e,t);return!n||n.startsWith("..")?t:n}function mi(e){let t=Rh.filter(c=>Ch(fi(e,c))),n=Ah(e,"core.hooksPath"),r=n?Sh(n)?n:xh(e,n):fi(e,".git","hooks"),i=Nh(e,r),o=Ih(r);if(o===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?o===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:a,hookDirs:t,hooksPath:n,effectiveDir:i}}function hi(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 Rh,gi=_(()=>{"use strict";Rh=[".githooks",".husky"];s(Th,"isRealHook");s(Ah,"gitConfig");s(Ih,"hasExecutableHook");s(Ch,"isDir");s(Nh,"displayPath");s(mi,"resolveHookState");s(hi,"describeHookState")});import{posix as ec}from"node:path";function et(e){let t=Ph.exec(e);return t?t[1]:null}function ue(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Ae(e,t){let n=S(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=s(o=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||o===c||o.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let o of n.split("\0").filter(Boolean)){if(!r(o))continue;let a=ec.basename(o),c=et(a);if(c===null)continue;let l=ec.dirname(o),u=i.get(l)??[];u.push({path:o,name:a,version:c}),i.set(l,u)}return[...i.entries()].map(([o,a])=>({dir:o,files:a.sort((c,l)=>ue(c.version,l.version))})).sort((o,a)=>o.dir.localeCompare(a.dir))}function tc(e){let t=S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var Ph,Ft=_(()=>{"use strict";q();Ph=/^(\d+)_.+\.sql$/;s(et,"parseMigrationVersion");s(ue,"compareVersions");s(Ae,"discoverSupabaseProjects");s(tc,"resolveDefaultBranch")});import{execFileSync as Oh}from"node:child_process";import{existsSync as H,readFileSync as we,readdirSync as Bn,statSync as bi}from"node:fs";import{posix as x}from"node:path";function Lh(e,t){let n=(()=>{let i=S(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=x.dirname(e);for(let i=0;i<8&&r&&r!==x.dirname(r);i++){if(H(x.join(r,".git"))){let o=(()=>{let c=S(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&o!=null&&wi(n,o))){let c=$h(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=x.dirname(r)}return null}function $h(e,t){let n=[];for(let r of Mh){let i;try{i=Bn(x.join(e,r),{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>o.name)}catch{continue}for(let o of i){let a=`${r}/${o}`,c=x.join(e,a),l=x.join(t,a);try{let u=bi(c),d=bi(l);if(!d.isFile())continue;if(u.size!==d.size){n.push(a);continue}if(u.size>Fh)continue;we(c).equals(we(l))||n.push(a)}catch{continue}}}return n.sort()}function cc(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let a=e.upstream.split("/").slice(1).join("/");a&&a!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;if(r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`}),e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let a=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${a} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let a=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${a.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${ki}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let a=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${a.map(c=>c.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:a.map(c=>`${c.install} (in ${x.dirname(c.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:a,diverging:c}=e.toolCopyDrift,l=c.slice(0,3).join(", "),u=c.length>3?` (+${c.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${a} ships ${l}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${c[0]}\` from this repo root), not via a path into ${a}.`})}if(e.stalePackageBuilds.length>0){let a=e.stalePackageBuilds,c=s(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),l=a.every(u=>u.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:a.some(u=>u.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${a.map(c).join(", ")}: src/ is newer than the built ${[...new Set(a.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${l}`,hint:`Rebuild: pnpm --filter ./${a[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let o=jh(e.hooks);return o&&t.push(o),Hh(t)}function jh(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:hi(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 Hh(e){return[...e].sort((t,n)=>nc[t.status]-nc[n.status]||t.id.localeCompare(n.id))}function lc(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function pe(e){let t=e?.trim();return t||null}function Uh(e){let t=pe(S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Gh(e){let t=pe(S(e,["rev-parse","--git-dir"]));if(!t)return null;let n=x.isAbsolute(t)?t:x.join(e,t);return H(x.join(n,"rebase-merge"))||H(x.join(n,"rebase-apply"))?"rebase":H(x.join(n,"MERGE_HEAD"))?"merge":H(x.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function Kh(e){let t=[],n=null,r=s(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
|
|
19
|
-
`))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function
|
|
20
|
-
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function
|
|
21
|
-
`).filter(A=>A.trim().length>0).length,h=
|
|
22
|
-
`).map(T=>T.trim()).filter(T=>T.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:u,ahead:d,behind:p,uncommitted:m,detachedHead:i,inProgressOp:h,isSharedMainTree:w,otherWorktrees:v,worktreeParity:k,toolCopyDrift:E,stalePackageBuilds:
|
|
23
|
-
`)){let o=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(o)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(o);a?t.push(a[1]):o.trim().length>0&&!/^\s/.test(o)&&(r=!1)}}}else{let r=x.join(e,"package.json");if(H(r)){let i=JSON.parse(we(r,"utf8")),o=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(o)&&t.push(...o.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function
|
|
24
|
-
`).filter(Boolean):[]}function
|
|
25
|
-
`,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}function Ut(e){return e==='"'||e==="'"||e==="`"}function Yn(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function Vn(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let o=e[i];if(Ut(o)){i=Jn(e,i);continue}if(Yn(e,i)){i=zn(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function
|
|
26
|
-
`:i==="r"?"\r":i==="t"?" ":i)}function
|
|
27
|
-
specification: ${h.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let u of n)c.has(u.key)||o("extra","warn",u.key,`${u.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let u of new Set([...a.keys(),...c.keys()])){if(
|
|
28
|
-
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:d});l.sort((d,p)=>
|
|
29
|
-
`;)n++;continue}if(i==="/"&&o==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],u=e.indexOf(l,n+l.length);n=u===-1?r:u+l.length,t+=" ";continue}}let a=(i==="E"||i==="e")&&o==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||a){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function X(e){let t=[],n="",r=!1,i=!1,o=s(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){o();continue}n+=l}o();let a=t.filter(c=>c.length>0);return a.length===0||a.length>2?null:a.length===2?{schema:a[0],name:a[1]}:{schema:"public",name:a[0]}}function fe(e){let t=[],n=0,r="";for(let i of e){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}function
|
|
30
|
-
`).filter(Boolean)){let[p,...f]=d.split(" ");p.startsWith("A")?a.add(f[0]):p.startsWith("R")?(c.push(f[0]),a.add(f[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(f[0])}let l=[],u=new Set(c);for(let{ref:d,content:p}of n)!a.has(d.path)&&!u.has(d.path)&&l.push({name:d.name,version:d.version,content:p});for(let d of c){let p=
|
|
10
|
+
`;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:n};try{await F(n,p,384)}catch(f){return{target:r,action:"merge",status:"failed",detail:`write: ${Xr(f)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function sa(e){let t=Zr.join(e.homeDir,ra);return oa(e,{event:"SessionStart",command:`cat ${t}`,timeout:5,matchPattern:/maind-session-start-reminder\.md/,targetKey:"hook:~/.claude/settings.json",skipDetail:s(()=>"SessionStart hook already references the reminder file","skipDetail"),consentDescription:`It 'cat's ${ra} into every new Claude Code session.`})}function Tm(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function ei(e,t){let n=e.launch??ee({entryPath:te(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=ze(n);return oa(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:Tm(t),skipDetail:s(i=>{let o=`${t.label} already runs maind ${t.subcommand}`;return Sn(i)?`${o}, but via the retired @maind/claude-code-hook \u2014 the bridge now owns that subcommand and that package is not published. Replace its command with: ${r}`:vn(i)?`${o}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:o},"skipDetail"),consentDescription:t.consentDescription})}async function aa(e){let t=[];for(let n of zr)t.push(await ei(e,n));return t}function Am(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Qr(i))continue;let o=i.hooks;if(Array.isArray(o))for(let a of o){if(!Qr(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function Im(e,t){e.write(t);let n=ia.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 Qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xr(e){return e instanceof Error?e.message:String(e)}var ra,ti=_(()=>{"use strict";ce();Ye();Dt();ra=".claude/maind-session-start-reminder.md";s(oa,"mergeClaudeHook");s(sa,"mergeSessionStartHook");s(Tm,"targetKeyFor");s(ei,"mergeSubcommandHook");s(aa,"mergeAllSubcommandHooks");s(Am,"findExistingHookCommand");s(Im,"promptYesNo");s(Qr,"isObject");s(Xr,"errMessage")});import{existsSync as Cm,readFileSync as Nm}from"node:fs";import{join as Pm}from"node:path";function de(){return Pm(Tt(),"config.json")}function ne(){try{let e=de();if(!Cm(e))return null;let t=JSON.parse(Nm(e,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r={};return typeof n.auto_announce=="boolean"&&(r.auto_announce=n.auto_announce),typeof n.machine_label=="string"&&(r.machine_label=n.machine_label),typeof n.auto_working_paths=="boolean"&&(r.auto_working_paths=n.auto_working_paths),(n.guard_mode==="off"||n.guard_mode==="warn"||n.guard_mode==="block")&&(r.guard_mode=n.guard_mode),typeof n.guard_stop_gate=="boolean"&&(r.guard_stop_gate=n.guard_stop_gate),(n.gateway_mode==="off"||n.gateway_mode==="warn"||n.gateway_mode==="enforce")&&(r.gateway_mode=n.gateway_mode),typeof n.gateway_attest=="boolean"&&(r.gateway_attest=n.gateway_attest),(n.gateway_sha_proof==="off"||n.gateway_sha_proof==="warn"||n.gateway_sha_proof==="enforce")&&(r.gateway_sha_proof=n.gateway_sha_proof),r}catch{return null}}var Xe=_(()=>{"use strict";B();s(de,"bridgeConfigPath");s(ne,"readBridgeConfig")});import{execFileSync as Hm}from"node:child_process";import{createHash as Um}from"node:crypto";function ni(e){return Um("sha256").update(e).digest("hex")}function Gm(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 Km(e){let t=Gm(e);return t?ni(t):null}function Wm(e){return typeof e=="string"&&Bm.test(e)}function ha(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(Wm(t))return t;let n;try{n=Hm("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?Km(n):null}var Bm,ri=_(()=>{"use strict";s(ni,"sha256Hex");s(Gm,"normalizeRemoteUrl");s(Km,"projectKeyFromRemote");Bm=/^[a-f0-9]{64}$/;s(Wm,"isProjectKey");s(ha,"computeProjectKey")});function An(e){return`${e}#<module>`}function In(e,t,n){return`${e}#${t}:${n}`}var Ot=_(()=>{"use strict";s(An,"moduleKey");s(In,"symbolKey")});function Cn(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}function ii(e){return e.toLowerCase().endsWith(".d.ts")}var Nn=_(()=>{"use strict";s(Cn,"languageForPath");s(ii,"isSkippablePath")});function Pn(){return{nodes:[],edges:[],refs:[],imports:[]}}function _e(e){return e+1}function Dn(e){return(e.text.split(`
|
|
11
|
+
`,1)[0]??"").trim().slice(0,200)}function Vm(e){if(!e)return null;switch(e.type){case"identifier":case"property_identifier":case"type_identifier":return e.text;case"member_expression":return e.childForFieldName("property")?.text??null;case"attribute":return e.childForFieldName("attribute")?.text??null;default:return null}}function qm(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=Vm(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function Qe(e,t,n,r){for(let i of qm(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}var On=_(()=>{"use strict";s(Pn,"newResult");s(_e,"line1");s(Dn,"signatureOf");s(Vm,"calleeName");s(qm,"collectCallTargets");s(Qe,"addCallRefs")});function ya(e,t){let n=Pn();for(let r of e.namedChildren)Jm(r,t,n);return n}function ba(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function Jm(e,t,n){let r=ba(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??Ym(r);o&&n.imports.push({fromModuleKey:t.moduleKey,specifier:o});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let o=Mn(r,t,i,i,"function");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&Qe(n,o.nodeKey,a,ga);return}case"class_definition":zm(r,t,n);return;case"expression_statement":{let o=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(o&&o.type==="identifier"){let a=Mn(r,t,o.text,o.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function zm(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Mn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let o=e.childForFieldName("superclasses");if(o){for(let c of o.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=ba(c);if(l.type!=="function_definition")continue;let u=l.childForFieldName("name")?.text;if(!u)continue;let d=`${r}.${u}`,p=Mn(l,t,u,d,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=l.childForFieldName("body");f&&Qe(n,p.nodeKey,f,ga)}}function Mn(e,t,n,r,i){return{nodeKey:In(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:_e(e.startPosition.row),endLine:_e(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Dn(e),doc:null}}function Ym(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var ga,_a=_(()=>{"use strict";Ot();On();ga="call";s(ya,"extractPython");s(ba,"unwrapDecorated");s(Jm,"handleTopLevel");s(zm,"addClass");s(Mn,"makeNode");s(Ym,"firstDottedName")});function va(e,t){let n=Pn();for(let r of e.namedChildren)Qm(r,t,n);return n}function Xm(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function Qm(e,t,n){let r=Xm(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:eh(i)});return}case"function_declaration":case"generator_function_declaration":{wa(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{Zm(r,t,n);return}case"interface_declaration":oi(r,t,n,"interface");return;case"type_alias_declaration":oi(r,t,n,"type_alias");return;case"enum_declaration":oi(r,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let i of r.namedChildren){if(i.type!=="variable_declarator")continue;let o=i.childForFieldName("name");if(!o||o.type!=="identifier")continue;let a=i.childForFieldName("value"),c=a?.type==="arrow_function"||a?.type==="function_expression"||a?.type==="function";wa(i,t,n,c?"function":"variable",o,a)}return}default:return}}function wa(e,t,n,r,i,o){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=Fn(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let u=o??e.childForFieldName("body")??e;r==="function"&&u&&Qe(n,l.nodeKey,u,ka)}function oi(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=Fn(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}function Zm(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Fn(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let a of e.descendantsOfType("class_heritage"))for(let c of a.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let u of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text});for(let u of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text})}let o=e.childForFieldName("body");if(o)for(let a of o.namedChildren){if(a.type!=="method_definition")continue;let c=a.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,u=Fn(a,t,c,l,"method");n.nodes.push(u),n.edges.push({srcKey:i.nodeKey,dstKey:u.nodeKey,kind:"contains"});let d=a.childForFieldName("body");d&&Qe(n,u.nodeKey,d,ka)}}function Fn(e,t,n,r,i){return{nodeKey:In(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:_e(e.startPosition.row),endLine:_e(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Dn(e),doc:null}}function eh(e){return e.replace(/^["'`]|["'`]$/g,"")}var ka,Sa=_(()=>{"use strict";Ot();On();ka="call_expression";s(va,"extractTypescript");s(Xm,"unwrapExport");s(Qm,"handleTopLevel");s(wa,"addFunctionLike");s(oi,"addSimpleNamed");s(Zm,"addClass");s(Fn,"makeNode");s(eh,"stripQuotes")});import{createRequire as th}from"node:module";import{join as nh}from"node:path";function Ra(e,t){return t?nh(t,Ea[e]):th(import.meta.url).resolve(`tree-sitter-wasms/out/${Ea[e]}`)}var Ea,xa,Ta=_(()=>{"use strict";Ea={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},xa="tree-sitter.wasm";s(Ra,"grammarPath")});import{join as rh}from"node:path";import si from"web-tree-sitter";var ih,Ln,Aa=_(()=>{"use strict";Ot();Nn();_a();Sa();On();Ta();ih=["typescript","tsx","javascript","python"],Ln=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await si.init(this.assetDir?{locateFile:s(t=>rh(this.assetDir,t||xa),"locateFile")}:void 0),this.parser=new si,this.initialized=!0)}supports(t){return ih.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let o=i.parse(n);if(!o)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[]};let a=o.rootNode,c=An(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:_e(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:c},d=r==="python"?ya(a,u):va(a,u);return o.delete(),{filePath:t,language:r,nodes:[l,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await si.Language.load(Ra(t,this.assetDir)),this.grammars.set(t,n)),n}}});function Ia(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
|
|
12
|
+
`).slice(0,1e3)}var Ca=_(()=>{"use strict";s(Ia,"nodeEmbedText")});var ai,ci=_(()=>{"use strict";ai=["function","method","class","interface","enum","type_alias"]});function Na(e,t){let n=Math.min(e.length,t.length),r=0,i=0,o=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,i+=c*c,o+=l*l}return i===0||o===0?0:r/(Math.sqrt(i)*Math.sqrt(o))}var Pa=_(()=>{"use strict";s(Na,"cosineSimilarity")});import{posix as li}from"node:path";function Da(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!oh.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 Oa(e,t){let n=new Set,r=[],i=new Set,o=s((a,c,l)=>{if(a===c)return;let u=`${a}\0${c}\0${l}`;n.has(u)||(n.add(u),r.push({srcKey:a,dstKey:c,kind:l}),i.add(a))},"push");for(let a of e.edges)o(a.srcKey,a.dstKey,a.kind);for(let a of e.nodes)i.add(a.nodeKey);for(let a of e.refs){let c=t.nameToKeys.get(a.targetName);!c||c.length!==1||o(a.fromKey,c[0],a.kind)}for(let a of e.imports){let c=sh(e.filePath,a.specifier,t.files);c&&o(a.fromModuleKey,An(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}function sh(e,t,n){if(!t.startsWith("."))return null;let r=li.normalize(li.join(li.dirname(e),t)),i=[],o=$n.some(c=>r.endsWith(c));o&&i.push(r);let a=/\.(js|jsx|mjs|cjs)$/.exec(r);if(a){let c=r.slice(0,-a[0].length);for(let l of $n)i.push(c+l)}if(!o){for(let c of $n)i.push(r+c);for(let c of $n)i.push(`${r}/index${c}`)}for(let c of i)if(n.has(c))return c;return null}var oh,$n,Ma=_(()=>{"use strict";Ot();oh=new Set(["function","method","class","interface","enum","type_alias"]),$n=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];s(Da,"buildResolutionIndex");s(Oa,"resolveFileEdges");s(sh,"resolveImportTarget")});import{execFileSync as ah}from"node:child_process";import{createHash as ch}from"node:crypto";import{readdirSync as lh,statSync as dh}from"node:fs";import{posix as ja,sep as Fa}from"node:path";function S(e,t){try{return ah("git",[...uh,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function ph(e){return Fa==="/"?e:e.split(Fa).join("/")}function jn(e){let t=[];for(let n of e){let r=ph(n).trim();if(!r||ii(r))continue;let i=Cn(r);i&&t.push({path:r,language:i})}return t}function Ha(e){return jn(e)}function Ua(e){let t=Ze(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return jn(t.split(`
|
|
13
|
+
`));let n=[];return Ga(e,"",n),jn(n)}function Ga(e,t,n){let r;try{r=lh(ja.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&La.has(i.name)||La.has(i.name))continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?Ga(e,o,n):i.isFile()&&n.push(o)}}function di(e,t){let r=S(e,["merge-base",t,"HEAD"])?.trim();return r&&r.length>0?r:t}function Hn(e,t={}){if(Mt(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?di(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let o=Ze(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of o.split(`
|
|
14
|
+
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let u=l[0][0],d=$a((l.length>=3?l[l.length-1]:l[1]).trim());d&&(u==="A"||u==="C"?a.set(d,"added"):u==="R"?a.set(d,"renamed"):a.set(d,"modified"))}if(n){let c=Ze(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
|
|
15
|
+
`)){if(l.length<4)continue;let u=l[0],d=l[1];if(u==="D"||d==="D")continue;let p=l.slice(3),f=p.indexOf(" -> ");f>=0&&(p=p.slice(f+4)),p=$a(p),!(!p||a.has(p))&&(u==="?"||u==="A"||d==="A"?a.set(p,"added"):u==="R"?a.set(p,"renamed"):a.set(p,"modified"))}}return a}function $a(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Ka(e,t={}){let n=Hn(e,t);return n===null?null:jn(n.keys())}function Ba(e,t){try{let n=dh(ja.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Un(e){return ch("sha256").update(e).digest("hex")}function Mt(e){return Ze(e,["rev-parse","HEAD"])?.trim()??null}function Gn(e,t){return Ze(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function Wa(e){let t=Ze(e,["status","--porcelain","-uall"]);return t!==null&&t.trim().length>0}var La,uh,Ze,q=_(()=>{"use strict";Nn();La=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),uh=["-c","diff.renames=true","-c","core.quotePath=false"];s(S,"runGit");Ze=S;s(ph,"toPosix");s(jn,"classify");s(Ha,"classifyPaths");s(Ua,"discoverSourceFiles");s(Ga,"walk");s(di,"resolveDiffBase");s(Hn,"enumerateChangedPaths");s($a,"unquote");s(Ka,"changedSourceFiles");s(Ba,"statFile");s(Un,"hashContent");s(Mt,"headCommit");s(Gn,"resolveCommitSha");s(Wa,"isWorktreeDirty")});function qa(e,t={}){if(S(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?di(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let o=S(e,i);if(o===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(o,"utf8")>fh?c="none":yh(o,a,()=>{c="partial"}),n){let l=S(e,["status","--porcelain","-uall"])??"";for(let u of l.split(`
|
|
16
|
+
`)){if(u.length<4||u[0]!=="?")continue;let d=u.slice(3);d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),!(!d||a.has(d))&&a.set(d,{path:d,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:a,coverage:c}}function yh(e,t,n){let r=null,i=0,o=!1,a=!1,c=s(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
|
|
17
|
+
`)){if(l.startsWith("diff --git ")){c(),o=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){o=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let d=l.slice(4).trim();if(d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1)),d.startsWith("b/")&&(d=d.slice(2)),d==="/dev/null")continue;r={path:d,status:a?"added":o?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let u=gh.exec(l);if(u){if(i++,i>mh){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let d=Number(u[1]),p=u[2]===void 0?1:Number(u[2]);p>0?r.addedRanges.push({start:d,end:d+p-1}):r.deletionPoints.push(d);continue}l.startsWith("+")&&!l.startsWith("+++")&&!r.degraded&&r.addedLines.length<hh&&r.addedLines.push(l.slice(1))}c()}var fh,mh,hh,Va,gh,Ja=_(()=>{"use strict";q();fh=16*1024*1024,mh=500,hh=4e3,Va=256*1024,gh=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;s(qa,"changedHunks");s(yh,"parseUnifiedDiff")});function wh(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function Ya(e){return e.split(bh).filter(t=>t.trim().length>0)}function Xa(e){let[t,n,r,i,o]=e.replace(/\n+$/,"").split(_h);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:o??""}}function kh(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 Za(e,t,n={}){let r=wh(n.limit,20,100),i=n.includeOwnership!==!1,o=Math.max(r,Qa),a=t.map(d=>d.trim()).filter(d=>d.length>0&&!d.startsWith(":")),c=a.slice(0,ui),l=[];for(let d of c){let p=S(e,["log","-n",String(o),za,"--",d]),f=p===null?[]:Ya(p).map(Xa).filter(m=>m!==null);l.push({path:d,lastCommits:f.slice(0,r),ownership:i?{topAuthors:kh(f),commitsInWindow:f.length}:null})}let u=null;if(n.since){let d=Gn(e,n.since),p=d!==null?[`${d}..HEAD`]:[`--since=${n.since}`],f=S(e,["log",...p,"-n",String(Kn+1),za,"--name-only","--",...c]),m=[];if(f!==null)for(let h of Ya(f)){let g=h.split(`
|
|
18
|
+
`),y=Xa(g[0]??"");if(!y)continue;let b=g.slice(1).filter(w=>w.trim().length>0).length;m.push({sha:y.sha,dateIso:y.dateIso,authorName:y.authorName,subject:y.subject,filesTouched:b})}u={sinceInput:n.since,sinceResolved:d,commits:m.slice(0,Kn),truncated:m.length>Kn}}return{history:l,regression:u,ownershipWindowCommits:o,pathsTruncated:a.length>ui}}var bh,_h,Qa,ui,Kn,za,pi=_(()=>{"use strict";q();bh="",_h="\0",Qa=200,ui=50,Kn=100,za="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";s(wh,"clamp");s(Ya,"splitRecords");s(Xa,"parseHistoryRecord");s(kh,"aggregateOwnership");s(Za,"readFileHistory")});import{execFileSync as vh}from"node:child_process";import{readdirSync as Sh,statSync as ec}from"node:fs";import{isAbsolute as Eh,join as fi,relative as xh,resolve as Rh}from"node:path";function Ah(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function Ih(e,t){try{let n=vh("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 Ch(e){let t;try{t=Sh(e)}catch{return null}for(let n of t.filter(Ah))try{let r=ec(fi(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function Nh(e){try{return ec(e).isDirectory()}catch{return!1}}function Ph(e,t){let n=xh(e,t);return!n||n.startsWith("..")?t:n}function mi(e){let t=Th.filter(c=>Nh(fi(e,c))),n=Ih(e,"core.hooksPath"),r=n?Eh(n)?n:Rh(e,n):fi(e,".git","hooks"),i=Ph(e,r),o=Ch(r);if(o===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?o===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:a,hookDirs:t,hooksPath:n,effectiveDir:i}}function hi(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 Th,gi=_(()=>{"use strict";Th=[".githooks",".husky"];s(Ah,"isRealHook");s(Ih,"gitConfig");s(Ch,"hasExecutableHook");s(Nh,"isDir");s(Ph,"displayPath");s(mi,"resolveHookState");s(hi,"describeHookState")});import{posix as tc}from"node:path";function et(e){let t=Dh.exec(e);return t?t[1]:null}function ue(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function Ae(e,t){let n=S(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=s(o=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||o===c||o.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let o of n.split("\0").filter(Boolean)){if(!r(o))continue;let a=tc.basename(o),c=et(a);if(c===null)continue;let l=tc.dirname(o),u=i.get(l)??[];u.push({path:o,name:a,version:c}),i.set(l,u)}return[...i.entries()].map(([o,a])=>({dir:o,files:a.sort((c,l)=>ue(c.version,l.version))})).sort((o,a)=>o.dir.localeCompare(a.dir))}function nc(e){let t=S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var Dh,Ft=_(()=>{"use strict";q();Dh=/^(\d+)_.+\.sql$/;s(et,"parseMigrationVersion");s(ue,"compareVersions");s(Ae,"discoverSupabaseProjects");s(nc,"resolveDefaultBranch")});import{execFileSync as Oh}from"node:child_process";import{existsSync as H,readFileSync as we,readdirSync as Bn,statSync as bi}from"node:fs";import{posix as x}from"node:path";function $h(e,t){let n=(()=>{let i=S(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=x.dirname(e);for(let i=0;i<8&&r&&r!==x.dirname(r);i++){if(H(x.join(r,".git"))){let o=(()=>{let c=S(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&o!=null&&wi(n,o))){let c=jh(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=x.dirname(r)}return null}function jh(e,t){let n=[];for(let r of Fh){let i;try{i=Bn(x.join(e,r),{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>o.name)}catch{continue}for(let o of i){let a=`${r}/${o}`,c=x.join(e,a),l=x.join(t,a);try{let u=bi(c),d=bi(l);if(!d.isFile())continue;if(u.size!==d.size){n.push(a);continue}if(u.size>Lh)continue;we(c).equals(we(l))||n.push(a)}catch{continue}}}return n.sort()}function lc(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let a=e.upstream.split("/").slice(1).join("/");a&&a!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;if(r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`}),e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let a=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${a} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let a=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${a.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${ki}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let a=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${a.map(c=>c.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:a.map(c=>`${c.install} (in ${x.dirname(c.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:a,diverging:c}=e.toolCopyDrift,l=c.slice(0,3).join(", "),u=c.length>3?` (+${c.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${a} ships ${l}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${c[0]}\` from this repo root), not via a path into ${a}.`})}if(e.stalePackageBuilds.length>0){let a=e.stalePackageBuilds,c=s(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),l=a.every(u=>u.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:a.some(u=>u.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${a.map(c).join(", ")}: src/ is newer than the built ${[...new Set(a.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${l}`,hint:`Rebuild: pnpm --filter ./${a[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let o=Hh(e.hooks);return o&&t.push(o),Uh(t)}function Hh(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:hi(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 Uh(e){return[...e].sort((t,n)=>rc[t.status]-rc[n.status]||t.id.localeCompare(n.id))}function dc(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function pe(e){let t=e?.trim();return t||null}function Gh(e){let t=pe(S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Kh(e){let t=pe(S(e,["rev-parse","--git-dir"]));if(!t)return null;let n=x.isAbsolute(t)?t:x.join(e,t);return H(x.join(n,"rebase-merge"))||H(x.join(n,"rebase-apply"))?"rebase":H(x.join(n,"MERGE_HEAD"))?"merge":H(x.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function Bh(e){let t=[],n=null,r=s(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
|
|
19
|
+
`))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function Wh(e){let t=x.join(e,ki);if(!H(t))return[];try{return we(t,"utf8").split(`
|
|
20
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function Vh(e){try{return Ae(e).map(t=>x.join(x.dirname(t.dir),"config.toml"))}catch{return[]}}function qh(e){let t=S(e,["ls-files","-z","--",...Mh]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=cc[x.basename(r)];if(i===void 0)continue;let o=x.dirname(r);if(!Jh(e,o))continue;let a=o==="."?"node_modules":x.join(o,"node_modules");n.has(a)||n.set(a,{dir:a,install:i})}return[...n.values()]}function Jh(e,t){return t==="."?!0:_i(e,t)}function _i(e,t){if(H(x.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(we(x.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function uc(e,t={}){if(pe(S(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,branch:null,defaultBranch:null,upstream:null,headMatchesUpstream:null,remoteTrackingExists:null,ahead:null,behind:null,uncommitted:0,detachedHead:!1,inProgressOp:null,isSharedMainTree:!1,otherWorktrees:0,worktreeParity:null,toolCopyDrift:null,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=pe(S(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",o=i?null:r,a=Gh(e),c=pe(S(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,u=null;if(c){let A=pe(S(e,["rev-parse","HEAD"])),T=pe(S(e,["rev-parse","@{u}"]));l=A!=null&&T!=null?A===T:null,u=S(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let d=null,p=null;if(a){let A=pe(S(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(A){let[T,j]=A.split(/\s+/).map(N=>Number.parseInt(N,10));Number.isFinite(T)&&(p=T),Number.isFinite(j)&&(d=j)}}let m=(S(e,["status","--porcelain"])??"").split(`
|
|
21
|
+
`).filter(A=>A.trim().length>0).length,h=Kh(e),g=pe(S(e,["rev-parse","--show-toplevel"]))??e,y=Bh(S(e,["worktree","list","--porcelain"])??""),b=y[0]?.path??null,w=b!=null&&wi(b,g),v=Math.max(0,y.length-1),k=null;if(b&&!wi(b,g)){let A=s(j=>H(x.join(b,j))&&!H(x.join(g,j)),"here"),T=[...ac,...Vh(g),...Wh(g),...t.probePaths??[]];k={mainWorktreePath:b,currentWorktreePath:g,missing:[...new Set(T.filter(A))],missingDeps:qh(g).filter(j=>A(j.dir))}}let E=$h(g,e),R=t.includeRelease===!1?null:tg(e,o),I=[];return a&&(I=(S(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
|
|
22
|
+
`).map(T=>T.trim()).filter(T=>T.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:u,ahead:d,behind:p,uncommitted:m,detachedHead:i,inProgressOp:h,isSharedMainTree:w,otherWorktrees:v,worktreeParity:k,toolCopyDrift:E,stalePackageBuilds:pc(g),release:R,unmergedMigrations:I,hooks:mi(e)}}function wi(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function Xh(e){let t=new Set;_i(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<oc;){let i=n.pop();if(i===void 0)break;if(i.depth>=Yh)continue;let o;try{o=Bn(x.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=i.rel==="."?a.name:x.join(i.rel,a.name);if(r+=1,r>=oc)break;_i(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function Qh(e){let t=[];try{let n=x.join(e,"pnpm-workspace.yaml");if(H(n)){let r=!1;for(let i of we(n,"utf8").split(`
|
|
23
|
+
`)){let o=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(o)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(o);a?t.push(a[1]):o.trim().length>0&&!/^\s/.test(o)&&(r=!1)}}}else{let r=x.join(e,"package.json");if(H(r)){let i=JSON.parse(we(r,"utf8")),o=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(o)&&t.push(...o.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function Zh(e){let t=[];for(let n of Xh(e)){let r=n==="."?e:x.join(e,n),i=s(o=>n==="."?o:x.join(n,o),"prefix");for(let o of Qh(r)){if(t.length>=yi)break;if(!(o.startsWith("!")||o.includes("**")))try{if(o.endsWith("/*")){let a=o.slice(0,-2),c=x.join(r,a);if(!H(c))continue;for(let l of Bn(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(x.join(a,l.name))),t.length>=yi)break}else o.includes("*")||t.push(i(o))}catch{}}}return t.slice(0,yi)}function sc(e){let t=null,n=0,r=[e];for(;r.length>0&&n<ic;){let i=r.pop();if(i===void 0)break;let o;try{o=Bn(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=x.join(i,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=bi(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=ic)break}}}return t}function eg(e,t){let n=new Set;for(let r of t)try{let i=x.join(e,r,"package.json");if(!H(i))continue;let o=JSON.parse(we(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=o[a];if(!(c===null||typeof c!="object"))for(let[l,u]of Object.entries(c))typeof u=="string"&&u.startsWith("workspace:")&&n.add(l)}}catch{}return n}function pc(e){let t=[],n=Zh(e),r=eg(e,n);for(let i of n)try{let o=x.join(e,i,"package.json");if(!H(o))continue;let a=JSON.parse(we(o,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(b=>{if(typeof b!="string")return null;let w=b.replace(/^\.\//,"").split("/")[0];return w==="build"||w==="dist"?w:null},"builtSeg"),l=c(a.types??a.typings),u=c(a.main),d=l??u;if(d===null)continue;let p=l!==null&&u!==null?"both":l!==null?"types":"runtime",f=x.join(e,i,"src"),m=x.join(e,i,d);if(!H(f)||!H(m))continue;let h=sc(f),g=sc(m);if(h===null||g===null)continue;let y=h-g;y>zh&&t.push({packageDir:i,buildDir:d,srcNewerByMs:Math.round(y),impact:p})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}function tg(e,t){if(!t)return null;let n=ng(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 ng(e,t){try{return Oh("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function Lt(e,t={}){let n=await uc(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=lc(n),i=dc(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var ac,ki,cc,Mh,Fh,Lh,rc,zh,yi,ic,Yh,oc,vi=_(()=>{"use strict";gi();q();Ft();ac=["supabase/config.toml","supabase/.temp",".env"],ki=".maind/worktree-requirements",cc={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},Mh=Object.keys(cc).flatMap(e=>[e,"*/"+e]),Fh=["scripts"],Lh=512*1024;s($h,"gatherToolCopyDrift");s(jh,"compareToolDirs");s(lc,"computeDivergence");s(Hh,"computeHookFinding");rc={open:0,warn:1,info:2,passed:3};s(Uh,"sortFindings");s(dc,"isHealthy");s(pe,"trimOrNull");s(Gh,"resolveDefaultBranch");s(Kh,"detectInProgressOp");s(Bh,"parseWorktrees");s(Wh,"readWorktreeRequirements");s(Vh,"discoverSupabaseConfigProbes");s(qh,"discoverDependencyDirs");s(Jh,"isWorkspaceRoot");s(_i,"hasWorkspaceMarkers");s(uc,"gatherRepoHealthFacts");s(wi,"samePath");zh=2e3,yi=64,ic=4e3,Yh=3,oc=400;s(Xh,"findWorkspaceRoots");s(Qh,"workspacePatternsAt");s(Zh,"listWorkspacePackageDirs");s(sc,"newestMtimeUnder");s(eg,"consumedWorkspaceNames");s(pc,"gatherStalePackageBuilds");s(tg,"gatherReleaseFact");s(ng,"runGh");s(Lt,"checkDivergence")});import{existsSync as Si,readdirSync as fc}from"node:fs";import{posix as re}from"node:path";function xi(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Ei)}function hc(e,t={}){let n=t.minFiles??Ri;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??mc)}function nt(e){return`${e.dir}#${e.prefix}`}function $t(e){let t=rg.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function gc(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let o=nt(i),a=e.sightingsByNamespace.get(o);if(!a)continue;let c=new Set(a.keys());for(let[l,u]of a){let d=[...new Set(u.map(h=>h.path))];if(d.length<2)continue;let p=d.find(h=>n.has(h)),f=d.filter(h=>h!==p),m=`${i.prefix}${l}`;t.push(p?{id:`number.collision:${o}#${l}`,status:"open",namespace:i,number:l,title:`${m} is already taken`,detail:`This branch adds ${p}, but ${m} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${m} stop being unambiguous.`,ownPath:p,sightings:u.filter(h=>h.path!==p),suggestion:`${i.prefix}${Ti(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${o}#${l}`,status:"info",namespace:i,number:l,title:`${m} is used more than once (pre-existing)`,detail:`${m} is carried by ${d.length} files: ${d.join(", ")}.`,sightings:u,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,o)=>r[i.status]-r[o.status]||i.id.localeCompare(o.id))}function yc(e){return!e.some(t=>t.status==="open")}function Ti(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}function Ai(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function bc(e,t){let n=Ai(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=$t(re.basename(n));if(!i)return r;let o=`${re.dirname(n)}#${i.prefix}`,a=e.namespaces.find(d=>nt(d)===o)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(o)??new Map,l=new Set,u=[];for(let d of c.get(i.number)??[])d.path===n||l.has(d.path)||(l.add(d.path),u.push(d));return{path:n,namespace:a,number:i.number,taken:u.length>0,sightings:u,suggestion:Ti(c.keys(),i.number)}}function Wn(e){let t=e?.trim();return t||null}function tt(e){return e?e.split(`
|
|
24
|
+
`).filter(Boolean):[]}function ig(e){let t=Wn(S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function _c(e,t={}){let n=t.minFiles??Ri,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=S(e,r);if(i===null)return[];let o=new Map;for(let a of i.split("\0").filter(Boolean)){let c=re.dirname(a),l=$t(re.basename(a));if(!l)continue;let u=`${c}#${l.prefix}`,d=o.get(u);d?d.numbers.push(l.number):o.set(u,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...o.values()].filter(a=>hc(a.numbers,{...t,minFiles:n})).map(a=>({dir:a.dir,prefix:a.prefix,fileCount:a.numbers.length,distinctRatio:new Set(a.numbers).size/a.numbers.length})).sort((a,c)=>nt(a).localeCompare(nt(c)))}async function Ii(e,t={}){let n=[];if(Wn(S(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,baseRef:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=_c(e,t),o=new Map(i.map(h=>[nt(h),h])),a=[...new Set(i.map(h=>h.dir))],c=new Map,l=s((h,g,y)=>{let b=re.dirname(h),w=$t(re.basename(h));if(!w)return;let v=`${b}#${w.prefix}`;if(!o.has(v))return;let k=c.get(v)??new Map,E=k.get(w.number)??[];E.push({kind:g,where:y,path:h}),k.set(w.number,E),c.set(v,k)},"record"),u=s((h,g,y)=>{if(a.length===0)return;let b=S(e,["ls-tree","-r","--name-only",h,"--",...a]);if(b===null){n.push(`could not read ${y}`);return}for(let w of tt(b))l(w,g,y)},"scanTree");for(let h of a){let g=re.join(e,h);if(Si(g))try{for(let y of fc(g))l(`${h}/${y}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let d=ig(e),p=t.baseRef??(d?`origin/${d}`:null);p?u(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let f=Wn(S(e,["rev-parse","--abbrev-ref","HEAD"]));for(let h of tt(S(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))h!==f&&u(h,"branch",`Branch ${h}`);if(t.includeWorktrees!==!1){let h=Wn(S(e,["rev-parse","--show-toplevel"]));for(let g of tt(S(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===h||!Si(y)))for(let b of a){let w=re.join(y,b);if(Si(w))try{for(let v of fc(w))l(`${b}/${v}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${b} in ${y}`)}}}}let m=[];if(p&&a.length>0){let h=S(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);h===null?n.push(Ei):m=tt(h);let g=S(e,["ls-files","--others","--exclude-standard","--",...a]);g!==null&&(m=[...m,...tt(g)]);let y=S(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);y!==null&&(m=[...m,...tt(y)])}return{isRepo:!0,defaultBranch:d,baseRef:p,namespaces:i,sightingsByNamespace:c,addedPaths:m,skipped:n}}async function Ie(e,t={}){let n=await Ii(e,t),r=gc(n);return{ok:yc(r),findings:r,facts:n}}async function Ce(e,t,n={}){let r=Ai(t);if(!$t(re.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Ii(e,{...n,dirs:n.dirs??[re.dirname(r)]});return bc(i,r)}var Ei,rg,Ri,mc,jt=_(()=>{"use strict";q();Ei="could not diff against the base ref \u2014 everything reported as info";s(xi,"isNumberCollisionsGraded");rg=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Ri=3,mc=.8;s(hc,"isCounterNamespace");s(nt,"namespaceKey");s($t,"parseNumbered");s(gc,"computeNumberCollisions");s(yc,"isCollisionFree");s(Ti,"suggestNextNumber");s(Ai,"normaliseRepoPath");s(bc,"checkProposedNumber");s(Wn,"trimOrNull");s(tt,"lines");s(ig,"resolveDefaultBranch");s(_c,"detectNamespaces");s(Ii,"gatherNumberCollisionFacts");s(Ie,"checkNumberCollisions");s(Ce,"checkNumberForPath")});function Oi(e){return`spec.${e}`}function rt(e,t={}){switch(e){case"open":return{level:"open",baseline:"introduced"};case"warn":return{level:"warn",baseline:"introduced"};case"info":return t.excepted?{level:"info",baseline:"introduced"}:{level:"open",baseline:"pre_existing"};default:throw new Error(`gradeEngineStatus: '${String(e)}' is not a finding status`)}}function og(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let o=0;o<i;o++){let a=(n[o].codePointAt(0)??0)-(r[o].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function wc(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(og)}function Ht(e){return ni(JSON.stringify(wc(e)))}var Ci,Ni,Pi,Di,Mi=_(()=>{"use strict";ri();Ci={det_number_collisions:{version:"1.1.0",rules:["number.collision"]},det_spec_drift:{version:"1.1.0",rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"]},det_theme_class_drift:{version:"1.1.0",rules:["theme.dead_class"]},det_table_acl_lint:{version:"1.0.0",rules:["acl.missing_revoke"]}},Ni="number.collision",Pi="theme.dead_class",Di="acl.missing_revoke";s(Oi,"specDriftRuleId");s(rt,"gradeEngineStatus");s(og,"codePointCompare");s(wc,"normalizeEvidenceForHash");s(Ht,"hashDetectorEvidence")});import{existsSync as sg,readFileSync as kc}from"node:fs";import{posix as ag}from"node:path";function Jn(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 zn(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
|
|
25
|
+
`,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}function Ut(e){return e==='"'||e==="'"||e==="`"}function Yn(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function Vn(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let o=e[i];if(Ut(o)){i=Jn(e,i);continue}if(Yn(e,i)){i=zn(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function cg(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Yn(e,t)){t=zn(e,t);continue}break}return e.slice(t)}function it(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let o=e[i];if(Ut(o)){i=Jn(e,i);continue}if(Yn(e,i)){i=zn(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=>cg(o).trim()).filter(o=>o.length>0)}function xc(e){let t=Jn(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
|
|
26
|
+
`:i==="r"?"\r":i==="t"?" ":i)}function lg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Li(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${lg(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,o=!1;for(;i<e.length;){let a=e[i];if(Ut(a)){i=Jn(e,i);continue}if(Yn(e,i)){i=zn(e,i);continue}if(!o){if(a==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))o=!0;else if(a===";")return null;i++;continue}if(a==="[")return Vn(e,i);if(a===";")return null;i++}return null}function $i(e){let t={};if(!e.startsWith("{"))return t;for(let n of it(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],o=r[4].trim();Ut(o[0]??"")&&(t[i]=xc(o))}return t}function dg(e,t){if(!e.startsWith("{"))return null;for(let n of it(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===t)return r[4].trim()}return null}function Rc(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Tc(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Ac(e,t){let n=Li(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Tc(),i=[],o=0;for(let a of it(n.slice(1,-1))){if(!a.startsWith("{")){o++;continue}let c=$i(a),l=c[t.key_field];if(!l){o++;continue}let u=(t.partition_by??[]).map(d=>c[d]??"");i.push({key:l,fields:Rc(c,t.fields),orderPath:u,ordinal:r(u)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function Ic(e,t){let n=Li(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=Tc(),i=[],o=0,a=s((c,l,u)=>{let d=t.levels[l],p=l===t.levels.length-1;for(let f of it(c.slice(1,-1))){let m={...u},h=null;if(d.shape==="object"){if(!f.startsWith("{")){o++;continue}let g=$i(f);for(let[y,b]of Object.entries(d.fields??{}))m[y]=g[String(b)]??"";if(!p&&typeof d.children=="string"){let y=dg(f,d.children);h=y&&y.startsWith("[")?Vn(y,0):null}}else{if(!f.startsWith("[")){o++;continue}let g=it(f.slice(1,-1));for(let[y,b]of Object.entries(d.fields??{})){let w=g[Number(b)];m[y]=w!==void 0&&Ut(w[0]??"")?xc(w):""}if(!p&&typeof d.children=="number"){let y=g[d.children];h=y!==void 0&&y.startsWith("[")?Vn(y,0):null}}if(p){let g=m[t.key_field];if(!g){o++;continue}let y=(t.partition_by??[]).map(b=>m[b]??"");i.push({key:g,fields:Rc(m,t.fields),orderPath:y,ordinal:r(y)});continue}h!==null&&a(h,l+1,m)}},"walk");return a(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}function vc(e,t){return t.extractor==="object-array"?Ac(e,t):Ic(e,t)}function Cc(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 Nc(e,t,n){return`spec.drift:${e}#${t}:${n}`}function ug(e){return e.orderPath.join(" / ")||"(flat)"}function Pc(e,t,n,r){let i=[],o=s((u,d,p,f,m,h)=>{i.push({id:Nc(e.id,u,p),contract:e.id,dimension:u,status:d,key:p,title:f,detail:m,hint:h})},"push"),a=new Map(n.map(u=>[u.key,u])),c=new Map(t.map(u=>[u.key,u]));for(let u of t){let d=a.get(u.key);if(!d){o("coverage","open",u.key,`${u.key} is declared by the specification but missing from the implementation`,`Partition ${ug(u)}, position ${u.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let f=u.fields[p]??"",m=d.fields[p]??"";f!==m&&o("fields","open",`${u.key}.${p}`,`${u.key}: ${p} is "${m||"\u2014"}", the specification says "${f||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let u of t){let d=u.orderPath.join("\0"),p=l.get(d);p?p.push(u):l.set(d,[u])}for(let[u,d]of l){let p=d.filter(g=>a.has(g.key)).map(g=>g.key),f=n.filter(g=>g.orderPath.join("\0")===u).filter(g=>c.has(g.key)).map(g=>g.key),m=new Set(f),h=p.filter(g=>m.has(g));if(f.join("|")!==h.join("|")){let g=u.split("\0").join(" / ")||"(flat)";o("order","open",g,`Partition ${g}: sequence differs from the specification`,`implementation: ${f.join(" \u2192 ")}
|
|
27
|
+
specification: ${h.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let u of n)c.has(u.key)||o("extra","warn",u.key,`${u.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let u of new Set([...a.keys(),...c.keys()])){if(Cc(u,e.grounding,r))continue;let d=a.has(u);o("unrealized",d?"open":"warn",u,d?`${u} is referenced by the implementation but has no artefact`:`${u} is declared by the specification but not built yet`,d?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}function pg(e,t,n){let r=[];for(let i of e.assertions??[]){let o=n.get(i.path);if(!o)continue;let a=o.indexOf(i.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(o.slice(a+i.prefix.length));if(!c)continue;let l=Number(c[1]),u=t[i.counts];l!==u&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${u}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function Sc(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 Dc(e,t={}){let n=s(d=>({ok:!1,verdict:"no_opinion",reason:d,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(d=>t.contracts.includes(d.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(d=>`"${d}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=s(d=>{let p=[],f=[];for(let m of r){let h=d.get(m.spec.path),g=d.get(m.impl.path);if(h==null||g==null){let v=h==null?m.spec.path:m.impl.path;p.push(Sc(m.id,`Declared file could not be read: ${v}`)),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let y=vc(h,m.spec),b=vc(g,m.impl);if(y.error||b.error){p.push(Sc(m.id,y.error??b.error??"unknown")),f.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let w=y.dropped>0||b.dropped>0;f.push({id:m.id,measured:!0,specRecords:y.records.length,implRecords:b.records.length,partial:w}),w&&p.push({id:`contract.partial:${m.id}`,contract:m.id,dimension:"contract",status:"warn",key:null,title:`Contract "${m.id}" was measured incompletely`,detail:`${y.dropped} specification and ${b.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),p.push(...Pc(m,y.records,b.records,e.files)),p.push(...pg(m,{spec:y.records.length,impl:b.records.length},d))}return{findings:p,contracts:f}},"runOnce"),o=i(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let d of i(e.baselineSources).findings)d.id.startsWith("contract.unreadable:")||a.add(d.id);let c=new Map;for(let d of r)for(let p of d.exceptions??[])c.set(Nc(d.id,p.dimension,p.key),p);let l=o.findings.map(d=>{let p=c.get(d.id);return p?{...d,status:"info",exceptionReason:p.reason}:a.has(d.id)?{...d,status:"info",detail:`${d.detail}
|
|
28
|
+
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:d});l.sort((d,p)=>Ec[d.status]-Ec[p.status]||d.id.localeCompare(p.id));let u=l.some(d=>d.status==="open");return{ok:!u,verdict:u?"drifted":"aligned",reason:null,findings:l,contracts:o.contracts}}function Fi(e){let t=e?.trim();return t||null}function Xn(e){let t;try{t=JSON.parse(e)}catch(a){return{manifest:null,error:`manifest is not valid JSON: ${a.message}`}}let n=s(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,"obj"),r=s(a=>typeof a=="string"?a:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let o=s(a=>({manifest:null,error:a}),"bad");for(let[a,c]of i.contracts.entries()){let l=n(c),u=r(l?.id),d=u?`contract "${u}"`:`contract #${a+1}`;if(!l)return o(`${d}: not an object`);if(!u)return o(`${d}: \`id\` is missing`);if(!r(l.reason))return o(`${d}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let p of["spec","impl"]){let f=n(l[p]);if(!f)return o(`${d}: \`${p}\` is missing`);let m=r(f.extractor);if(!m)return o(`${d}: \`${p}.extractor\` is missing`);if(m!=="object-array"&&m!=="nested-literal-list")return o(`${d}: unknown \`${p}.extractor\` "${m}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return o(`${d}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(m==="nested-literal-list"&&!Array.isArray(f.levels))return o(`${d}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(l.exceptions)?l.exceptions:[]){let f=n(p);if(!f||!r(f.reason))return o(`${d}: exception for "${r(f?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}function fg(e){let t=Fi(S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(S(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function mg(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 Oc(e,t={}){let n=s((h,g)=>ag.join(h,g),"join"),r=t.manifestPath??qn,i=[],o={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(Fi(S(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...o,manifestError:"not a git work tree"};let a=n(e,r);if(!sg(a))return{...o,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,l=null;try{({manifest:c,error:l}=Xn(kc(a,"utf8")))}catch(h){l=`manifest at ${r} could not be read: ${h.message}`}if(!c)return{...o,isRepo:!0,manifestError:l};let u=new Map;for(let h of mg(c))try{u.set(h,kc(n(e,h),"utf8"))}catch{u.set(h,null),i.push(`declared file unreadable in the working tree: ${h}`)}let d=new Set,p=S(e,["ls-files","-z"]);if(p===null)i.push("could not list tracked files \u2014 grounding is skipped");else for(let h of p.split("\0"))h&&d.add(h);let f=null,m=new Map;if(t.includeBaseline!==!1){let h=t.baseRef?null:fg(e),g=t.baseRef??(h?`origin/${h}`:null);if(!g)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(f=Fi(S(e,["merge-base",g,"HEAD"])),!f)i.push(`no merge-base with ${g} \u2014 every finding reported as new`);else for(let y of u.keys())m.set(y,S(e,["show",`${f}:${y}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:u,baselineSources:m,baseRef:f,files:d,skipped:i}}async function Ne(e,t={}){let n=await Oc(e,t);return{...Dc(n,t),facts:n}}function ji(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var qn,Ec,Gt=_(()=>{"use strict";q();qn=".maind/spec-contracts.json";s(Jn,"endOfString");s(zn,"skipComment");s(Ut,"isQuote");s(Yn,"isCommentStart");s(Vn,"sliceBalanced");s(cg,"stripLeadingTrivia");s(it,"splitTopLevel");s(xc,"readStringLiteral");s(lg,"escapeRe");s(Li,"findSymbolArray");s($i,"parseObjectFields");s(dg,"objectFieldRaw");s(Rc,"pickFields");s(Tc,"makeOrdinals");s(Ac,"extractObjectArray");s(Ic,"extractNestedList");s(vc,"extractRecords");s(Cc,"isGrounded");s(Nc,"findingId");s(ug,"partitionOf");s(Pc,"compareContract");s(pg,"checkAssertions");s(Sc,"unreadable");Ec={open:0,warn:1,info:2,passed:3};s(Dc,"computeSpecDrift");s(Fi,"trimOrNull");s(Xn,"parseManifest");s(fg,"resolveDefaultBranch");s(mg,"declaredPaths");s(Oc,"gatherSpecDriftFacts");s(Ne,"checkSpecDrift");s(ji,"isSpecDriftGraded")});import{readFileSync as hg}from"node:fs";import{join as gg,posix as yg}from"node:path";function Mc(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],o=e[n+1];if(i==="-"&&o==="-"){for(;n<r&&e[n]!==`
|
|
29
|
+
`;)n++;continue}if(i==="/"&&o==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],u=e.indexOf(l,n+l.length);n=u===-1?r:u+l.length,t+=" ";continue}}let a=(i==="E"||i==="e")&&o==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||a){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function X(e){let t=[],n="",r=!1,i=!1,o=s(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){o();continue}n+=l}o();let a=t.filter(c=>c.length>0);return a.length===0||a.length>2?null:a.length===2?{schema:a[0],name:a[1]}:{schema:"public",name:a[0]}}function fe(e){let t=[],n=0,r="";for(let i of e){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}function bg(e){let t=/^ALTER\s+DEFAULT\s+PRIVILEGES\s+([\s\S]*?)(REVOKE|GRANT)\s+(?:GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+TABLES\s+(?:FROM|TO)\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT|WITH\s+GRANT\s+OPTION))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,o]=t;if(/REVOKE\s+GRANT\s+OPTION\s+FOR/i.test(e))return null;let a=/\bFOR\s+ROLE\s+([\s\S]+?)(?=\s+IN\s+SCHEMA\b|$)/i.exec(n);if(a&&!fe(a[1]).map(f=>X(f)?.name??"").filter(Boolean).includes("postgres"))return null;let c=/\bIN\s+SCHEMA\s+([\s\S]+?)(?=\s+FOR\s+ROLE\b|$)/i.exec(n);if(!c||!fe(c[1]).map(p=>X(p)?.name??"").filter(Boolean).includes("public"))return null;let u=fe(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>X(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(u.length===0)return null;let d=[];for(let p of fe(i)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let m=f[1].toUpperCase();if(m==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:u,writePrivs:[...Kt]};f[2]!=="("&&Kt.includes(m)&&d.push(m)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:u,writePrivs:d}}function Fc(e){let t=/^REVOKE\s+(GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+([\s\S]+?)\s+FROM\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,o]=t;if(n)return null;let a=i.trim();if(_g.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!fe(l[1]).map(f=>X(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),f=fe(p).map(m=>X(m)).filter(m=>m!==null).filter(m=>m.schema==="public").map(m=>m.name);if(f.length===0)return null;c=f}let u=fe(o).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>X(p)?.name??"").filter(p=>p.length>0&&p!=="public"),d=[];for(let p of fe(r)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let m=f[1].toUpperCase(),h=f[2]==="(";if(m==="ALL")return{tables:c,roles:u,writePrivs:[...Kt]};!h&&Kt.includes(m)&&d.push(m)}return{tables:c,roles:u,writePrivs:d}}function Ui(e){let t=new Map,n=[...e].sort((i,o)=>ue(i.version,o.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let o=Mc(i.content);for(let a of o.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=bg(c);if(!p)continue;let f=p.roles.includes("anon"),m=p.roles.includes("authenticated");if(p.action==="revoke"){if(f&&(r.anonAddressed=!0),m)for(let h of p.writePrivs)r.authWritesRevoked.add(h)}else if(f&&(r.anonAddressed=!1),m)for(let h of p.writePrivs)r.authWritesRevoked.delete(h);continue}let l=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(c);if(l){if(/\bTEMP(?:ORARY)?\b/i.test(l[1]??""))continue;let p=X(l[2]);if(!p||p.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(c)&&t.has(p.name))continue;t.set(p.name,{createdIn:i.version,anonAddressed:r.anonAddressed,authWritesRevoked:new Set(r.authWritesRevoked)});continue}let u=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(c);if(u){let p=u[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let f of fe(p)){let m=X(f);m&&m.schema==="public"&&t.delete(m.name)}continue}let d=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(d){let p=X(d[1]),f=X(d[2]);if(p&&f&&p.schema==="public"){let m=t.get(p.name);m&&(t.delete(p.name),t.set(f.name,m))}continue}if(/^REVOKE\b/i.test(c)){let p=Fc(c);if(!p)continue;let f=p.tables==="all_in_public"?[...t.keys()]:p.tables,m=p.roles.includes("anon"),h=p.roles.includes("authenticated");if(!m&&!h)continue;for(let g of f){let y=t.get(g);if(y&&(m&&(y.anonAddressed=!0),h))for(let b of p.writePrivs)y.authWritesRevoked.add(b)}continue}}}return t}function Hi(e){let t=[];for(let[n,r]of Ui(e)){let i=[];r.anonAddressed||i.push("anon"),Kt.every(o=>r.authWritesRevoked.has(o))||i.push("authenticated_writes"),i.length>0&&t.push({table:n,createdIn:r.createdIn,missing:i})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function Lc(e){let t=Hi(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Hi(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),a=i!=null&&r.missing.every(l=>i.has(l))?"info":"open",c=r.missing.map(l=>l==="anon"?"kein Tabellen-REVOKE nennt anon":"authenticated beh\xE4lt Schreibrechte (kumulierte REVOKEs decken INSERT/UPDATE/DELETE nicht)").join("; ");return{id:`table.acl:${e.dir}#${r.table}`,status:a,project:e.dir,table:r.table,createdIn:r.createdIn,missing:r.missing,title:`public.${r.table}: Default-Grants nie adressiert (${r.missing.join(", ")})`,detail:`\xDCber den gesamten Migrations-Bestand von ${e.dir}: ${c}. Supabase' ALTER DEFAULT PRIVILEGES grantet vollen CRUD an anon UND authenticated auf jede neue public-Tabelle; ohne Tabellen-REVOKE ist RLS die einzige Verteidigungslinie. Tabelle erzeugt in Migration ${r.createdIn}.`,hint:`REVOKE ALL ON public.${r.table} FROM PUBLIC, anon; REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.${r.table} FROM authenticated; \u2014 SELECT f\xFCr authenticated darf bewusst bleiben (RLS-gedecktes Lese-Muster). PUBLIC allein reicht NICHT (Default-Privileges sind direkte Rollen-Grants). Ein REVOKE in einer sp\xE4teren Migration z\xE4hlt ebenfalls; in DO-Bl\xF6cken z\xE4hlt es nicht (aufs Top-Level ziehen). Eine Tabelle, die NACH der Wurzelbehandlung entsteht (ALTER DEFAULT PRIVILEGES \u2026 IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated), kommt bereits geschlossen zur Welt und braucht kein eigenes REVOKE \u2014 diese Tabelle hier ist \xE4lter als die Wurzelbehandlung oder es gibt keine.`}})}function $c(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function Ki(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(Qn)||t.endsWith(Gi))}function kg(e,t){try{let n=hg(e,"utf8");return n.length>t?null:n}catch{return null}}function vg(e,t,n,r,i){let o=S(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(o===null)return i.push(`could not diff ${t} against ${r} ${Qn}`),null;let a=new Set,c=[];for(let d of o.split(`
|
|
30
|
+
`).filter(Boolean)){let[p,...f]=d.split(" ");p.startsWith("A")?a.add(f[0]):p.startsWith("R")?(c.push(f[0]),a.add(f[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(f[0])}let l=[],u=new Set(c);for(let{ref:d,content:p}of n)!a.has(d.path)&&!u.has(d.path)&&l.push({name:d.name,version:d.version,content:p});for(let d of c){let p=yg.basename(d),f=et(p);if(f===null)continue;let m=S(e,["show",`${r}:${d}`]);if(m===null)return i.push(`could not read ${d} at ${r} ${Gi}`),null;l.push({name:p,version:f,content:m})}return l}function Pe(e,t={}){let n=t.maxFileBytes??wg,r=[],i=Ae(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let o=t.includeBaseline!==!1,a=null;if(o)if(t.baseRef)a=t.baseRef;else{let f=nc(e);a=f?`origin/${f}`:null,a===null&&r.push(`no default branch resolvable ${Qn}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let f of i){let m=[];for(let y of f.files){let b=kg(gg(e,y.path),n);if(b===null){r.push(`could not read ${y.path} \u2014 excluded from the fold`);continue}m.push({ref:y,content:b})}let h=m.map(({ref:y,content:b})=>({name:y.name,version:y.version,content:b})),g=a===null?null:vg(e,f.dir,m,a,r);c.push(...Lc({dir:f.dir,files:h,baseFiles:g})),l.push({dir:f.dir,migrationCount:h.length,tableCount:Ui(h).size})}let u=l.reduce((f,m)=>f+m.migrationCount,0),d=$c(u,c.length),p={open:0,info:1};return c.sort((f,m)=>p[f.status]-p[m.status]||f.id.localeCompare(m.id)),{ok:d!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:d,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var Kt,_g,wg,Qn,Gi,Zn=_(()=>{"use strict";q();Ft();s(Mc,"stripSql");s(X,"normalizeQualifiedIdent");s(fe,"splitTopLevel");Kt=["INSERT","UPDATE","DELETE"];s(bg,"parseDefaultAclTables");_g=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;s(Fc,"parseTableRevoke");s(Ui,"foldTableAcl");s(Hi,"evaluateTableAcl");s(Lc,"computeTableAclFindings");s($c,"deriveTableAclVerdict");wg=5e6,Qn="\u2014 findings reported ungraded (open)",Gi="\u2014 baseline degraded";s(Ki,"isTableAclGraded");s(kg,"safeRead");s(vg,"baseFilesFor");s(Pe,"checkTableAclLint")});import{readFileSync as Sg}from"node:fs";import{join as Bi}from"node:path";function Vi(e){return e.verdict!=="no_opinion"&&e.graded}function qi(e){let t=new Set;for(let n of e.matchAll(Eg))t.add(n[1]);return t}function Ji(e){return new Set([...e].map(t=>t.split("-")[0]))}function Bc(e){return e.split(`
|
|
31
31
|
`).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
|
|
32
|
-
`)}function zi(e){let t=Ji(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let o=
|
|
33
|
-
`).filter(Boolean)}function
|
|
34
|
-
`).filter(Boolean)),l=s(p=>c.has(p)?S(e,["show",`${o}:${p}`]):Wi(Bi(e,p),n),"atBase"),u=new Set;for(let p of
|
|
35
|
-
`).filter(i=>i.length>0&&n.some(o=>
|
|
36
|
-
`):t.readUntracked(e)}var
|
|
32
|
+
`)}function zi(e){let t=Ji(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let o=Bc(i),a=new Set;for(let c of o.matchAll(xg)){let l=c[2],u=l.split("-")[0];if(!t.has(u)||e.tokens.has(l))continue;let d=`${c[1]}-${l}`;a.has(d)||(a.add(d),n.push({file:r,klass:d,token:l,namespace:u}))}}return n}function jc(e){return`${e.file} ${e.klass}`}function Rg(e,t){let n=t===null?null:new Set(t.map(jc));return e.map(r=>({...r,status:n!==null&&n.has(jc(r))?"info":"open"}))}function Wc(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function Yi(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Uc(e,t){let n=S(e,["ls-files","--",...t]);return n===null?[]:n.split(`
|
|
33
|
+
`).filter(Boolean)}function De(e,t={}){let n=t.maxFileBytes??Tg,r=new Set;for(let d of Uc(e,["*.css"])){let p=Wi(Bi(e,d),n);if(p!==null)for(let f of qi(p))r.add(f)}if(r.size===0)return{ok:!1,verdict:"no_opinion",tokenCount:0,namespaceCount:0,findings:[],scannedFiles:0,graded:!1,baseRef:null};let i=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(d=>Hc.map(p=>`${d.replace(/\/+$/,"")}/**/${p}`)):Hc,o=[];for(let d of Uc(e,i)){if(!Yi(d))continue;let p=Wi(Bi(e,d),n);p!==null&&o.push({path:d,content:p})}let a=zi({tokens:r,sources:o}),c=t.includeBaseline===!1?null:Ag(e,i,n,t.baseRef),l=Rg(a,c?.findings??null),u=Wc(r.size,l.length);return{ok:u!=="no_opinion"&&!l.some(d=>d.status==="open"),verdict:u,tokenCount:r.size,namespaceCount:Ji(r).size,findings:l,scannedFiles:o.length,graded:c!==null,baseRef:c?.mergeBase??null}}function Ag(e,t,n,r){let i=r??Cg(e);if(i===null)return null;let o=S(e,["merge-base",i,"HEAD"])?.trim();if(!o)return null;let a=S(e,["diff","--name-only","--no-renames",o]);if(a===null)return null;let c=new Set(a.split(`
|
|
34
|
+
`).filter(Boolean)),l=s(p=>c.has(p)?S(e,["show",`${o}:${p}`]):Wi(Bi(e,p),n),"atBase"),u=new Set;for(let p of Gc(e,o,["*.css"])){let f=l(p);if(f!==null)for(let m of qi(f))u.add(m)}if(u.size===0)return{findings:[],mergeBase:o};let d=[];for(let p of Gc(e,o,t)){if(!Yi(p))continue;let f=l(p);f===null||f.length>n||d.push({path:p,content:f})}return{findings:zi({tokens:u,sources:d}),mergeBase:o}}function Gc(e,t,n){let r=S(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
|
|
35
|
+
`).filter(i=>i.length>0&&n.some(o=>Ig(i,o)))}function Ig(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let o=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?o.endsWith(r.slice(1)):o===r}function Cg(e){let t=S(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>S(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function Wi(e,t){try{let n=Sg(e,"utf8");return n.length>t?null:n}catch{return null}}var Kc,Eg,xg,Hc,Tg,er=_(()=>{"use strict";q();s(Vi,"isThemeClassDriftGraded");Kc=["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"],Eg=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,xg=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Kc.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");s(qi,"extractTokens");s(Ji,"deriveNamespaces");s(Bc,"stripCommentLines");s(zi,"evaluateThemeClasses");s(jc,"findingKey");s(Rg,"gradeAgainstBaseline");s(Wc,"deriveThemeClassVerdict");Hc=["*.ts","*.tsx","*.js","*.jsx"],Tg=15e5;s(Yi,"isScannableSource");s(Uc,"listTracked");s(De,"checkThemeClassDrift");s(Ag,"baselineFindings");s(Gc,"listTrackedAt");s(Ig,"matchesSourcePattern");s(Cg,"resolveBaseRef");s(Wi,"safeRead")});function Xi(e){return Ci[e].version}function Wt(e,t,n,r){return{detector_id:e,detector_version:Xi(e),state:t,finding_count:n,...r?{reason:r}:{}}}function K(e,t,n){return{summary:Wt(e,t,0,n),findings:[]}}function Yc(e){return e==="open"||e==="warn"||e==="info"}function Pg(e){let t="det_number_collisions";if(!e.ok)return K(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return K(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return K(t,"not_applicable","no numbered namespaces");if(!xi(n))return K(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let o of r){if(!Yc(o.status))continue;let{level:a,baseline:c}=rt(o.status);i.push({detector_id:t,rule_id:Ni,level:a,baseline:c,evidence:[...o.ownPath?[o.ownPath]:[],...o.sightings.map(l=>l.path)],title:o.title})}return{summary:Wt(t,"ran",i.length),findings:i}}function Dg(e){let t="det_spec_drift";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return K(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return K(t,"not_applicable",n.reason??"no opinion");if(!ji(n))return K(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!Yc(i.status))continue;let{level:o,baseline:a}=rt(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:Oi(i.dimension),level:o,baseline:a,evidence:[i.id],title:i.title})}return{summary:Wt(t,"ran",r.length),findings:r}}function Og(e){let t="det_theme_class_drift";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return K(t,"not_applicable","no theme tokens");if(!Vi(n))return K(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=rt(i.status);r.push({detector_id:t,rule_id:Pi,level:o,baseline:a,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:Wt(t,"ran",r.length),findings:r}}function Mg(e){let t="det_table_acl_lint";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return K(t,"not_applicable","no supabase migrations");if(!Ki(n))return K(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:o,baseline:a}=rt(i.status);r.push({detector_id:t,rule_id:Di,level:o,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:Wt(t,"ran",r.length),findings:r}}function Qi(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||nr[e.level]-nr[t.level]||qc[e.baseline]-qc[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Jc(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function Fg(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let o=Ht(i.evidence),a=`${i.detector_id}|${i.rule_id}|${i.level}|${o}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:i.detector_id,detector_version:Xi(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:o,count:1})}else{let o=`${i.detector_id}|${i.rule_id}`,a=n.get(o);a?(a.evidence.push(...i.evidence),a.count+=1,nr[i.level]<nr[a.level]&&(a.level=i.level)):n.set(o,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:Xi(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Ht(i.evidence),count:i.count});return r.sort(Qi)}function Lg(e,t){let n=e.filter(r=>r.state==="ran"||r.state==="not_applicable").length;return n===0?"none":n<e.length||t>0?"partial":"full"}function ot(e){let t={det_number_collisions:Pg(e.number),det_spec_drift:Dg(e.spec),det_theme_class_drift:Og(e.theme),det_table_acl_lint:Mg(e.acl)},n=Vc.map(l=>t[l].summary),r=Vc.flatMap(l=>t[l].findings),i=Fg(r),o=[...i].sort((l,u)=>Jc(l)-Jc(u)||Qi(l,u)).slice(0,zc).sort(Qi),a=i.length-o.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Ht(l.evidence),title:l.title}));return{findings:o,coverage:Lg(n,a),engines:n,local:c,truncated:a}}function Bt(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e}}}function Xc(e){return e instanceof Error?e.message:String(e)}async function tr(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:Xc(t)}}}async function Zi(e,t={}){let n={...Ng,...t.engines};try{if(S(e,["rev-parse","--is-inside-work-tree"])?.trim()!=="true")return ot(Bt("not a git work tree"));let i=t.baseRef,o={number:await tr(()=>n.number(e,{...i?{baseRef:i}:{},...t.includeWorktrees===void 0?{}:{includeWorktrees:t.includeWorktrees}})),spec:await tr(()=>n.spec(e,i?{baseRef:i}:{})),theme:await tr(()=>n.theme(e,i?{baseRef:i}:{})),acl:await tr(()=>n.acl(e,i?{baseRef:i}:{}))};return ot(o)}catch(r){return ot(Bt(`detector adapter failed: ${Xc(r)}`))}}var zc,Ng,Vc,nr,qc,eo=_(()=>{"use strict";q();Mi();jt();Gt();Zn();er();zc=64,Ng={number:s((e,t)=>Ie(e,t),"number"),spec:s((e,t)=>Ne(e,t),"spec"),theme:s((e,t)=>De(e,t),"theme"),acl:s((e,t)=>Pe(e,t),"acl")},Vc=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint"];s(Xi,"versionOf");s(Wt,"summary");s(K,"noFindings");s(Yc,"isFindingStatus");s(Pg,"adaptNumber");s(Dg,"adaptSpec");s(Og,"adaptTheme");s(Mg,"adaptAcl");nr={open:0,warn:1,info:2},qc={introduced:0,pre_existing:1};s(Qi,"compareWire");s(Jc,"capPriority");s(Fg,"buildWire");s(Lg,"deriveCoverage");s(ot,"adaptDetectorReports");s(Bt,"unavailableDetectorReports");s(Xc,"errorText");s(tr,"attempt");s(Zi,"runRepoHealthDetectors")});var Qc,to=_(()=>{"use strict";Qc=[{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 Zc(e){let t=new Set;for(let[n,r]of e.paths)for(let i of Qc){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let o=$g(n,e);o!==null&&i.content.test(o)&&t.add(i.flag)}return[...t].sort()}function $g(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
36
|
+
`):t.readUntracked(e)}var el=_(()=>{"use strict";to();s(Zc,"scanRiskFlags");s($g,"contentForPath")});var st,tl,at,ct,no,rr,ir,or,ro,nl,Vt=_(()=>{"use strict";st="1",tl=`
|
|
37
37
|
CREATE TABLE IF NOT EXISTS meta (
|
|
38
38
|
key TEXT PRIMARY KEY,
|
|
39
39
|
value TEXT NOT NULL
|
|
@@ -92,7 +92,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
92
92
|
vec BLOB NOT NULL,
|
|
93
93
|
content_hash TEXT NOT NULL
|
|
94
94
|
);
|
|
95
|
-
`,at="schema_version",ct="last_index_commit",no="last_indexed_at",rr="embed_recipe_version",ir="embed_model",or="embed_dim",ro="last_synced_at",tl="last_synced_commit"});function io(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 nl(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of io(e.name))t.add(i);for(let i of io(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function rl(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 io(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var oo=_(()=>{"use strict";s(io,"splitIdentifier");s(nl,"buildSearchText");s(rl,"toFtsMatchQuery")});import{readFileSync as il}from"node:fs";import{posix as ol}from"node:path";function sl(e){return{nodeKey:e.nodeKey,kind:e.kind,name:e.name,qualifiedName:e.qualifiedName,filePath:e.filePath,language:e.language,startLine:e.startLine,endLine:e.endLine}}function De(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function al(e){return e==="added"?0:e==="modified"?1:2}function $g(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(i+=l-c+1)}let o=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||o?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var qt,so=_(()=>{"use strict";Ia();ci();Na();Da();q();qa();pi();vi();jt();eo();Gt();Zc();Vt();oo();qt=class{static{s(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(at),i=await this.store.countFiles()>0;(t.full||i&&r!==st)&&await this.wipe();let o=Ha(this.repoRoot),a=new Set(o.map(h=>h.path)),c=await this.store.getAllFiles(),l=new Map(c.map(h=>[h.path,h])),u=c.length>0&&!t.full,d={filesScanned:o.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u};for(let h of c)a.has(h.path)||(await this.store.deleteFile(h.path),d.filesDeleted++);let p=[],f=0;for(let h of o){f++;let g=Ka(this.repoRoot,h.path);if(!g){d.filesSkipped++;continue}let y=l.get(h.path);if(y&&y.mtimeMs===g.mtimeMs&&y.size===g.size){d.filesSkipped++;continue}let b=this.readRepoFile(h.path);if(b===null){d.filesSkipped++;continue}let w=Un(b);if(y&&y.contentHash===w){await this.store.upsertFile({...y,mtimeMs:g.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let v=await this.parser.parse(h.path,b,h.language),k=new Map;for(let R of v.nodes)k.set(R.nodeKey,nl(R));let E={path:h.path,language:h.language,contentHash:w,mtimeMs:g.mtimeMs,size:g.size,indexedAt:n};await this.store.replaceFileNodes(E,v.nodes,k),p.push(v),d.filesParsed++,t.onProgress?.({path:h.path,done:f,total:o.length})}if(p.length>0){let h=await this.store.getNameIndex(),g=Pa(h);for(let y of p){let b=Oa(y,g);await this.store.replaceOutgoingEdges(b.srcKeys,b.edges)}}if(this.embedder&&t.embed){let h=await this.store.getNodesByKinds([...ai]),g=await this.store.getEmbeddingContentHashes(),y=[];for(let w of h){let v=Aa(w),k=Un(`${this.embedder.recipeVersion}\0${v}`);g.get(w.nodeKey)!==k&&y.push({nodeKey:w.nodeKey,text:v,hash:k})}let b=64;for(let w=0;w<y.length;w+=b){let v=y.slice(w,w+b),k=await this.embedder.embedDocuments(v.map(R=>R.text));await this.store.upsertEmbeddings(v.map((R,I)=>({nodeKey:R.nodeKey,dim:this.embedder.dim,vec:k[I],contentHash:R.hash})));let E=Math.min(w+b,y.length);t.onProgress?.({path:"embedding symbols",done:E,total:y.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(rr,this.embedder.recipeVersion),await this.store.setMeta(ir,this.embedder.model),await this.store.setMeta(or,String(this.embedder.dim))}await this.store.setMeta(at,st),await this.store.setMeta(no,String(n));let m=Mt(this.repoRoot);return m&&await this.store.setMeta(ct,m),d.nodeCount=await this.store.countNodes(),d.edgeCount=await this.store.countEdges(),d.durationMs=(t.now??Date.now())-n,d}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let o of n)r[o.language]=o.count;let i=await this.store.getMeta(no);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(ct),schemaVersion:await this.store.getMeta(at),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=De(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),o=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&o.push({...sl(c),score:a.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=De(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:Ca(i,l.vec)})).sort((l,u)=>u.score-l.score).slice(0,r),c=[];for(let l of a){let u=await this.store.getNode(l.nodeKey);u&&c.push({...sl(u),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=De(n.maxDepth,3,5),o=De(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,u=new Set([t]),d=[t];for(let p=0;p<i&&d.length>0;p++){let f=[];for(let m of d){let h=await this.store.neighbors(m,r,a,o);for(let g of h){let y=`${g.srcKey} ${g.dstKey} ${g.kind}`;if(l.has(y))continue;if(l.add(y),c.push({srcKey:g.srcKey,dstKey:g.dstKey,kind:g.kind}),c.length>=o)return c;let b=r==="out"?g.dstKey:g.srcKey;u.has(b)||(u.add(b),f.push(b))}}d=f}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=il(ol.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let a of n)i[a.kind]=a.count;let o={};for(let a of r)o[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:o,topModules:await this.store.topModulesByFanIn(De(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Ga(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=De(t.limit,64,200),i=[],o=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&o++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:o,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Hn(this.repoRoot,{since:t.since});if(r===null)throw new Error("fileHistory requires a git repository (history is git-based)");n=[...r.keys()]}else if(Mt(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Qa(this.repoRoot,n,t)}async checkDivergence(t={}){return Lt(this.repoRoot,t)}async checkNumberCollisions(t={}){return Ie(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Ce(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Ne(this.repoRoot,t)}async reviewDetectors(t={}){return Zi(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Hn(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Va(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=Qc({paths:n,hunks:i,readUntracked:s(f=>this.readRepoFileHead(f,Wa),"readUntracked")}),c=ja(n.keys()),l=De(t.limit,64,200),u=[],d=0,p=0;for(let f of c){let m=await this.store.getNodesByFile(f.path);if(m.length===0)continue;d++;let h=await this.store.getFile(f.path),g=this.readRepoFile(f.path),y=h!==null&&g!==null&&Un(g)!==h.contentHash;y&&(p++,o==="full"&&(o="partial"));let b=n.get(f.path)??"modified",w=i.get(f.path);for(let v of m)u.push($g(v,b,w,y))}return u.sort((f,m)=>al(f.change)-al(m.change)||f.filePath.localeCompare(m.filePath)||f.startLine-m.startLine),{changedFiles:c.length,indexedFiles:d,staleFiles:p,symbols:u.slice(0,l),truncated:u.length>l,riskFlags:a,hunkCoverage:o,baseKind:t.since?"ref":"uncommitted",headSha:Mt(this.repoRoot),dirty:Ba(this.repoRoot),baseSha:t.since?Gn(this.repoRoot,t.since):null}}async close(){await this.store.close()}readRepoFileHead(t,n){let r=this.readRepoFile(t);return r===null?null:r.slice(0,n)}readRepoFile(t){try{return il(ol.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};s(sl,"toHit");s(De,"clampLimit");s(al,"changeRank");s($g,"classifyReviewSymbol")});import{createRequire as jg}from"node:module";function ll(){return cl("node:sqlite")}function lt(){if(Jt)return Jt;try{let{DatabaseSync:e}=ll(),t=new e(":memory:");try{t.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),t.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),t.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),Jt={ok:!0}}finally{t.close()}}catch(e){Jt={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Jt}function Hg(e){let{DatabaseSync:t}=ll(),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>n.exec(r),"exec"),close:s(()=>n.close(),"close"),transaction:s(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function Ug(e){let t=cl("better-sqlite3"),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>{n.exec(r)},"exec"),close:s(()=>{n.close()},"close"),transaction:s(r=>n.transaction(r),"transaction")}}function Gg(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function sr(e){let t=Gg(),n=s(i=>{let o=i==="node:sqlite"?Hg(e):Ug(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=lt();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=lt();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${o})`)}}var cl,Jt,ao=_(()=>{"use strict";cl=jg(import.meta.url);s(ll,"loadBuiltin");Jt=null;s(lt,"probeBuiltinSqlite");s(Hg,"openBuiltin");s(Ug,"openBetter");s(Gg,"backendOverride");s(sr,"openSqliteDatabase")});function ar(e){return{nodeKey:e.node_key,kind:e.kind,name:e.name,qualifiedName:e.qualified_name,filePath:e.file_path,language:e.language,startLine:e.start_line,endLine:e.end_line,startByte:e.start_byte,endByte:e.end_byte,signature:e.signature,doc:e.doc}}var dl,zt,ul=_(()=>{"use strict";ao();Vt();oo();s(ar,"toNodeRow");dl=400,zt=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=sr(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(el)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r){this.db.transaction(()=>{this.deleteFileGraph(t.path);let o=this.insertNodeStmt(),a=this.insertFtsStmt();for(let c of n)o.run(c.nodeKey,c.kind,c.name,c.qualifiedName,c.filePath,c.language,c.startLine,c.endLine,c.startByte,c.endByte,c.signature,c.doc),a.run(c.nodeKey,r.get(c.nodeKey)??c.name);this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)i.run(a);let o=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)o.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?ar(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(ar)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(ar)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(ar)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let o=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,o,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=rl(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
95
|
+
`,at="schema_version",ct="last_index_commit",no="last_indexed_at",rr="embed_recipe_version",ir="embed_model",or="embed_dim",ro="last_synced_at",nl="last_synced_commit"});function io(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 rl(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of io(e.name))t.add(i);for(let i of io(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function il(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 io(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var oo=_(()=>{"use strict";s(io,"splitIdentifier");s(rl,"buildSearchText");s(il,"toFtsMatchQuery")});import{readFileSync as ol}from"node:fs";import{posix as sl}from"node:path";function al(e){return{nodeKey:e.nodeKey,kind:e.kind,name:e.name,qualifiedName:e.qualifiedName,filePath:e.filePath,language:e.language,startLine:e.startLine,endLine:e.endLine}}function Oe(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function cl(e){return e==="added"?0:e==="modified"?1:2}function jg(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(i+=l-c+1)}let o=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||o?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var qt,so=_(()=>{"use strict";Ca();ci();Pa();Ma();q();Ja();pi();vi();jt();eo();Gt();el();Vt();oo();qt=class{static{s(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(at),i=await this.store.countFiles()>0;(t.full||i&&r!==st)&&await this.wipe();let o=Ua(this.repoRoot),a=new Set(o.map(h=>h.path)),c=await this.store.getAllFiles(),l=new Map(c.map(h=>[h.path,h])),u=c.length>0&&!t.full,d={filesScanned:o.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:u};for(let h of c)a.has(h.path)||(await this.store.deleteFile(h.path),d.filesDeleted++);let p=[],f=0;for(let h of o){f++;let g=Ba(this.repoRoot,h.path);if(!g){d.filesSkipped++;continue}let y=l.get(h.path);if(y&&y.mtimeMs===g.mtimeMs&&y.size===g.size){d.filesSkipped++;continue}let b=this.readRepoFile(h.path);if(b===null){d.filesSkipped++;continue}let w=Un(b);if(y&&y.contentHash===w){await this.store.upsertFile({...y,mtimeMs:g.mtimeMs,indexedAt:n}),d.filesSkipped++;continue}let v=await this.parser.parse(h.path,b,h.language),k=new Map;for(let R of v.nodes)k.set(R.nodeKey,rl(R));let E={path:h.path,language:h.language,contentHash:w,mtimeMs:g.mtimeMs,size:g.size,indexedAt:n};await this.store.replaceFileNodes(E,v.nodes,k),p.push(v),d.filesParsed++,t.onProgress?.({path:h.path,done:f,total:o.length})}if(p.length>0){let h=await this.store.getNameIndex(),g=Da(h);for(let y of p){let b=Oa(y,g);await this.store.replaceOutgoingEdges(b.srcKeys,b.edges)}}if(this.embedder&&t.embed){let h=await this.store.getNodesByKinds([...ai]),g=await this.store.getEmbeddingContentHashes(),y=[];for(let w of h){let v=Ia(w),k=Un(`${this.embedder.recipeVersion}\0${v}`);g.get(w.nodeKey)!==k&&y.push({nodeKey:w.nodeKey,text:v,hash:k})}let b=64;for(let w=0;w<y.length;w+=b){let v=y.slice(w,w+b),k=await this.embedder.embedDocuments(v.map(R=>R.text));await this.store.upsertEmbeddings(v.map((R,I)=>({nodeKey:R.nodeKey,dim:this.embedder.dim,vec:k[I],contentHash:R.hash})));let E=Math.min(w+b,y.length);t.onProgress?.({path:"embedding symbols",done:E,total:y.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(rr,this.embedder.recipeVersion),await this.store.setMeta(ir,this.embedder.model),await this.store.setMeta(or,String(this.embedder.dim))}await this.store.setMeta(at,st),await this.store.setMeta(no,String(n));let m=Mt(this.repoRoot);return m&&await this.store.setMeta(ct,m),d.nodeCount=await this.store.countNodes(),d.edgeCount=await this.store.countEdges(),d.durationMs=(t.now??Date.now())-n,d}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let o of n)r[o.language]=o.count;let i=await this.store.getMeta(no);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(ct),schemaVersion:await this.store.getMeta(at),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Oe(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),o=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&o.push({...al(c),score:a.score})}return o}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Oe(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:Na(i,l.vec)})).sort((l,u)=>u.score-l.score).slice(0,r),c=[];for(let l of a){let u=await this.store.getNode(l.nodeKey);u&&c.push({...al(u),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Oe(n.maxDepth,3,5),o=Oe(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,u=new Set([t]),d=[t];for(let p=0;p<i&&d.length>0;p++){let f=[];for(let m of d){let h=await this.store.neighbors(m,r,a,o);for(let g of h){let y=`${g.srcKey} ${g.dstKey} ${g.kind}`;if(l.has(y))continue;if(l.add(y),c.push({srcKey:g.srcKey,dstKey:g.dstKey,kind:g.kind}),c.length>=o)return c;let b=r==="out"?g.dstKey:g.srcKey;u.has(b)||(u.add(b),f.push(b))}}d=f}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=ol(sl.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let a of n)i[a.kind]=a.count;let o={};for(let a of r)o[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:o,topModules:await this.store.topModulesByFanIn(Oe(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Ka(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Oe(t.limit,64,200),i=[],o=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&o++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:o,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Hn(this.repoRoot,{since:t.since});if(r===null)throw new Error("fileHistory requires a git repository (history is git-based)");n=[...r.keys()]}else if(Mt(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Za(this.repoRoot,n,t)}async checkDivergence(t={}){return Lt(this.repoRoot,t)}async checkNumberCollisions(t={}){return Ie(this.repoRoot,t)}async checkNumberForPath(t,n={}){return Ce(this.repoRoot,t,n)}async checkSpecDrift(t={}){return Ne(this.repoRoot,t)}async reviewDetectors(t={}){return Zi(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Hn(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=qa(this.repoRoot,t),i=r?.files??new Map,o=r?.coverage??"none",a=Zc({paths:n,hunks:i,readUntracked:s(f=>this.readRepoFileHead(f,Va),"readUntracked")}),c=Ha(n.keys()),l=Oe(t.limit,64,200),u=[],d=0,p=0;for(let f of c){let m=await this.store.getNodesByFile(f.path);if(m.length===0)continue;d++;let h=await this.store.getFile(f.path),g=this.readRepoFile(f.path),y=h!==null&&g!==null&&Un(g)!==h.contentHash;y&&(p++,o==="full"&&(o="partial"));let b=n.get(f.path)??"modified",w=i.get(f.path);for(let v of m)u.push(jg(v,b,w,y))}return u.sort((f,m)=>cl(f.change)-cl(m.change)||f.filePath.localeCompare(m.filePath)||f.startLine-m.startLine),{changedFiles:c.length,indexedFiles:d,staleFiles:p,symbols:u.slice(0,l),truncated:u.length>l,riskFlags:a,hunkCoverage:o,baseKind:t.since?"ref":"uncommitted",headSha:Mt(this.repoRoot),dirty:Wa(this.repoRoot),baseSha:t.since?Gn(this.repoRoot,t.since):null}}async close(){await this.store.close()}readRepoFileHead(t,n){let r=this.readRepoFile(t);return r===null?null:r.slice(0,n)}readRepoFile(t){try{return ol(sl.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};s(al,"toHit");s(Oe,"clampLimit");s(cl,"changeRank");s(jg,"classifyReviewSymbol")});import{createRequire as Hg}from"node:module";function dl(){return ll("node:sqlite")}function lt(){if(Jt)return Jt;try{let{DatabaseSync:e}=dl(),t=new e(":memory:");try{t.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),t.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),t.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),Jt={ok:!0}}finally{t.close()}}catch(e){Jt={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Jt}function Ug(e){let{DatabaseSync:t}=dl(),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>n.exec(r),"exec"),close:s(()=>n.close(),"close"),transaction:s(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function Gg(e){let t=ll("better-sqlite3"),n=new t(e);return{prepare:s(r=>n.prepare(r),"prepare"),exec:s(r=>{n.exec(r)},"exec"),close:s(()=>{n.close()},"close"),transaction:s(r=>n.transaction(r),"transaction")}}function Kg(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function sr(e){let t=Kg(),n=s(i=>{let o=i==="node:sqlite"?Ug(e):Gg(e);return o.exec("PRAGMA journal_mode = WAL"),o.exec("PRAGMA foreign_keys = ON"),{db:o,backend:i}},"openAs");if(t==="builtin"){let i=lt();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=lt();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${o})`)}}var ll,Jt,ao=_(()=>{"use strict";ll=Hg(import.meta.url);s(dl,"loadBuiltin");Jt=null;s(lt,"probeBuiltinSqlite");s(Ug,"openBuiltin");s(Gg,"openBetter");s(Kg,"backendOverride");s(sr,"openSqliteDatabase")});function ar(e){return{nodeKey:e.node_key,kind:e.kind,name:e.name,qualifiedName:e.qualified_name,filePath:e.file_path,language:e.language,startLine:e.start_line,endLine:e.end_line,startByte:e.start_byte,endByte:e.end_byte,signature:e.signature,doc:e.doc}}var ul,zt,pl=_(()=>{"use strict";ao();Vt();oo();s(ar,"toNodeRow");ul=400,zt=class{static{s(this,"NodeSqliteStore")}db;backend;constructor(t){let n=sr(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(tl)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r){this.db.transaction(()=>{this.deleteFileGraph(t.path);let o=this.insertNodeStmt(),a=this.insertFtsStmt();for(let c of n)o.run(c.nodeKey,c.kind,c.name,c.qualifiedName,c.filePath,c.language,c.startLine,c.endLine,c.startByte,c.endByte,c.signature,c.doc),a.run(c.nodeKey,r.get(c.nodeKey)??c.name);this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)i.run(a);let o=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)o.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?ar(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(ar)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(ar)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(ar)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let o=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,o,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=il(t);if(!i)return[];let o=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
96
96
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
97
97
|
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
98
98
|
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
@@ -105,7 +105,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
105
105
|
FROM nodes n
|
|
106
106
|
WHERE n.kind = 'module'
|
|
107
107
|
ORDER BY imports_in DESC, symbol_count DESC
|
|
108
|
-
LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(o=>o.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let o=0;o<n.length;o+=
|
|
108
|
+
LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(o=>o.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let o=0;o<n.length;o+=ul)for(let a of n.slice(o,o+ul))r.run(a),i.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
|
|
109
109
|
node_key, kind, name, qualified_name, file_path, language,
|
|
110
110
|
start_line, end_line, start_byte, end_byte, signature, doc
|
|
111
111
|
) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)),this._insNode}_insFts=null;insertFtsStmt(){return this._insFts||(this._insFts=this.db.prepare("INSERT INTO nodes_fts(node_key, search_text) VALUES(?, ?)")),this._insFts}_upsertFile=null;upsertFileStmt(){return this._upsertFile||(this._upsertFile=this.db.prepare(`INSERT INTO files(path, language, content_hash, mtime_ms, size, indexed_at)
|
|
@@ -115,22 +115,22 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
115
115
|
content_hash = excluded.content_hash,
|
|
116
116
|
mtime_ms = excluded.mtime_ms,
|
|
117
117
|
size = excluded.size,
|
|
118
|
-
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as Kg}from"node:crypto";function dt(e){return Kg("sha256").update(e,"utf8").digest("hex")}function pl(e){return{node_key_hash:dt(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:dt(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?dt(e.signature):null}}function fl(e){return{src_key_hash:dt(e.srcKey),dst_key_hash:dt(e.dstKey),kind:e.kind}}function ml(e,t,n){return{node_key_hash:dt(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var hl=_(()=>{"use strict";s(dt,"sha256");s(pl,"toCloudNode");s(fl,"toCloudEdge");s(ml,"toCloudEmbedding")});function co(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function gl(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Wg(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var ut,pt,Bg,lo=_(()=>{"use strict";Vt();hl();ut=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},pt=class{static{s(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(ct),lastSyncedAt:gl(await this.store.getMeta(ro))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(pl),n=(await this.store.getAllEdges()).map(fl),r=await this.store.getMeta(at)??st,i=await this.store.getMeta(ct),o=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(g=>[g.language,g.count])),c={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:o,lang_dist:a},l=0,u=co(t,this.chunk),d=co(n,this.chunk*2),p=Math.max(1,u.length+d.length);for(let g of u)await this.post("/api/codebase/push",{...c,nodes:g,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:p});for(let g of d)await this.post("/api/codebase/push",{...c,nodes:[],edges:g}),this.cfg.onProgress?.({phase:"edges",done:++l,total:p});u.length===0&&d.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let f=t.map(g=>g.node_key_hash),m=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:f});this.cfg.onProgress?.({phase:"prune",done:p,total:p});let h=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(ro,String(Date.now())),i&&await this.store.setMeta(tl,i),{nodes:t.length,edges:n.length,pruned:Wg(m.nodes_deleted),embeddings:h,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),o=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(u=>ml(u,t.get(u.nodeKey)??"",n)).filter(u=>u.content_hash!==""&&o[u.node_key_hash]!==u.content_hash);if(a.length===0)return 0;let c=co(a,Bg),l=0;for(let u of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:u}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(rr),n=await this.store.getMeta(ir),r=gl(await this.store.getMeta(or));if(!t||!n||!r)throw new ut("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let o=i?.error;throw new ut(`${n} failed (HTTP ${t.status})${o?`: ${o}`:""}`,t.status,o)}return i}},Bg=250;s(co,"chunkArray");s(gl,"numOrNull");s(Wg,"numOr0")});var yl={};V(yl,{CodeIndexSync:()=>pt,DEFAULT_DB_RELPATH:()=>po,SyncError:()=>ut,createCodeIndexSync:()=>qg,createNodeCodeIndex:()=>fo,openSqliteDatabase:()=>sr,probeBuiltinSqlite:()=>lt});import{mkdirSync as Vg}from"node:fs";import{posix as uo}from"node:path";function fo(e){let t=e.dbPath??uo.join(e.repoRoot,po);Vg(uo.dirname(t),{recursive:!0});let n=new zt(t),r=new Ln;return new qt({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function qg(e){let t=e.dbPath??uo.join(e.repoRoot,po),n=e.projectKey??ma(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new zt(t);return new pt(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var po,mo=_(()=>{"use strict";ri();Ta();so();ul();lo();lo();ao();po=".maind/code-index.sqlite";s(fo,"createNodeCodeIndex");s(qg,"createCodeIndexSync")});import{execFileSync as bl}from"node:child_process";import{existsSync as _l,realpathSync as wl}from"node:fs";import{createRequire as Jg}from"node:module";import{basename as zg,dirname as Yg,isAbsolute as kl,join as Xg,relative as vl,resolve as cr,sep as Sl}from"node:path";function El(){let e=lt();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return Jg(import.meta.url)("better-sqlite3"),{ok:!0,backend:"better-sqlite3"}}catch(t){let n=t instanceof Error?t.message:String(t);return{ok:!1,reason:`node:sqlite: ${e.reason}; better-sqlite3: ${n}`}}}function xl(e){let t=e?.code??"",n=e instanceof Error?e.message:String(e);return/better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(`${t} ${n}`)||t==="ERR_DLOPEN_FAILED"||/NODE_MODULE_VERSION/.test(n)}function J(e=process.cwd()){try{let t=bl("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 Tl(e,t=J(),n=process.cwd()){let r=kl(e)?[e]:[cr(t,e),cr(n,e)];for(let i of r){let o=Yg(i);if(!_l(o))continue;let a;try{a=wl(o)}catch{continue}let c=Al(a);if(c===null)continue;let l=vl(c,Xg(a,zg(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Sl).join("/")}}return null}function lr(e,t=J(),n=process.cwd()){let r=kl(e)?[e]:[cr(t,e),cr(n,e)];for(let i of r){if(!_l(i))continue;let o;try{o=wl(i)}catch{continue}let a=Al(o);if(a===null)continue;let c=vl(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Sl).join("/")}}return null}function Al(e){try{let t=bl("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function Il(){return fo({repoRoot:J()})}var Rl,Yt=_(()=>{"use strict";mo();s(El,"probeNativeStore");s(xl,"isNativeStoreUnavailable");Rl="codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";s(J,"resolveRepoRoot");s(Tl,"resolveRepoRootForPath");s(lr,"resolveRepoRootForDir");s(Al,"gitToplevelOf");s(Il,"defaultEngineFactory")});var Fl=_(()=>{"use strict"});import{existsSync as ho,readdirSync as ty,readFileSync as ny}from"node:fs";import{spawnSync as ry}from"node:child_process";import{dirname as iy,join as go,posix as oy}from"node:path";function $l(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 ${yo} 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 ${yo} 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,h={psql_missing:{title:"psql nicht im PATH \u2014 Ledger nicht lesbar",detailText:"Ohne psql kann der lokale Ledger nicht gelesen werden. Kein Urteil \xFCber Drift m\xF6glich.",hint:"psql installieren (z. B. `brew install libpq` + PATH) oder den lokalen Stack-Client nachr\xFCsten."},unreachable:{title:`lokale Datenbank auf 127.0.0.1:${e.config.port} nicht erreichbar`,detailText:"Der Port aus config.toml antwortet nicht \u2014 der Stack schl\xE4ft vermutlich. Scheitert wenigstens laut (anders als die Default-Port-Falle); ein Urteil \xFCber Drift ist trotzdem nicht m\xF6glich.",hint:"`npx supabase start` im Projekt, dann erneut pr\xFCfen."},no_ledger:{title:`Port ${e.config.port} antwortet, tr\xE4gt aber KEINEN Supabase-Ledger`,detailText:"supabase_migrations.schema_migrations existiert dort nicht. Mutma\xDFlich lauscht auf diesem Port eine FREMDE Datenbank \u2014 dieselbe Verwechslungsklasse wie die 54322-Panne, nur von der anderen Seite gesehen.",hint:"Pr\xFCfen, wer auf dem Port lauscht (`lsof -nP -iTCP:<port> -sTCP:LISTEN`), und die config.toml gegen das Projekt halten."},query_failed:{title:"Ledger-Abfrage fehlgeschlagen",detailText:`Die SELECT-Abfrage gegen supabase_migrations.schema_migrations scheiterte${f?`: ${f}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:h.title,detail:h.detailText,hint:h.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),o=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!i.has(p)).sort(ue);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:"`npx supabase migration up` im Projektverzeichnis (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen.",versions:a});let c=r.versions.filter(p=>!o.has(p)).sort(ue),l=new Map,u=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let m=l.get(f)??[];m.push(p),l.set(f,m)}else u.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(u.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${u.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${u.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:u}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),f=e.fileVersions.filter(h=>!p.has(h)).sort(ue),m=e.remote.versions.filter(h=>!o.has(h)).sort(ue);f.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${f.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${f.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:f}),m.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${m.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${m.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:m})}let d=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:d,findings:t,db:n}}function jl(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Ul(e,t){if(t==="enoent")return{ok:!1,reason:"psql_missing"};let n=e.toLowerCase();return n.includes("does not exist")&&n.includes("schema_migrations")?{ok:!1,reason:"no_ledger"}:n.includes("connection refused")||n.includes("could not connect")||n.includes("timeout expired")||n.includes("server closed the connection")||n.includes("connection timed out")?{ok:!1,reason:"unreachable"}:{ok:!1,reason:"query_failed",detail:e.split(`
|
|
119
|
-
`).filter(Boolean).slice(-1)[0]}}function
|
|
120
|
-
`).map(i=>i.trim()).filter(Boolean)}}function
|
|
121
|
-
`)){if(!o.startsWith("worktree "))continue;let a=o.slice(9).trim();if(!a||a===i||!ho(a))continue;let c=go(a,t);if(ho(c))try{for(let l of
|
|
122
|
-
`)),this.machineLabel=
|
|
123
|
-
`,{mode:384}),
|
|
124
|
-
`)}function Tb(e,t){let n=s(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[o,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of o)a.has(l)&&c++;return c/o.size>=.8}function Ab(e,t,n){return _b.test(e)?{polarity:-1,magnitude:yt.rework,kind:"rework"}:n&&wb.test(e)?{polarity:-1,magnitude:yt.correction,kind:"correction"}:kb.test(e)?{polarity:1,magnitude:yt.acceptance,kind:"acceptance"}:t!==null&&Tb(t,e)?{polarity:-1,magnitude:yt.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function Ib(e){return{session_id:e,user_turns:0,assistant_turns:0,tool_calls:0,agent_questions:0,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,user_chars:0,user_token_estimate:0,human_share:0,reactions_pos:0,reactions_neg:0,net_sentiment:0,corrections:0,reworks:0,interrupts:0,tool_denials:0,repeated_instructions:0,acceptances:0,momentum_series:[],momentum_final:0,momentum_auc:0,ended_positive:!1,recovery_events:0,effort_at_end:null,model_mix:[],ai_title:null,session_slug:null,maind_tool_calls:{},maind_connected:"unknown",lines_seen:0,analyzer_version:Ed}}async function Io(e,t={}){let n=Ib("");if(!e||!yb(e))return n;let r=t.turns??(await en(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let i=[],o=new Map,a=null,c=!1,l=null;await new Promise(m=>{let h=gb(e,{encoding:"utf-8"}),g=bb({input:h}),y=s(b=>{let w=b.trim();if(!w)return;let v;try{v=JSON.parse(w)}catch{return}if(n.lines_seen++,!n.session_id){let N=v.sessionId??v.session_id;typeof N=="string"&&N&&(n.session_id=N)}v.type==="ai-title"&&typeof v.aiTitle=="string"&&v.aiTitle&&(n.ai_title=v.aiTitle),typeof v.slug=="string"&&v.slug&&(n.session_slug=v.slug);let k=v.message?.role,E=v.isSidechain===!0;if(k==="assistant")for(let N of Ao(v.message?.content)){if(N.type!=="tool_use"||typeof N.name!="string"||!N.name.startsWith(Sd))continue;let Be=N.name.slice(Sd.length);Be&&(n.maind_tool_calls[Be]=(n.maind_tool_calls[Be]??0)+1)}if(E)return;if(k==="assistant"){let N=Ao(v.message?.content),Be=!1;for(let hs of N)hs.type==="tool_use"&&(n.tool_calls++,Be=!0,hs.name==="AskUserQuestion"&&n.agent_questions++);c=Be;return}if(k!=="user")return;let R=Ao(v.message?.content),I=Rb(R);if(I.includes(vb)){n.interrupts++,i.push({polarity:-1,magnitude:yt.interrupt,kind:"interrupt"});return}if(R.some(N=>N.type==="tool_result"&&N.is_error===!0&&typeof N.content=="string"&&N.content.includes(Sb))){n.tool_denials++,i.push({polarity:-1,magnitude:yt.denial,kind:"denial"});return}if(R.some(N=>N.type==="tool_result")||!I.trim())return;n.user_turns++,n.user_chars+=I.length;let T=Zt(I);T&&(a=T);let j=Ab(I,l,c);l=I,j.kind==="correction"?n.corrections++:j.kind==="rework"?n.reworks++:j.kind==="repeat"?n.repeated_instructions++:j.kind==="acceptance"&&n.acceptances++,j.polarity!==0&&i.push(j),c=!1},"processLine");g.on("line",b=>{try{y(b)}catch{}}),g.on("close",()=>m()),g.on("error",()=>m()),h.on("error",()=>m())}),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||xb(o,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...o.values()].sort((m,h)=>m.first_ts-h.first_ts||m.model.localeCompare(h.model)),n.user_token_estimate=Math.round(n.user_chars/4);let u=n.user_token_estimate+n.output_tokens;n.human_share=u>0?Number((n.user_token_estimate/u).toFixed(4)):0;let d=0,p=0,f=[];return i.forEach((m,h)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,d=d*Eb+m.polarity*m.magnitude;let g=Number(d.toFixed(3));f.push({t:h,value:g,...m.kind!=="neutral"?{kind:m.kind}:{}}),p+=g,h>0&&i[h-1].polarity<0&&m.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls).length>0&&(n.maind_connected="connected"),n}var Sd,Ed,_b,wb,kb,vb,Sb,Eb,yt,xd=_(()=>{"use strict";br();_r();Sd="mcp__maind__",Ed="2026-09-04",_b=/(\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,wb=/(\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,kb=/(\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,vb="[Request interrupted by user",Sb="The user doesn't want to proceed with this tool use",Eb=.7,yt={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(xb,"bumpModel");s(Ao,"asBlocks");s(Rb,"textOf");s(Tb,"isRepeat");s(Ab,"classifyGenuine");s(Ib,"emptyAnalysis");s(Io,"analyzeSession")});function Co(e){let t=e!==null&&typeof e=="object"?e:{},n=typeof t.slices_stored=="boolean"?t.slices_stored:null;return{analyticsStored:t.analytics_stored===!0,spanStored:t.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof t.slices_reason=="string"?t.slices_reason:null,slicesCount:typeof t.slices_count=="number"&&Number.isFinite(t.slices_count)?t.slices_count:0}}function No(e,t){return!t||e.slicesStored===!0?null:e.slicesStored===null?"cost slices sent, verdict unknown \u2014 the ingest endpoint predates slice verdicts (redeploy mcp-client-metrics-ingest)":`cost slices not stored: ${e.slicesReason??"no reason given"} (${e.slicesCount} sent)`}function Po(e,t,n,r="unknown",i){let o={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};return t&&t.started_at&&(o.session_span=n?{...t,...n}:t),o}var Rd=_(()=>{"use strict";s(Co,"parseIngestResponse");s(No,"describeSliceVerdict");s(Po,"ingestBody")});import{isAbsolute as Td,relative as Cb,resolve as Ad,sep as Id}from"node:path";function wr(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Mo(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=s(a=>{if(!Array.isArray(a))return[];let c=[];for(let l of a){if(!l||typeof l!="object")continue;let u=l,d=wr(u.from);typeof u.object_id!="string"||!Oo.test(u.object_id)||d===null||c.push({object_id:u.object_id.toLowerCase(),from:d,to:wr(u.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=wr(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:wr(c.to)})}let o=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let c=a;typeof c.object_id!="string"||!Oo.test(c.object_id)||typeof c.path_prefix=="string"&&o.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Oo.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:o}}function Nd(e,t){if(!Td(e))return null;let n=Cb(Ad(t),Ad(e));return!n||n==="."||n.startsWith("..")||Td(n)?null:Id==="/"?n:n.split(Id).join("/")}function Nb(e,t){return t===""||e===t||e.startsWith(t+"/")}function Fo(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Pd(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function Lo(e,t){for(let n of Pd(t))if(Nb(e,n.path_prefix))return n.object_id;return null}function Pb(e,t){for(let n of Pd(t))if(Fo(e,n.path_prefix))return n.object_id;return null}function Do(e,t){return e>=t.from&&(t.to===null||e<t.to)}function Od(e,t,n,r){let i=e.ts,o=r?.anchors??[],a=t.map(c=>Lo(c,o)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(d=>Do(i,d));if(c.length)return c.sort((d,p)=>p.from-d.from||d.object_id.localeCompare(p.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(d=>Do(i,d));if(l.length)return{object_id:(l.find(p=>a.includes(p.object_id))??l.find(p=>n!==null&&p.object_id===n.object_id)??[...l].sort((p,f)=>p.object_id.localeCompare(f.object_id))[0]).object_id,source:"binding"};let u=r.claims.filter(d=>Do(i,d));if(u.length){let d=t[0]??n?.rel??null,p=(d===null?u:u.filter(f=>Fo(f.path_prefix,d))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of p){let m=Pb(f.path_prefix,o);if(m)return{object_id:m,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function $o(e,t,n){let r=t?.anchors??[],i=s(h=>{if(!n.repoRoot)return[];let g=[];for(let y of h.edited_paths){let b=Nd(y,n.repoRoot);b!==null&&!g.includes(b)&&g.push(b)}return g},"relOf"),o=s(h=>{for(let g of h){let y=Lo(g,r);if(y)return{object_id:y,rel:g}}return null},"firstAnchoredEdit"),a=new Map;for(let h of e){let g=a.get(h.stream)??[];g.push(h),a.set(h.stream,g)}let c=[...a.entries()].sort(([h],[g])=>h===Fe?-1:g===Fe?1:0),l=[],u=s(h=>{let g=null;for(let y of l){if(y.ts>h&&h>0)break;g=y.seg}return g},"mainSegmentAt"),d=new Map;for(let[h,g]of c){let y=g.map((w,v)=>({t:w,i:v,rels:i(w)})).sort((w,v)=>w.t.ts-v.t.ts||w.i-v.i),b=null;for(let w of y){let v=o(w.rels);if(v){b=v;break}}!b&&h!==Fe&&y.length&&(b=u(y[0].t.ts));for(let w of y){let v=o(w.rels);v&&(b=v),h===Fe&&l.push({ts:w.t.ts,seg:b});let k=w.t;if(k.input_tokens+k.output_tokens+k.cache_read_tokens+k.cache_creation_tokens===0)continue;let R=Od(k,w.rels,b,t),I=k.input_tokens+k.cache_read_tokens+k.cache_creation_tokens>Cd?"above_200k":"standard",A=`${R.object_id??""}|${R.source}|${k.model}|${I}`,T=d.get(A);T||(T={object_id:R.object_id,attribution_source:R.source,model:k.model,context_tier:I,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},d.set(A,T)),T.input_tokens+=k.input_tokens,T.output_tokens+=k.output_tokens,T.cache_read_tokens+=k.cache_read_tokens,T.cache_creation_tokens+=k.cache_creation_tokens,T.cache_creation_1h_tokens+=k.cache_creation_1h_tokens,T.turns+=1,k.ts>0&&((T.firstMs===0||k.ts<T.firstMs)&&(T.firstMs=k.ts),k.ts>T.lastMs&&(T.lastMs=k.ts))}}let p=n.nowMs??Date.now(),f=[];for(let h of d.values()){let{firstMs:g,lastMs:y,...b}=h;b.first_ts=new Date(g>0?g:p).toISOString(),b.last_ts=new Date(y>0?y:p).toISOString(),f.push(b)}let m={lease:0,binding:1,claim:2,path:3,none:4};return f.sort((h,g)=>m[h.attribution_source]-m[g.attribution_source]||(h.object_id??"").localeCompare(g.object_id??"")||h.model.localeCompare(g.model)||h.context_tier.localeCompare(g.context_tier)),f}var Cd,Oo,Dd=_(()=>{"use strict";_r();Cd=2e5,Oo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(wr,"msOf");s(Mo,"parseCostContext");s(Nd,"toRepoRelative");s(Nb,"underPrefix");s(Fo,"prefixesOverlap");s(Pd,"sortedAnchors");s(Lo,"anchorFor");s(Pb,"bestAnchorOverlapping");s(Do,"inWindow");s(Od,"assignTurn");s($o,"sliceSession")});import{createReadStream as Ob,existsSync as Db}from"node:fs";import{createInterface as Mb}from"node:readline";function Md(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function $b(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
125
|
-
`)}function
|
|
126
|
-
`)}return""}async function Ho(e,t={}){if(!e||!
|
|
118
|
+
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as Bg}from"node:crypto";function dt(e){return Bg("sha256").update(e,"utf8").digest("hex")}function fl(e){return{node_key_hash:dt(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:dt(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?dt(e.signature):null}}function ml(e){return{src_key_hash:dt(e.srcKey),dst_key_hash:dt(e.dstKey),kind:e.kind}}function hl(e,t,n){return{node_key_hash:dt(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var gl=_(()=>{"use strict";s(dt,"sha256");s(fl,"toCloudNode");s(ml,"toCloudEdge");s(hl,"toCloudEmbedding")});function co(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function yl(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Vg(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var ut,pt,Wg,lo=_(()=>{"use strict";Vt();gl();ut=class extends Error{static{s(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},pt=class{static{s(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(ct),lastSyncedAt:yl(await this.store.getMeta(ro))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(fl),n=(await this.store.getAllEdges()).map(ml),r=await this.store.getMeta(at)??st,i=await this.store.getMeta(ct),o=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(g=>[g.language,g.count])),c={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:o,lang_dist:a},l=0,u=co(t,this.chunk),d=co(n,this.chunk*2),p=Math.max(1,u.length+d.length);for(let g of u)await this.post("/api/codebase/push",{...c,nodes:g,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:p});for(let g of d)await this.post("/api/codebase/push",{...c,nodes:[],edges:g}),this.cfg.onProgress?.({phase:"edges",done:++l,total:p});u.length===0&&d.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let f=t.map(g=>g.node_key_hash),m=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:f});this.cfg.onProgress?.({phase:"prune",done:p,total:p});let h=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(ro,String(Date.now())),i&&await this.store.setMeta(nl,i),{nodes:t.length,edges:n.length,pruned:Vg(m.nodes_deleted),embeddings:h,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),o=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(u=>hl(u,t.get(u.nodeKey)??"",n)).filter(u=>u.content_hash!==""&&o[u.node_key_hash]!==u.content_hash);if(a.length===0)return 0;let c=co(a,Wg),l=0;for(let u of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:u}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(rr),n=await this.store.getMeta(ir),r=yl(await this.store.getMeta(or));if(!t||!n||!r)throw new ut("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let o=i?.error;throw new ut(`${n} failed (HTTP ${t.status})${o?`: ${o}`:""}`,t.status,o)}return i}},Wg=250;s(co,"chunkArray");s(yl,"numOrNull");s(Vg,"numOr0")});var bl={};V(bl,{CodeIndexSync:()=>pt,DEFAULT_DB_RELPATH:()=>po,SyncError:()=>ut,createCodeIndexSync:()=>Jg,createNodeCodeIndex:()=>fo,openSqliteDatabase:()=>sr,probeBuiltinSqlite:()=>lt});import{mkdirSync as qg}from"node:fs";import{posix as uo}from"node:path";function fo(e){let t=e.dbPath??uo.join(e.repoRoot,po);qg(uo.dirname(t),{recursive:!0});let n=new zt(t),r=new Ln;return new qt({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function Jg(e){let t=e.dbPath??uo.join(e.repoRoot,po),n=e.projectKey??ha(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new zt(t);return new pt(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var po,mo=_(()=>{"use strict";ri();Aa();so();pl();lo();lo();ao();po=".maind/code-index.sqlite";s(fo,"createNodeCodeIndex");s(Jg,"createCodeIndexSync")});import{execFileSync as _l}from"node:child_process";import{existsSync as wl,realpathSync as kl}from"node:fs";import{createRequire as zg}from"node:module";import{basename as Yg,dirname as Xg,isAbsolute as vl,join as Qg,relative as Sl,resolve as cr,sep as El}from"node:path";function xl(){let e=lt();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return zg(import.meta.url)("better-sqlite3"),{ok:!0,backend:"better-sqlite3"}}catch(t){let n=t instanceof Error?t.message:String(t);return{ok:!1,reason:`node:sqlite: ${e.reason}; better-sqlite3: ${n}`}}}function Rl(e){let t=e?.code??"",n=e instanceof Error?e.message:String(e);return/better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(`${t} ${n}`)||t==="ERR_DLOPEN_FAILED"||/NODE_MODULE_VERSION/.test(n)}function J(e=process.cwd()){try{let t=_l("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function Al(e,t=J(),n=process.cwd()){let r=vl(e)?[e]:[cr(t,e),cr(n,e)];for(let i of r){let o=Xg(i);if(!wl(o))continue;let a;try{a=kl(o)}catch{continue}let c=Il(a);if(c===null)continue;let l=Sl(c,Qg(a,Yg(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(El).join("/")}}return null}function lr(e,t=J(),n=process.cwd()){let r=vl(e)?[e]:[cr(t,e),cr(n,e)];for(let i of r){if(!wl(i))continue;let o;try{o=kl(i)}catch{continue}let a=Il(o);if(a===null)continue;let c=Sl(a,o);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(El).join("/")}}return null}function Il(e){try{let t=_l("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function Cl(){return fo({repoRoot:J()})}var Tl,Yt=_(()=>{"use strict";mo();s(xl,"probeNativeStore");s(Rl,"isNativeStoreUnavailable");Tl="codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";s(J,"resolveRepoRoot");s(Al,"resolveRepoRootForPath");s(lr,"resolveRepoRootForDir");s(Il,"gitToplevelOf");s(Cl,"defaultEngineFactory")});var Ll=_(()=>{"use strict"});import{existsSync as ho,readdirSync as ny,readFileSync as ry}from"node:fs";import{spawnSync as iy}from"node:child_process";import{dirname as oy,join as go,posix as sy}from"node:path";function jl(e){let t=[],n={host:"127.0.0.1",port:e.config.source==="missing"?null:e.config.port,configSource:e.config.source,reachable:null,ledgerCount:null};if(e.config.source==="missing")return t.push({id:`db.config_missing:${e.dir}`,status:"open",project:e.dir,title:"supabase/config.toml nirgends auffindbar \u2014 DB-Ziel unbekannt",detail:`Weder dieser Tree noch der Haupt-Worktree tragen eine config.toml f\xFCr ${e.dir}. Die Supabase-CLI w\xFCrde hier still auf ihren Default-Port ${yo} 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 ${yo} 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,h={psql_missing:{title:"psql nicht im PATH \u2014 Ledger nicht lesbar",detailText:"Ohne psql kann der lokale Ledger nicht gelesen werden. Kein Urteil \xFCber Drift m\xF6glich.",hint:"psql installieren (z. B. `brew install libpq` + PATH) oder den lokalen Stack-Client nachr\xFCsten."},unreachable:{title:`lokale Datenbank auf 127.0.0.1:${e.config.port} nicht erreichbar`,detailText:"Der Port aus config.toml antwortet nicht \u2014 der Stack schl\xE4ft vermutlich. Scheitert wenigstens laut (anders als die Default-Port-Falle); ein Urteil \xFCber Drift ist trotzdem nicht m\xF6glich.",hint:"`npx supabase start` im Projekt, dann erneut pr\xFCfen."},no_ledger:{title:`Port ${e.config.port} antwortet, tr\xE4gt aber KEINEN Supabase-Ledger`,detailText:"supabase_migrations.schema_migrations existiert dort nicht. Mutma\xDFlich lauscht auf diesem Port eine FREMDE Datenbank \u2014 dieselbe Verwechslungsklasse wie die 54322-Panne, nur von der anderen Seite gesehen.",hint:"Pr\xFCfen, wer auf dem Port lauscht (`lsof -nP -iTCP:<port> -sTCP:LISTEN`), und die config.toml gegen das Projekt halten."},query_failed:{title:"Ledger-Abfrage fehlgeschlagen",detailText:`Die SELECT-Abfrage gegen supabase_migrations.schema_migrations scheiterte${f?`: ${f}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:h.title,detail:h.detailText,hint:h.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),o=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!i.has(p)).sort(ue);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:"`npx supabase migration up` im Projektverzeichnis (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen.",versions:a});let c=r.versions.filter(p=>!o.has(p)).sort(ue),l=new Map,u=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let m=l.get(f)??[];m.push(p),l.set(f,m)}else u.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(u.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${u.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${u.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:u}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),f=e.fileVersions.filter(h=>!p.has(h)).sort(ue),m=e.remote.versions.filter(h=>!o.has(h)).sort(ue);f.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${f.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${f.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:f}),m.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${m.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${m.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:m})}let d=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:d,findings:t,db:n}}function Hl(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Gl(e,t){if(t==="enoent")return{ok:!1,reason:"psql_missing"};let n=e.toLowerCase();return n.includes("does not exist")&&n.includes("schema_migrations")?{ok:!1,reason:"no_ledger"}:n.includes("connection refused")||n.includes("could not connect")||n.includes("timeout expired")||n.includes("server closed the connection")||n.includes("connection timed out")?{ok:!1,reason:"unreachable"}:{ok:!1,reason:"query_failed",detail:e.split(`
|
|
119
|
+
`).filter(Boolean).slice(-1)[0]}}function $l(e,t,n){let r=e(t,ay,n);return r.ok===!1?Gl(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
|
|
120
|
+
`).map(i=>i.trim()).filter(Boolean)}}function Kl(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 cy(e){let t=S(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=oy(t);return n===e?null:n}function ly(e,t,n){let r=sy.dirname(t),o=[{path:go(e,r,"config.toml"),source:"worktree"}],a=cy(e);a&&o.push({path:go(a,r,"config.toml"),source:"main_worktree"});for(let c of o)if(ho(c.path))try{let l=Kl(ry(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 dy(e,t){let n=new Map,r=S(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=S(e,["rev-parse","--show-toplevel"])?.trim();for(let o of r.split(`
|
|
121
|
+
`)){if(!o.startsWith("worktree "))continue;let a=o.slice(9).trim();if(!a||a===i||!ho(a))continue;let c=go(a,t);if(ho(c))try{for(let l of ny(c)){let u=et(l);u!==null&&!n.has(u)&&n.set(u,a)}}catch{}}return n}function bo(e,t={}){let n=t.runPsql??Ul,r=t.timeoutMs??15e3,i=[],o=Ae(e,t.dirs);if(o.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let a=[],c=[],l=[];for(let p of o){let f=ly(e,p.dir,i),m=f.source==="missing"?null:$l(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),h=t.remoteDbUrl!==void 0?$l(n,t.remoteDbUrl,r):null,g=jl({dir:p.dir,fileVersions:p.files.map(y=>y.version),config:f,ledger:m,siblingVersions:dy(e,p.dir),remote:h});a.push(...g.findings),l.push(g.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:g.verdict,db:g.db})}let u=Hl(l),d={open:0,warn:1,info:2};return a.sort((p,f)=>d[p.status]-d[f.status]||p.id.localeCompare(f.id)),{ok:u==="in_sync",verdict:u,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var yo,Ul,ay,Bl=_(()=>{"use strict";q();Ft();yo=54322;s(jl,"evaluateLedgerProject");s(Hl,"deriveLedgerVerdict");Ul=s((e,t,n)=>{let r=iy("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"),ay="select version from supabase_migrations.schema_migrations order by version";s(Gl,"classifyLedgerError");s($l,"readLedger");s(Kl,"parseDbPort");s(cy,"mainWorktreeRoot");s(ly,"resolveConfig");s(dy,"gatherSiblingVersions");s(bo,"checkMigrationLedgerDrift")});var Wl,Xt=_(()=>{"use strict";Ll();so();pi();to();vi();gi();jt();er();Gt();Ft();Zn();Bl();Mi();eo();jt();Gt();er();Zn();Nn();ci();Vt();Wl="0.1.0"});import{execFile as Zl}from"node:child_process";import{randomUUID as _y}from"node:crypto";function xy(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return wo.test(t)?t:_y()}function ko(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function Ry(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 Ty(e){return await new Promise(t=>{Zl("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(Ay(r))})})}function Ay(e){let t=(e??"").trim().toLowerCase();return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t)?t:null}async function Iy(){return await new Promise(e=>{Zl("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 Cy(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function Ny(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=wo.test(r)&&r===t?"env":"random";return{current:s(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:s(()=>!1,"tryUpgrade"),adopt:s(o=>{wo.test(o)&&(n=o.trim().toLowerCase())},"adopt"),activityAtMs:s(()=>null,"activityAtMs")}}var Ql,ed,wy,ky,vy,Sy,Ey,wo,mr,vo=_(()=>{"use strict";Xe();Ql=45e3,ed=3e4,wy=5,ky=120,vy=3e4,Sy=15*6e4,Ey=1500,wo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(xy,"resolveClientSessionId");s(ko,"autoAnnounceDisabled");s(Ry,"autoWorkingPathsEnabled");mr=class{static{s(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;lastBranch=null;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??ne)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??Iy,this.gitBranchObject=t.gitBranchObject??Ty,this.log=t.log??(i=>process.stderr.write(i+`
|
|
122
|
+
`)),this.machineLabel=Cy(r?.machine_label),this.enabled=this.projectKey!==null&&!ko(n,r),this.workingPathsEnabled=Ry(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??Ny(n,xy(n)),this.sessionMeta=t.sessionMeta??null}get sessionId(){return this.identity.current().id}get isEnabled(){return this.enabled}onSessionReady(){!this.enabled||this.ended||this.lastAnnounceAt>0||this.announce("active")}onActivity(){!this.enabled||this.ended||this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<Ql||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<Ql||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<wy||(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,Ey).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(vy*2**(this.consecutiveFailures-1),Sy);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:ky,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let o=await this.gitBranch();if(o&&(r.branch=o),this.lastBranch=o,o)try{let a=await this.gitBranchObject(o);a!==null&&a!==this.lastSentObjectId&&(r.object_ids=[a],this.lastSentObjectId=a)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.sessionMeta!==null)try{let a=await this.sessionMeta();a?.model&&(r.model=a.model),a?.title&&(r.title=a.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let a=await this.deriveWorkingPaths();a&&a.length>0&&(r.working_paths=a)}catch{}}let i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let o=i;if(o.ok===!0&&typeof o.session_id=="string")try{this.identity.adopt(o.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let o={sessionId:this.sessionId,branch:this.lastBranch},a=typeof i=="object"?i:null;if(a!==null&&a.ok===!0)this.snapshot.write(i,o);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,o)}}}catch{}}};s(Ty,"defaultGitBranchObject");s(Ay,"normalizeObjectId");s(Iy,"defaultGitBranch");s(Cy,"normalizeMachineLabel");s(Ny,"staticIdentity")});import{mkdirSync as td,readdirSync as od,readFileSync as Py,renameSync as nd,statSync as Dy,unlinkSync as sd,writeFileSync as rd}from"node:fs";import{homedir as Oy}from"node:os";import{join as ft}from"node:path";function ad(){return ft(Oy(),".maind","presence")}function cd(e,t){return ft(e,t)}function ld(e){let t=e.baseDir??ad(),n=cd(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,o=e.cwd??process.cwd(),a=e.now??Date.now,c=null;return{write(l,u){try{if(typeof l!="object"||l===null)return;let d=l;if(d.ok!==!0)return;let p={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:Array.isArray(d.peers)?d.peers:[],conflicts:Array.isArray(d.conflicts)?d.conflicts:[]};td(n,{recursive:!0,mode:448}),c=ft(n,`${u.sessionId}.json`);let f=`${c}.tmp-${r}`;rd(f,JSON.stringify(p),{mode:384}),nd(f,c),id(n,a(),c)}catch{}},endSession(){try{c&&sd(c)}catch{}},markFailed(l,u){try{let d={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:o,branch:u.branch,peers:[],conflicts:[],announce_error:l};td(n,{recursive:!0,mode:448}),c=ft(n,`${u.sessionId}.json`);let p=`${c}.tmp-${r}`;rd(p,JSON.stringify(d),{mode:384}),nd(p,c),id(n,a(),c)}catch{}}}}function id(e,t,n){try{for(let r of od(e)){if(!r.endsWith(".json"))continue;let i=ft(e,r);if(i!==n)try{t-Dy(i).mtimeMs>My&&sd(i)}catch{}}}catch{}}function mt(e,t=ad()){try{let n=cd(t,e),r=[];for(let i of od(n))if(i.endsWith(".json"))try{let o=JSON.parse(Py(ft(n,i),"utf8")),a=Fy(o);a&&r.push(a)}catch{}return r.sort((i,o)=>o.written_at.localeCompare(i.written_at)),r}catch{return[]}}function Fy(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 My,hr=_(()=>{"use strict";My=120*6e4;s(ad,"presenceSnapshotBaseDir");s(cd,"projectDir");s(ld,"createSnapshotStore");s(id,"pruneStale");s(mt,"readSnapshots");s(Fy,"parseSnapshot")});import{execFileSync as Ly}from"node:child_process";import{createHash as $y,randomUUID as jy}from"node:crypto";import{existsSync as Hy,mkdirSync as Uy,readdirSync as Gy,readFileSync as ud,renameSync as Ky,statSync as So,unlinkSync as pd,writeFileSync as By}from"node:fs";import{homedir as Wy}from"node:os";import{basename as Vy,join as ke}from"node:path";function ht(e){return ke(e??ke(Wy(),".maind","presence"),"identity")}function fd(e,t){if(e){let n=Vy(e).replace(/\.jsonl$/i,"");if(Qt.test(n))return n.toLowerCase()}return t&&Qt.test(t)?t.toLowerCase():null}function md(e){let t=e.nowMs??Date.now();Uy(e.dir,{recursive:!0,mode:448});let n=ke(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(ud(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let o=e.transcriptPath??i.transcript_path,a=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...o?{transcript_path:o}:{},...a?{model:a}:{}};By(r,JSON.stringify(c,null,2)+`
|
|
123
|
+
`,{mode:384}),Ky(r,n),Xy(e.dir,t)}function hd(e,t,n,r=Date.now()){try{let i=So(ke(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function gd(e,t){try{pd(ke(e,`${t}.json`))}catch{}}function Xy(e,t){try{for(let n of Gy(e))if(n.endsWith(".json"))try{let r=So(ke(e,n));t-r.mtimeMs>Jy&&pd(ke(e,n))}catch{}}catch{}}function Qy(e){return yd(e)?.file??null}function yd(e){let t=ke(e.dir,`${e.agentPid}.json`);try{if(!Hy(t))return null;let n=So(t);if(n.mtimeMs<e.bridgeStartMs-zy)return null;let r=JSON.parse(ud(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Qt.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!Zy(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function dd(e){return e.replace(/\/+$/,"")}function Zy(e,t){let n=dd(e),r=dd(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function eb(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=$y("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 tb(e){if(process.platform==="win32")return null;try{let t=Ly("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function nb(){try{return U()}catch{return null}}var Qt,qy,Jy,zy,Yy,gr,yr=_(()=>{"use strict";B();Qt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,qy=8,Jy=48*60*6e4,zy=6e4,Yy="9f3c72da-2f10-4b8f-9c31-ad291c0de291";s(ht,"identityDirPath");s(fd,"transcriptStemOf");s(md,"writeAgentIdentityFile");s(hd,"identityFileStale");s(gd,"deleteAgentIdentityFile");s(Xy,"pruneIdentityDir");s(Qy,"readAgentIdentityFile");s(yd,"readAgentIdentityEntry");s(dd,"normDir");s(Zy,"sameSessionTree");s(eb,"uuidV5");s(tb,"processStartTime");gr=class{static{s(this,"SessionIdentityManager")}env;agentPid;cwd;dir;bridgeStartMs;nowMs;envId;id;source;aliases=[];constructor(t){this.env=t.env??process.env,this.agentPid=t.agentPid??process.ppid,this.cwd=t.cwd??process.cwd(),this.dir=t.identityDir??ht(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Qt.test(n)?n:null;let r=this.readStem();if(r!==null){this.id=r,this.source="client_native",this.envId&&this.envId!==r&&(this.aliases=[this.envId]);return}if(this.envId!==null){this.id=this.envId,this.source="env";return}let i=(t.deviceId??nb)(),o=(t.ppidStart??tb)(this.agentPid);if(i!==null&&o!==null&&t.projectKey!==null){this.id=eb(`${i}|${this.agentPid}|${o}|${t.projectKey}`,Yy),this.source="derived";return}this.id=jy(),this.source="random"}current(){return{id:this.id,source:this.source,aliases:[...this.aliases]}}tryUpgrade(){if(this.source==="client_native")return!1;let t=this.readStem();if(t===null||t===this.id)return!1;let n=this.id;return this.id=t,this.source="client_native",this.pushAlias(n),this.envId!==null&&this.pushAlias(this.envId),!0}adopt(t){let n=t.trim().toLowerCase();if(!Qt.test(n)||n===this.id)return;let r=this.id;this.id=n,this.pushAlias(r)}pushAlias(t){t===this.id||this.aliases.includes(t)||(this.aliases.push(t),this.aliases.length>qy&&this.aliases.shift())}activityAtMs(){return yd({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let t=this.sideChannel();return t===null?null:t.transcript_stem.toLowerCase()}sideChannel(){return Qy({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};s(nb,"defaultDeviceId")});function Eo(){return{ultracode:!1,planMode:!1,autoMode:!1}}var xo=_(()=>{"use strict";s(Eo,"newModeState")});import{createReadStream as rb,existsSync as ib}from"node:fs";import{stat as ob}from"node:fs/promises";import{createInterface as sb}from"node:readline";async function Ro(e){if(!e||!ib(e))return null;let t;try{t=await ob(e)}catch{return null}let n=new Set,r=0,i=0,o=0;return await new Promise(a=>{let c=rb(e,{encoding:"utf-8"}),l=sb({input:c});l.on("line",u=>{let d=u.trim();if(d){o++;try{let p=JSON.parse(d),f=p.message?.usage;if(!f)return;let m=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,h=typeof p.requestId=="string"&&p.requestId?p.requestId:null,g=m??h;if(g!==null){if(n.has(g))return;n.add(g)}typeof f.input_tokens=="number"&&(r+=f.input_tokens),typeof f.output_tokens=="number"&&(i+=f.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:o,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var bd=_(()=>{"use strict";s(Ro,"summariseTranscript")});var _d=_(()=>{"use strict"});function Zt(e){if(!e)return null;let t=null;for(let n of e.matchAll(cb)){let r=n[1].toLowerCase();ab.has(r)&&(t=r)}return t}var ab,cb,br=_(()=>{"use strict";ab=new Set(["low","medium","high","xhigh","max"]),cb=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;s(Zt,"detectEffortLevel")});import{createReadStream as lb,existsSync as db,readdirSync as ub}from"node:fs";import{basename as vd,dirname as pb,join as wd}from"node:path";import{createInterface as fb}from"node:readline";function gt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function gb(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let i=hb[r.name];if(!i||!r.input||typeof r.input!="object")continue;let o=r.input[i];typeof o=="string"&&o.length>0&&t.push(o)}return t}function Sd(e){let t=vd(e).replace(/\.jsonl$/,""),n=wd(pb(e),t,"subagents"),r;try{r=ub(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>wd(n,i))}async function kd(e,t,n,r,i){db(e)&&await new Promise(o=>{let a=lb(e,{encoding:"utf-8"}),c=fb({input:a}),l=0;c.on("line",u=>{l++;let d=u.trim();if(!d)return;let p;try{p=JSON.parse(d)}catch{return}if(p.message?.role!=="assistant")return;let f=typeof p.message.id=="string"&&p.message.id?p.message.id:null,m=typeof p.requestId=="string"&&p.requestId?p.requestId:null,h=f??m??`${e}#${l}`,g=gb(p.message.content),y=r.get(h);if(y){for(let E of g)y.edited_paths.includes(E)||y.edited_paths.push(E);return}if(n.has(h))return;n.add(h);let b=p.message.usage??{},w=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,v=typeof p.message.model=="string"&&p.message.model?p.message.model:"",k={ts:Number.isFinite(w)?w:0,model:v||"<unknown>",synthetic:v===mb,input_tokens:gt(b.input_tokens),output_tokens:gt(b.output_tokens),cache_read_tokens:gt(b.cache_read_input_tokens),cache_creation_tokens:gt(b.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(gt(b.cache_creation?.ephemeral_1h_input_tokens),gt(b.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:t,edited_paths:g,cwd:typeof p.cwd=="string"&&p.cwd?p.cwd:null};r.set(h,k),i.push(k)}),c.on("close",()=>o()),c.on("error",()=>o()),a.on("error",()=>o())})}function To(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];i.ts>0?n=i.ts:n>0&&(i.ts=n)}}async function en(e){let t=new Set,n=new Map,r=[],i=e?Sd(e):[];if(!e)return{turns:r,subagent_files:i};let o=[];await kd(e,Fe,t,n,o),To(o),r.push(...o);for(let a of i){let c=[],l=vd(a).replace(/\.jsonl$/,"");await kd(a,l,t,n,c),To(c);for(let u of c)u.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:i}}var Fe,mb,hb,_r=_(()=>{"use strict";Fe="main",mb="<synthetic>",hb={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};s(gt,"num");s(gb,"editedPathsOf");s(Sd,"subagentFilesOf");s(kd,"readStream");s(To,"fillTimestamps");s(en,"collectTurns")});import{createReadStream as yb,existsSync as bb}from"node:fs";import{createInterface as _b}from"node:readline";function Rb(e,t,n,r,i){let o=`${n?"s":"m"}:${t}`,a=e.get(o);if(!a){e.set(o,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}a.turns++,a.output_tokens+=r,i>0&&((a.first_ts===0||i<a.first_ts)&&(a.first_ts=i),i>a.last_ts&&(a.last_ts=i))}function Ao(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function Tb(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
124
|
+
`)}function Ab(e,t){let n=s(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(u=>u.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[o,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of o)a.has(l)&&c++;return c/o.size>=.8}function Ib(e,t,n){return wb.test(e)?{polarity:-1,magnitude:yt.rework,kind:"rework"}:n&&kb.test(e)?{polarity:-1,magnitude:yt.correction,kind:"correction"}:vb.test(e)?{polarity:1,magnitude:yt.acceptance,kind:"acceptance"}:t!==null&&Ab(t,e)?{polarity:-1,magnitude:yt.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function Cb(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:xd}}async function Io(e,t={}){let n=Cb("");if(!e||!bb(e))return n;let r=t.turns??(await en(e)).turns;for(let m of r)n.input_tokens+=m.input_tokens,n.output_tokens+=m.output_tokens,n.cache_read_tokens+=m.cache_read_tokens,n.cache_creation_tokens+=m.cache_creation_tokens,m.sidechain||n.assistant_turns++;let i=[],o=new Map,a=null,c=!1,l=null;await new Promise(m=>{let h=yb(e,{encoding:"utf-8"}),g=_b({input:h}),y=s(b=>{let w=b.trim();if(!w)return;let v;try{v=JSON.parse(w)}catch{return}if(n.lines_seen++,!n.session_id){let N=v.sessionId??v.session_id;typeof N=="string"&&N&&(n.session_id=N)}v.type==="ai-title"&&typeof v.aiTitle=="string"&&v.aiTitle&&(n.ai_title=v.aiTitle),typeof v.slug=="string"&&v.slug&&(n.session_slug=v.slug);let k=v.message?.role,E=v.isSidechain===!0;if(k==="assistant")for(let N of Ao(v.message?.content)){if(N.type!=="tool_use"||typeof N.name!="string"||!N.name.startsWith(Ed))continue;let Be=N.name.slice(Ed.length);Be&&(n.maind_tool_calls[Be]=(n.maind_tool_calls[Be]??0)+1)}if(E)return;if(k==="assistant"){let N=Ao(v.message?.content),Be=!1;for(let hs of N)hs.type==="tool_use"&&(n.tool_calls++,Be=!0,hs.name==="AskUserQuestion"&&n.agent_questions++);c=Be;return}if(k!=="user")return;let R=Ao(v.message?.content),I=Tb(R);if(I.includes(Sb)){n.interrupts++,i.push({polarity:-1,magnitude:yt.interrupt,kind:"interrupt"});return}if(R.some(N=>N.type==="tool_result"&&N.is_error===!0&&typeof N.content=="string"&&N.content.includes(Eb))){n.tool_denials++,i.push({polarity:-1,magnitude:yt.denial,kind:"denial"});return}if(R.some(N=>N.type==="tool_result")||!I.trim())return;n.user_turns++,n.user_chars+=I.length;let T=Zt(I);T&&(a=T);let j=Ib(I,l,c);l=I,j.kind==="correction"?n.corrections++:j.kind==="rework"?n.reworks++:j.kind==="repeat"?n.repeated_instructions++:j.kind==="acceptance"&&n.acceptances++,j.polarity!==0&&i.push(j),c=!1},"processLine");g.on("line",b=>{try{y(b)}catch{}}),g.on("close",()=>m()),g.on("error",()=>m()),h.on("error",()=>m())}),n.effort_at_end=a;for(let m of r)m.synthetic||m.model==="<unknown>"||Rb(o,m.model,m.sidechain,m.output_tokens,m.ts);n.model_mix=[...o.values()].sort((m,h)=>m.first_ts-h.first_ts||m.model.localeCompare(h.model)),n.user_token_estimate=Math.round(n.user_chars/4);let u=n.user_token_estimate+n.output_tokens;n.human_share=u>0?Number((n.user_token_estimate/u).toFixed(4)):0;let d=0,p=0,f=[];return i.forEach((m,h)=>{m.polarity>0?n.reactions_pos++:m.polarity<0&&n.reactions_neg++,d=d*xb+m.polarity*m.magnitude;let g=Number(d.toFixed(3));f.push({t:h,value:g,...m.kind!=="neutral"?{kind:m.kind}:{}}),p+=g,h>0&&i[h-1].polarity<0&&m.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls).length>0&&(n.maind_connected="connected"),n}var Ed,xd,wb,kb,vb,Sb,Eb,xb,yt,Rd=_(()=>{"use strict";br();_r();Ed="mcp__maind__",xd="2026-09-04",wb=/(\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,kb=/(\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,vb=/(\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,Sb="[Request interrupted by user",Eb="The user doesn't want to proceed with this tool use",xb=.7,yt={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};s(Rb,"bumpModel");s(Ao,"asBlocks");s(Tb,"textOf");s(Ab,"isRepeat");s(Ib,"classifyGenuine");s(Cb,"emptyAnalysis");s(Io,"analyzeSession")});function Co(e){let t=e!==null&&typeof e=="object"?e:{},n=typeof t.slices_stored=="boolean"?t.slices_stored:null;return{analyticsStored:t.analytics_stored===!0,spanStored:t.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof t.slices_reason=="string"?t.slices_reason:null,slicesCount:typeof t.slices_count=="number"&&Number.isFinite(t.slices_count)?t.slices_count:0}}function No(e,t){return!t||e.slicesStored===!0?null:e.slicesStored===null?"cost slices sent, verdict unknown \u2014 the ingest endpoint predates slice verdicts (redeploy mcp-client-metrics-ingest)":`cost slices not stored: ${e.slicesReason??"no reason given"} (${e.slicesCount} sent)`}function Po(e,t,n,r="unknown",i){let o={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};return t&&t.started_at&&(o.session_span=n?{...t,...n}:t),o}var Td=_(()=>{"use strict";s(Co,"parseIngestResponse");s(No,"describeSliceVerdict");s(Po,"ingestBody")});import{isAbsolute as Ad,relative as Nb,resolve as Id,sep as Cd}from"node:path";function wr(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Mo(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=s(a=>{if(!Array.isArray(a))return[];let c=[];for(let l of a){if(!l||typeof l!="object")continue;let u=l,d=wr(u.from);typeof u.object_id!="string"||!Do.test(u.object_id)||d===null||c.push({object_id:u.object_id.toLowerCase(),from:d,to:wr(u.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=wr(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:wr(c.to)})}let o=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let c=a;typeof c.object_id!="string"||!Do.test(c.object_id)||typeof c.path_prefix=="string"&&o.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Do.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:o}}function Pd(e,t){if(!Ad(e))return null;let n=Nb(Id(t),Id(e));return!n||n==="."||n.startsWith("..")||Ad(n)?null:Cd==="/"?n:n.split(Cd).join("/")}function Pb(e,t){return t===""||e===t||e.startsWith(t+"/")}function Fo(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Dd(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function Lo(e,t){for(let n of Dd(t))if(Pb(e,n.path_prefix))return n.object_id;return null}function Db(e,t){for(let n of Dd(t))if(Fo(e,n.path_prefix))return n.object_id;return null}function Oo(e,t){return e>=t.from&&(t.to===null||e<t.to)}function Od(e,t,n,r){let i=e.ts,o=r?.anchors??[],a=t.map(c=>Lo(c,o)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(d=>Oo(i,d));if(c.length)return c.sort((d,p)=>p.from-d.from||d.object_id.localeCompare(p.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(d=>Oo(i,d));if(l.length)return{object_id:(l.find(p=>a.includes(p.object_id))??l.find(p=>n!==null&&p.object_id===n.object_id)??[...l].sort((p,f)=>p.object_id.localeCompare(f.object_id))[0]).object_id,source:"binding"};let u=r.claims.filter(d=>Oo(i,d));if(u.length){let d=t[0]??n?.rel??null,p=(d===null?u:u.filter(f=>Fo(f.path_prefix,d))).sort((f,m)=>m.path_prefix.length-f.path_prefix.length);for(let f of p){let m=Db(f.path_prefix,o);if(m)return{object_id:m,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function $o(e,t,n){let r=t?.anchors??[],i=s(h=>{if(!n.repoRoot)return[];let g=[];for(let y of h.edited_paths){let b=Pd(y,n.repoRoot);b!==null&&!g.includes(b)&&g.push(b)}return g},"relOf"),o=s(h=>{for(let g of h){let y=Lo(g,r);if(y)return{object_id:y,rel:g}}return null},"firstAnchoredEdit"),a=new Map;for(let h of e){let g=a.get(h.stream)??[];g.push(h),a.set(h.stream,g)}let c=[...a.entries()].sort(([h],[g])=>h===Fe?-1:g===Fe?1:0),l=[],u=s(h=>{let g=null;for(let y of l){if(y.ts>h&&h>0)break;g=y.seg}return g},"mainSegmentAt"),d=new Map;for(let[h,g]of c){let y=g.map((w,v)=>({t:w,i:v,rels:i(w)})).sort((w,v)=>w.t.ts-v.t.ts||w.i-v.i),b=null;for(let w of y){let v=o(w.rels);if(v){b=v;break}}!b&&h!==Fe&&y.length&&(b=u(y[0].t.ts));for(let w of y){let v=o(w.rels);v&&(b=v),h===Fe&&l.push({ts:w.t.ts,seg:b});let k=w.t;if(k.input_tokens+k.output_tokens+k.cache_read_tokens+k.cache_creation_tokens===0)continue;let R=Od(k,w.rels,b,t),I=k.input_tokens+k.cache_read_tokens+k.cache_creation_tokens>Nd?"above_200k":"standard",A=`${R.object_id??""}|${R.source}|${k.model}|${I}`,T=d.get(A);T||(T={object_id:R.object_id,attribution_source:R.source,model:k.model,context_tier:I,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},d.set(A,T)),T.input_tokens+=k.input_tokens,T.output_tokens+=k.output_tokens,T.cache_read_tokens+=k.cache_read_tokens,T.cache_creation_tokens+=k.cache_creation_tokens,T.cache_creation_1h_tokens+=k.cache_creation_1h_tokens,T.turns+=1,k.ts>0&&((T.firstMs===0||k.ts<T.firstMs)&&(T.firstMs=k.ts),k.ts>T.lastMs&&(T.lastMs=k.ts))}}let p=n.nowMs??Date.now(),f=[];for(let h of d.values()){let{firstMs:g,lastMs:y,...b}=h;b.first_ts=new Date(g>0?g:p).toISOString(),b.last_ts=new Date(y>0?y:p).toISOString(),f.push(b)}let m={lease:0,binding:1,claim:2,path:3,none:4};return f.sort((h,g)=>m[h.attribution_source]-m[g.attribution_source]||(h.object_id??"").localeCompare(g.object_id??"")||h.model.localeCompare(g.model)||h.context_tier.localeCompare(g.context_tier)),f}var Nd,Do,Md=_(()=>{"use strict";_r();Nd=2e5,Do=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(wr,"msOf");s(Mo,"parseCostContext");s(Pd,"toRepoRelative");s(Pb,"underPrefix");s(Fo,"prefixesOverlap");s(Dd,"sortedAnchors");s(Lo,"anchorFor");s(Db,"bestAnchorOverlapping");s(Oo,"inWindow");s(Od,"assignTurn");s($o,"sliceSession")});import{createReadStream as Ob,existsSync as Mb}from"node:fs";import{createInterface as Fb}from"node:readline";function Fd(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function jb(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
125
|
+
`)}function jd(e){return{session_id:e,started_at:null,ended_at:null,wall_seconds:0,agent_seconds:0,wait_seconds:0,pauses:[],pause_count:0,pause_seconds:0,pauses_truncated:!1,turn_count:0,event_count:0}}function Hb(e){let t=e.message?.role;if(t==="assistant")return{holder:Fd(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Fd(e.message?.content),r=jb(n);return r.includes(Lb)?{holder:"human",genuine:!1}:n.some(o=>o.type==="tool_result"&&o.is_error===!0&&typeof o.content=="string"&&o.content.includes($b))?{holder:"agent",genuine:!1}:n.some(o=>o.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function jo(e){let t=jd("");if(!e||!Mb(e))return t;let n=null,r=0,i=0,o=null,a="human",c=[];return await new Promise(l=>{let u=Ob(e,{encoding:"utf-8"}),d=Fb({input:u}),p=s(f=>{let m=f.trim();if(!m)return;let h;try{h=JSON.parse(m)}catch{return}if(!t.session_id){let b=h.sessionId??h.session_id;typeof b=="string"&&b&&(t.session_id=b)}if(h.isSidechain===!0)return;let g=typeof h.timestamp=="string"?Date.parse(h.timestamp):NaN;if(!Number.isFinite(g)||o!==null&&g<o)return;let y=Hb(h);if(y!==null){if(t.event_count++,y.genuine&&t.turn_count++,n===null&&(n=g),r=g,o!==null){let b=g-o;a==="agent"?i+=b:b>=Ld*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(b/1e3),c.length<$d&&c.push({offset_seconds:Math.round((o-n)/1e3),duration_seconds:Math.round(b/1e3)}))}o=g,a=y.holder}},"processLine");d.on("line",f=>{try{p(f)}catch{}}),d.on("close",()=>l()),d.on("error",()=>l()),u.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var Lb,$b,Ld,$d,Hd=_(()=>{"use strict";Lb="[Request interrupted by user",$b="The user doesn't want to proceed with this tool use",Ld=60,$d=200;s(Fd,"asBlocks");s(jb,"textOf");s(jd,"emptySpan");s(Hb,"classify");s(jo,"analyzeSpan")});import{createReadStream as Ub,existsSync as Gb}from"node:fs";import{createInterface as Kb}from"node:readline";function Wb(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function kr(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Vb(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=[];for(let n of e)if(n&&typeof n=="object"&&"text"in n){let r=n.text;typeof r=="string"&&t.push(r)}return t.join(`
|
|
126
|
+
`)}return""}async function Ho(e,t={}){if(!e||!Gb(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Eo(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,o=t.initialModes?{...t.initialModes}:Eo(),a=t.start??0;return await new Promise(c=>{let l=Ub(e,{encoding:"utf-8",start:t.start??0}),u=Kb({input:l});u.on("line",p=>{a+=Buffer.byteLength(p,"utf-8")+1;let f=p.trim();if(!f)return;let m;try{m=JSON.parse(f)}catch{return}let h=m.sessionId??m.session_id??"",g=m.timestamp?Date.parse(m.timestamp):Date.now(),y=m.message?.role;if(m.type==="ai-title"&&typeof m.aiTitle=="string"){n.push({kind:"title",session_id:h,ts:g,title:m.aiTitle});return}if(m.type==="attachment"&&m.attachment?.type){let b=Bb[m.attachment.type];b&&(o[Wb(b.mode)]=b.active,n.push({kind:"mode",session_id:h,ts:g,mode:b.mode,active:b.active}));return}if(y==="user"){let b=Vb(m.message?.content),w=Zt(b);w&&(i=w);let v={session_id:h,ts:g,text:b,effort_directive:w};n.push({kind:"user",...v});return}if(y==="assistant"){let b=m.message?.usage,w=typeof m.message?.id=="string"&&m.message.id?m.message.id:null,v=typeof m.requestId=="string"&&m.requestId?m.requestId:null,k=w??v,E=k!==null&&r.has(k);k!==null&&!E&&r.add(k);let R={session_id:h,ts:g,model:m.message?.model??null,input_tokens:E?0:kr(b?.input_tokens),output_tokens:E?0:kr(b?.output_tokens),cache_read_input_tokens:E?0:kr(b?.cache_read_input_tokens),cache_creation_input_tokens:E?0:kr(b?.cache_creation_input_tokens),effort:i,isSidechain:m.isSidechain===!0,...o.ultracode?{ultracode:!0}:{},...o.planMode?{planMode:!0}:{},...o.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...R})}});let d=s(()=>({events:n,bytesRead:a,effortAtEnd:i,modesAtEnd:{...o},seenMessagesAtEnd:new Set(r)}),"finalResult");u.on("close",()=>c(d())),u.on("error",()=>c(d())),l.on("error",()=>c(d()))})}var Bb,Ud=_(()=>{"use strict";br();xo();Bb={ultra_effort_enter:{mode:"ultracode",active:!0},ultra_effort_exit:{mode:"ultracode",active:!1},plan_mode:{mode:"plan",active:!0},plan_mode_reentry:{mode:"plan",active:!0},plan_mode_exit:{mode:"plan",active:!1},auto_mode:{mode:"auto",active:!0},auto_mode_exit:{mode:"auto",active:!1}};s(Wb,"modeFlagKey");s(kr,"num");s(Vb,"extractUserText");s(Ho,"streamTranscript")});var Gd=_(()=>{"use strict"});import{homedir as qb}from"node:os";import{join as Jb}from"node:path";function Go(e){return e.replace(/[/.]/g,"-")}var zb,Uo,Kd=_(()=>{"use strict";zb=qb(),Uo=Jb(zb,".claude","projects");s(Go,"projectPathFromCwd")});var tn=_(()=>{"use strict";xo();bd();_d();Rd();Td();_r();Md();Hd();Ud();br();Gd();Kd()});async function Vd(e){return Le("get_session_briefing",{tools:["claude-code"]},e)}async function Le(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??Ko,i=new AbortController,o=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let a={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n.apiKey}`,"x-maind-client-family":n.clientFamily??"claude-code","x-maind-client-version":n.bridgeVersion,"x-maind-bridge-version":n.bridgeVersion};n.deviceId&&(a["x-maind-device-id"]=n.deviceId),n.projectKey&&(a["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:a,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:i_,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),l=c.headers.get("mcp-session-id");if(await c.text().catch(()=>""),!c.ok||!l)return null;let u={...a,"mcp-session-id":l};await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(g=>g.text().catch(()=>"")).catch(()=>"");let d=await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!d.ok)return null;let f=(d.headers.get("content-type")??"").startsWith("text/event-stream")?await o_(d):await d.text();if(f.trim().length===0)return null;let m=JSON.parse(f);if(m.error||m.result?.isError)return null;let h=m.result?.content?.find(g=>g.type==="text"&&typeof g.text=="string")?.text;return typeof h=="string"&&h.trim().length>0?h:null}catch{return null}finally{clearTimeout(o)}}async function o_(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o="",a=s(()=>{if(i.length===0)return;let c=i.join(`
|
|
127
127
|
`).trim();i=[],c.length>0&&(o=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let u;for(;(u=r.indexOf(`
|
|
128
|
-
`))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let p=d.endsWith("\r")?d.slice(0,-1):d;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return a(),o}var Ko,
|
|
128
|
+
`))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let p=d.endsWith("\r")?d.slice(0,-1):d;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return a(),o}var Ko,i_,nn=_(()=>{"use strict";Ko="https://mcp.maind.dev/mcp",i_="2025-06-18";s(Vd,"fetchSessionBriefing");s(Le,"fetchToolText");s(o_,"readSseMessage")});function s_(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":U()}}async function qd(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:s_(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 Sr,Bo=_(()=>{"use strict";B();Sr=process.env.MAIND_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";s(s_,"ingestHeaders");s(qd,"postMetrics")});function Jd(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function Yd(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,o=Array.isArray(i.active_claims)?i.active_claims:[],a=[];for(let c of o){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let d=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;d<=0||a.push({path_prefix:l.path_prefix,note:typeof l.note=="string"?l.note:null,remaining_seconds:Math.round(d)})}n.push({session_id_short:typeof i.session_id_short=="string"?i.session_id_short:"?",is_own_user:i.is_own_user===!0,branch:typeof i.branch=="string"?i.branch:null,focus:typeof i.focus=="string"?i.focus:null,machine_label:typeof i.machine_label=="string"?i.machine_label:null,last_seen_seconds:typeof i.last_seen_seconds=="number"?i.last_seen_seconds:0,claims:a,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function bt(e,t){if(t.hostPids.length>0){let r=e.find(i=>t.hostPids.includes(i.own_ppid));if(r)return{snap:r,via:"ppid"}}let n=e.find(r=>r.cwd===t.cwd);return n?{snap:n,via:"cwd"}:null}function rn(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function Xd(e,t,n){let r=n.maxAgeMs??zd,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let o=i/1e3,a=Yd(e,o),c=[];for(let l of a)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let u of l.claims)Jd(t,u.path_prefix)&&c.push(`'${u.path_prefix}' is CLAIMED by peer session ${l.session_id_short}${l.branch?` (branch ${l.branch}`:" ("}${l.machine_label?`, ${l.machine_label}`:""}${l.focus?`, focus: "${l.focus}"`:""}, last seen ${rn(l.last_seen_seconds+o)} ago)${u.note?` \u2014 note: "${u.note}"`:""}, claim expires in ${rn(u.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let u of l.working_paths)if(Jd(t,u)){c.push(`'${u}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${rn(l.last_seen_seconds+o)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${rn(o)} ago, advisory \u2014 never a lock):
|
|
129
129
|
`+c.map(l=>` \u2022 ${l}`).join(`
|
|
130
130
|
`)+`
|
|
131
|
-
Verify live before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: ["${t}"]}) \u2014 then claim_paths for your own edit area.`}function
|
|
132
|
-
${m}`:m}var
|
|
133
|
-
`),
|
|
131
|
+
Verify live before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: ["${t}"]}) \u2014 then claim_paths for your own edit area.`}function Qd(e,t,n,r=zd,i=null){if(!e)return null;let o=n-Date.parse(e.written_at);if(!Number.isFinite(o)||o<0||o>r)return null;let a=o/1e3,c=Yd(e,a),l=i!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${i}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let u=c.reduce((h,g)=>h+g.claims.length,0),d=c.filter(h=>h.focus===null&&h.working_paths.length===0&&h.claims.length===0).length,p=u>0?`${u} active claim${u===1?"":"s"}`:"no active claims",f=d>0?`, ${d} presence-only`:"",m=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${rn(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
|
|
132
|
+
${m}`:m}var zd,Wo=_(()=>{"use strict";s(Jd,"prefixConflict");zd=10*6e4;s(Yd,"parsePeers");s(bt,"selectOwnSnapshot");s(rn,"ageDisplay");s(Xd,"adviseOnPath");s(Qd,"sessionStartSummary")});async function C(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=s(o=>{n||(n=!0,clearTimeout(i),t(o))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",o=>e.push(o)),process.stdin.on("end",()=>{try{let o=Buffer.concat(e).toString("utf-8").trim();r(o?JSON.parse(o):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function on(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function ie(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var oe=_(()=>{"use strict";s(C,"readHookInput");s(on,"transcriptPathOf");s(ie,"toolFilePathOf")});function _t(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function ve(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function Zd(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}var wt=_(()=>{"use strict";s(_t,"denyPayload");s(ve,"advisoryPayload");s(Zd,"postAdvisoryPayload")});import{realpathSync as a_}from"node:fs";import{basename as eu,dirname as tu,join as c_}from"node:path";function $e(e){let t=tu(e),n=[eu(e)];for(;;)try{let r=a_(t);return c_(r,...n.reverse())}catch{let r=tu(t);if(r===t)return e;n.push(eu(t)),t=r}}var Er=_(()=>{"use strict";s($e,"realpathOfUnwritten")});import{mkdir as l_,readFile as d_,writeFile as u_,rename as p_}from"node:fs/promises";import{existsSync as ru}from"node:fs";import{homedir as f_}from"node:os";import{join as iu}from"node:path";function nu(){return{config:null,sessions:{},pending_metrics:[]}}async function $(){if(!ru(xr))return nu();try{let e=await d_(xr,"utf-8"),t=JSON.parse(e);return{config:t.config??null,sessions:t.sessions??{},pending_metrics:Array.isArray(t.pending_metrics)?t.pending_metrics:[],thresholds:t.thresholds,thresholds_synced_at:t.thresholds_synced_at,guard_signals:t.guard_signals,repo_health_seen:t.repo_health_seen,write_health_seen:t.write_health_seen}}catch(e){return process.stderr.write(`[maind-mcp-bridge] state.json corrupt, resetting: ${e instanceof Error?e.message:String(e)}
|
|
133
|
+
`),nu()}}async function se(e){ru(je)||await l_(je,{recursive:!0,mode:448});let t=`${xr}.tmp`;await u_(t,JSON.stringify(e,null,2),{mode:384}),await p_(t,xr)}function Vo(e){return e.thresholds??e.config?.thresholds??m_}var je,xr,m_,He=_(()=>{"use strict";je=iu(f_(),".maind"),xr=iu(je,"state.json"),m_={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};s(nu,"emptyState");s($,"loadState");s(se,"saveState");s(Vo,"resolveThresholds")});import{existsSync as h_,realpathSync as g_,statSync as y_}from"node:fs";import{dirname as ou,isAbsolute as b_,join as __}from"node:path";function v_(e,t){let n=e.filter(i=>su.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let o=i.hint?`
|
|
134
134
|
\u2192 ${i.hint}`:"";return` \u2022 ${i.title}
|
|
135
135
|
${i.detail}${o}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
|
|
136
136
|
|
|
@@ -138,39 +138,39 @@ ${m}`:m}var Jd,Wo=_(()=>{"use strict";s(qd,"prefixConflict");Jd=10*6e4;s(zd,"par
|
|
|
138
138
|
|
|
139
139
|
`)+`
|
|
140
140
|
|
|
141
|
-
This is advisory; nothing is blocked. Resolve it before running build/test commands in this tree \u2014 otherwise the failure arrives later, disguised as your own change.`}function
|
|
141
|
+
This is advisory; nothing is blocked. Resolve it before running build/test commands in this tree \u2014 otherwise the failure arrives later, disguised as your own change.`}function S_(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function E_(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},o=i[t]??{};o[n]=new Date(r).toISOString(),i[t]=o,e.repo_health_seen=i}function qo(e){let t=ou(e);for(;;){try{if(y_(t).isDirectory())return t}catch{}let n=ou(t);if(n===t)return t;t=n}}async function x_(e,t,n){let r=await n.load();if(S_(r,e,t))return null;E_(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let o=i.filter(c=>su.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:w_,metric_value:1},{session_id:e,metric_key:k_,metric_value:o}),await n.save(a),v_(i,t)}async function au(){try{let e=await C(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"";if(!n)return 0;let r=ie(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=b_(r)?r:__(i,r),a=h_(o)?g_(o):$e(o),c=ae(qo(a)),l=await x_(n,c,{load:$,save:se,check:s(async u=>(await Lt(u,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(ve(l)),0}catch{return 0}}var su,w_,k_,Jo=_(()=>{"use strict";Xt();qe();wt();oe();Er();He();su=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],w_="repo_health_hook_runs",k_="repo_health_hook_findings";s(v_,"formatRepoHealth");s(S_,"alreadySeen");s(E_,"markSeen");s(qo,"nearestExistingDir");s(x_,"repoHealthForEdit");s(au,"runOnRepoHealth")});import{existsSync as R_,readFileSync as T_,realpathSync as A_}from"node:fs";import{isAbsolute as lu,join as du,posix as I_,relative as C_,sep as N_}from"node:path";function cu(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function F_(e,t){return{contracts:t.filter(r=>cu(r.spec)===e||cu(r.impl)===e).map(r=>r.id),theme:O_.test(e),acl:M_.test(e)}}function L_(e){return e.contracts.length===0&&!e.theme&&!e.acl}function $_(e,t,n,r,i=Date.now()){let o=e.write_health_seen??{},a=o[t]??{},c=new Set(a[n]?.keys??[]),l=r.filter(u=>!c.has(u.key));if(l.length>0){for(let u of l)c.add(u.key);a[n]={at:new Date(i).toISOString(),keys:[...c]},o[t]=a,e.write_health_seen=o}return l}function j_(e,t){return e.length===0?null:`maind write-health \u2014 your edit to ${t} makes these checks relevant, and each finding below is reported once per session:
|
|
142
142
|
|
|
143
143
|
`+e.map(n=>` \u2022 ${n.line}`).join(`
|
|
144
144
|
`)+`
|
|
145
145
|
|
|
146
|
-
Advisory; nothing is blocked. These are findings THIS branch introduces (pre-existing ones are graded out) \u2014 fix them now, or they surface at the gate.`}function
|
|
147
|
-
`)}}catch{}try{let r=Pt(
|
|
148
|
-
`)}}catch{}return 0}function
|
|
146
|
+
Advisory; nothing is blocked. These are findings THIS branch introduces (pre-existing ones are graded out) \u2014 fix them now, or they surface at the gate.`}function H_(e,t){let n=C_(e,t);return!n||n.startsWith("..")||lu(n)?null:n.split(N_).join(I_.sep)}function U_(e){try{let t=T_(du(e,qn),"utf8"),{manifest:n}=Xn(t);return n?.contracts??[]}catch{return[]}}async function uu(){try{let e=await C(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=ie(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o=lu(r)?r:du(i,r),a=R_(o)?A_(o):$e(o),c=ae(qo(a)),l=H_(c,a);if(l===null)return 0;let u=F_(l,U_(c));if(L_(u))return 0;let d=[];if(u.contracts.length>0)try{let h=await Ne(c,{contracts:u.contracts});for(let g of h.findings)g.status==="open"&&d.push({key:`spec:${g.id}`,line:`spec-drift (${g.contract}): ${g.detail}`})}catch{}if(u.theme)try{let h=De(c);for(let g of h.findings)g.status==="open"&&d.push({key:`theme:${g.file}:${g.klass}`,line:`theme-class-drift: \`${g.klass}\` in ${g.file} \u2014 no token \`--color-${g.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(u.acl)try{let h=Pe(c);for(let g of h.findings)g.status==="open"&&d.push({key:`acl:${g.id}`,line:`table-acl-lint: \`${g.table}\` (created in ${g.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let p=await $(),f=$_(p,n,c,d);p.pending_metrics.push({session_id:n,metric_key:P_,metric_value:1},{session_id:n,metric_key:D_,metric_value:f.length}),await se(p);let m=j_(f,l);return m!==null&&process.stdout.write(Zd(m)),0}catch{return 0}}var P_,D_,O_,M_,pu=_(()=>{"use strict";Xt();qe();wt();oe();Jo();Er();He();P_="write_health_hook_runs",D_="write_health_hook_findings",O_=/\.(tsx?|jsx?|css)$/,M_=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;s(cu,"declPath");s(F_,"routesForPath");s(L_,"routesAreEmpty");s($_,"takeUnreported");s(j_,"formatWriteHealth");s(H_,"repoRelative");s(U_,"readContracts");s(uu,"runOnWriteHealth")});var Eu={};V(Eu,{agentHostPidCandidates:()=>me,closeTrackedSession:()=>_u,effectiveConfig:()=>Ue,grandparentPid:()=>ku,recordGuardSignals:()=>bu,runFlush:()=>rw,runHookStatus:()=>iw,runOnFileEdit:()=>ew,runOnFileWrite:()=>Z_,runOnRepoHealth:()=>au,runOnSessionStart:()=>J_,runOnToolUse:()=>X_,runOnWriteHealth:()=>uu,runSessionEndMetrics:()=>Yo,runSyncConfig:()=>sw,writeIdentitySideChannel:()=>zo});import{execFileSync as mu}from"node:child_process";import{existsSync as Ar,readFileSync as hu,realpathSync as G_}from"node:fs";import{writeFile as K_}from"node:fs/promises";import{homedir as gu}from"node:os";import{isAbsolute as Tr,join as sn,relative as yu}from"node:path";function bu(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=n.includes("search_lessons")||n.includes("get_session_briefing")||n.includes("get_lesson")||n.includes("get_conventions")||n.includes("activate_skill")||n.includes("suggest_skills")||n.includes("codebase_change_briefing"),o=n.includes("review_changes");if(!i&&!o)return;let a=e.guard_signals??{},c=a[t]??{},l=new Date(r).toISOString();i&&(c.consulted_at=l),o&&(c.reviewed_at=l),a[t]=c,e.guard_signals=a}function _u(e,t,n=Date.now()){q_(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 q_(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let i=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0);t-i>Rr&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(o=>Date.parse(o)||0));t-i>Rr&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let i=Math.max(0,...Object.values(r).map(o=>Date.parse(o.at)||0));t-i>Rr&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let i=Date.parse(r.started_at);!Number.isNaN(i)&&t-i>Rr&&delete e.sessions[n]}}function Ue(e){if(e.config)return e.config;let t=D();return t===null?null:{api_key:t,endpoint:Sr}}function wu(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 J_(){let e=await $();if(Ue(e)===null)return 0;let t=await C(),n=Su(t);if(n===null)return 0;wu(e,n),await se(e);try{zo(t,n)}catch{}try{let r=O();if(r!==null){let i=mt(r),o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=bt(i,{hostPids:me(),cwd:o}),c=Qd(a?.snap??i[0]??null,a?.snap.own_session_id??null,Date.now(),void 0,a?.snap.announce_error??null);c!==null&&process.stdout.write(c+`
|
|
147
|
+
`)}}catch{}try{let r=Pt(z_());if(Yr(r)&&Tn(r)){let i=r.filter(o=>o.remedy==="run-install").map(o=>o.subcommand).join(", ");process.stderr.write(`[maind] New bridge capability not yet wired (${i}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
|
|
148
|
+
`)}}catch{}return 0}function z_(){try{let e=sn(gu(),".claude","settings.json");return Ar(e)?hu(e,"utf8"):null}catch{return null}}function zo(e,t,n,r=ht()){let i=n??me();if(i.length===0)return;let o=fd(on(e)||null,t);if(o===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=on(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let u of i)md({dir:r,agentPid:u,sessionId:t,transcriptStem:o,cwd:a,transcriptPath:c,model:l})}function ku(){try{if(process.platform==="win32")return null;let e=mu("ps",["-o","ppid=","-p",String(process.ppid)],{timeout:1e3,encoding:"utf8"}),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function me(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=ku();return n!==null&&n>1&&n!==t&&e.push(n),e}async function X_(){let e=await $();if(Ue(e)===null)return 0;let t=await C(),n=Su(t)??"unknown",r=wu(e,n);r.tool_call_count+=1;try{let a=me().filter(c=>hd(ht(),c,Y_));n!=="unknown"&&a.length>0&&zo(t,n,a)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),bu(e,n,i);let o=t.transcript_path;if(typeof o=="string"&&o&&!r.transcript_path&&(r.transcript_path=o),r.transcript_path){let a=await Ro(r.transcript_path);a&&(r.token_count=a.total_tokens,await nw(e,r))}return await se(e),0}function Q_(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
|
|
149
149
|
`);return`${t.prefix}${e.number} is already taken:
|
|
150
150
|
${n}
|
|
151
151
|
|
|
152
152
|
Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
|
|
153
153
|
|
|
154
|
-
Renumbering later is not the same cost: once the index entry, the links and the commit message name the number, every one of them has to be rewritten.`}async function
|
|
154
|
+
Renumbering later is not the same cost: once the index entry, the links and the commit message name the number, every one of them has to be rewritten.`}async function Z_(){try{let e=await C();if((e.tool_name??"")!=="Write")return 0;let t=ie(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=Tr(t)?t:sn(n,t);if(Ar(r))return 0;let i=ae(n),o=yu(i,$e(r));if(o.length===0||o.startsWith("..")||Tr(o))return 0;let a=await Ce(i,o);return!a.taken||a.namespace===null||process.stdout.write(_t(Q_(a,a.namespace))),0}catch{return 0}}async function ew(){try{let e=await C(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=ie(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=Tr(n)?n:sn(r,n),o=O();if(o===null)return 0;let a=mt(o);if(a.length===0)return 0;let c=bt(a,{hostPids:me(),cwd:r});if(c===null)return 0;let l=ae(r),u=Ar(i)?G_(i):$e(i),d=yu(l,u).replace(/\\/g,"/");if(d.length===0||d.startsWith("..")||Tr(d))return 0;let p=Xd(c.snap,d,{via:c.via,currentBranch:c.via==="cwd"?tw(r):null,nowMs:Date.now()});return p===null||process.stdout.write(ve(p)),0}catch{return 0}}function tw(e){try{let n=mu("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 nw(e,t){let n=Vo(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,o="ok";if(i>=n.handoff_at_pct/100?o="handoff_recommended":i>=n.warn_at_pct/100&&(o="warn"),t.last_advisory_status===o||(t.last_advisory_status=o,o==="ok"))return;let a=Math.round(i*100),c={session_id:t.session_id,status:o,tokens:r,ratio:Number(i.toFixed(3)),pct:a,thresholds:n,suggested_next:o==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await K_(sn(je,`handoff_advisory_${t.session_id}.json`),JSON.stringify(c,null,2))}catch(l){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${l instanceof Error?l.message:String(l)}
|
|
155
155
|
`)}o==="warn"?process.stderr.write(`[maind] \u26A0 Token usage at ~${a}% (warn threshold ${n.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
|
|
156
156
|
`):process.stderr.write(`[maind] \u26D4 Token usage at ~${a}% (handoff threshold ${n.handoff_at_pct}%). Strongly consider compiling a HANDOFF brief and starting a fresh session \u2014 call recommend_handoff or generate_handoff_brief.
|
|
157
|
-
`)}async function Yo(e){try{let t=await $(),n=Ue(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(
|
|
158
|
-
`)}}async function
|
|
159
|
-
`),n.ok?0:1}async function
|
|
157
|
+
`)}async function Yo(e){try{let t=await $(),n=Ue(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(_u(t,r),await se(t)),await vu(n,W_)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
|
|
158
|
+
`)}}async function rw(){let e=await $(),t=Ue(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=await vu(t,V_);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
159
|
+
`),n.ok?0:1}async function vu(e,t){let n=await $();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=qd(e.endpoint,e.api_key,r),o=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([i,o]);if(a.ok){let c=await $();return c.pending_metrics=c.pending_metrics.slice(r.length),await se(c),{ok:!0,flushed:r.length,remaining:c.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:a.error}}async function iw(){let e=await $(),t=Ue(e),n=ow(),r=Yr(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:Vo(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})),...Tn(n.findings)?{remedy:fu}:{}}},null,2)+`
|
|
160
160
|
`),r){process.stderr.write(`
|
|
161
161
|
[maind] Claude Code hook wiring is incomplete:
|
|
162
162
|
`);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
|
|
163
|
-
`);Tn(n.findings)&&process.stderr.write(` ${
|
|
164
|
-
`)}return 0}function
|
|
163
|
+
`);Tn(n.findings)&&process.stderr.write(` ${fu}
|
|
164
|
+
`)}return 0}function ow(){let e=sn(gu(),".claude","settings.json"),t=null;try{Ar(e)&&(t=hu(e,"utf8"))}catch{}return{settingsPath:e,findings:Pt(t)}}async function sw(){let e=await $(),t=Ue(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=t.thresholds_endpoint??B_,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(a){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${a instanceof Error?a.message:String(a)}
|
|
165
165
|
`),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
|
|
166
166
|
`);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
|
|
167
167
|
`),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
|
|
168
168
|
`),1}let o=i;return typeof o.warn_at_pct!="number"||typeof o.handoff_at_pct!="number"||typeof o.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
|
|
169
169
|
`),1):(e.thresholds={warn_at_pct:o.warn_at_pct,handoff_at_pct:o.handoff_at_pct,model_token_limit:o.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await se(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
|
|
170
|
-
`),0)}function
|
|
171
|
-
`)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([o,a])}async function
|
|
172
|
-
`)}return await Yo(n),0}var
|
|
173
|
-
`,384)}var Ge=_(()=>{"use strict";Xe();ce();s(Q,"resolveGuardConfig");s(kt,"writeGuardConfig")});function
|
|
170
|
+
`),0)}function Su(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var B_,W_,V_,Rr,Y_,fu,Xo=_(()=>{"use strict";tn();Xt();qe();B();Dt();hr();ge();Bo();Wo();yr();oe();wt();Er();He();Jo();pu();B_=process.env.MAIND_THRESHOLDS_ENDPOINT??"https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds",W_=1500,V_=1e4,Rr=7*24*60*60*1e3;s(bu,"recordGuardSignals");s(_u,"closeTrackedSession");s(q_,"gcState");s(Ue,"effectiveConfig");s(wu,"getOrCreateSession");s(J_,"runOnSessionStart");s(z_,"readSettingsRaw");s(zo,"writeIdentitySideChannel");Y_=6e4;s(ku,"grandparentPid");s(me,"agentHostPidCandidates");s(X_,"runOnToolUse");s(Q_,"denyReason");s(Z_,"runOnFileWrite");s(ew,"runOnFileEdit");s(tw,"currentGitBranch");s(nw,"maybeEmitAdvisory");s(Yo,"runSessionEndMetrics");s(rw,"runFlush");s(vu,"flushPending");s(iw,"runHookStatus");fu="Re-run `maind-mcp-bridge install` to add the missing hooks \u2014 it is append-only and idempotent: it adds only what is absent, asks consent per hook, and never rewrites an entry you already have.";s(ow,"readHookWiring");s(sw,"runSyncConfig");s(Su,"sessionIdOf")});function xu(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Ru=_(()=>{"use strict";s(xu,"resolveConnection")});function Au(e,t,n,r=Date.now()){let i=t===null?null:Mo(t),o=$o(e,i,{repoRoot:n,nowMs:r});return o.length===0?null:{slices:o,context_ok:i!==null}}var Tu,Iu=_(()=>{"use strict";tn();Tu=2e3;s(Au,"buildCostPayload")});function Cu(e){if(!e||e.announce_error!=null)return null;let t=e.own_session_id;return typeof t=="string"&&aw.test(t)?t.toLowerCase():null}var aw,Nu=_(()=>{"use strict";aw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;s(Cu,"snapshotSessionId")});var Pu={};V(Pu,{runOnSessionEnd:()=>hw});import{execFileSync as cw}from"node:child_process";function dw(e,t){try{let n=O(),r=n!==null&&!ko(process.env,ne()),i=null;if(n!==null){let o=bt(mt(n),{hostPids:me(),cwd:process.cwd()});if(o){let a=Date.parse(o.snap.written_at);i=Number.isFinite(a)?Math.max(0,t-a):null}}return xu({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function uw(){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;try{let n=O();if(n!==null){let r=bt(mt(n),{hostPids:me(),cwd:process.cwd()}),i=Cu(r?.snap);if(i!==null)return i}}catch{}let t=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return e.test(t)?t:null}function pw(){try{let e=cw("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}async function fw(e,t,n,r){if(n===null)return null;try{return await Le("get_session_cost_context",{project_key:n,...r?{session_id:r}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:P,timeoutMs:Tu})}catch{return null}}async function mw(e,t,n,r,i){let o=fetch(lw,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":P},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=No(Co(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
|
|
171
|
+
`)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([o,a])}async function hw(){try{for(let i of me())gd(ht(),i)}catch{}let e=D();if(!e)return 0;let t=await C(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=on(t);if(r)try{let i=U(),o=uw(),a=O(),c=fw(e,i,a,o),{turns:l}=await en(r),[u,d,p]=await Promise.all([Io(r,{turns:l}),jo(r),c]);if(n&&(u.session_id=n,d.session_id=n),u.maind_connected=dw(u.maind_connected==="connected",Date.now()),u.session_id){let f=Au(l,p,pw()),m=Po(u,d,{client_session_id:o,client:"claude-code"},"live_bridge",f);await mw(e,i,m,1500,f!==null)}}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
|
|
172
|
+
`)}return await Yo(n),0}var lw,Du=_(()=>{"use strict";tn();Xe();B();nn();Bo();Wo();oe();Xo();vo();hr();ge();yr();xe();Ru();Iu();Nu();lw=Sr;s(dw,"connectionVerdict");s(uw,"presenceSessionId");s(pw,"sessionRepoRoot");s(fw,"fetchCostContext");s(mw,"postWithTimeout");s(hw,"runOnSessionEnd")});function Q(e=process.env,t=ne()){let n=e.MAIND_GUARD;return{mode:n==="off"||n==="warn"||n==="block"?n:t?.guard_mode??"off",stopGate:t?.guard_stop_gate===!0}}async function kt(e,t=de()){let n={};try{let i=await G(t);if(i!==null&&i.trim().length>0){let o=JSON.parse(i);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}let r={...n,...e};await F(t,JSON.stringify(r,null,2)+`
|
|
173
|
+
`,384)}var Ge=_(()=>{"use strict";Xe();ce();s(Q,"resolveGuardConfig");s(kt,"writeGuardConfig")});function gw(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 Ou(e,t,n=process.stdout){let r=gw(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
|
|
174
174
|
`),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},o=[];for(let l of Rn)o.push(await ei(i,l));for(let l of o)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
|
|
175
175
|
`);let a=o.some(l=>l.detail==="user declined"),c=o.some(l=>l.status==="failed");return r.dryRun?(n.write(`
|
|
176
176
|
[dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
|
|
@@ -181,77 +181,77 @@ Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
|
|
|
181
181
|
check: maind-mcp-bridge guard status
|
|
182
182
|
Takes effect for NEW Claude Code sessions (hooks are read at session start).
|
|
183
183
|
`),a&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
|
|
184
|
-
`),c?1:0)}var
|
|
185
|
-
`;await
|
|
186
|
-
`);for(let l of i>0?c.slice(1):c)if(l.trim())try{let u=JSON.parse(l);typeof u.event=="string"&&u.event in t&&(t[u.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var Et,xt=_(()=>{"use strict";St();Et=
|
|
184
|
+
`),c?1:0)}var Mu=_(()=>{"use strict";Dt();ti();Ge();s(gw,"parseGuardInstallFlags");s(Ou,"runGuardInstall")});import{existsSync as Fu}from"node:fs";import{mkdir as yw,readFile as bw,readdir as _w,rename as ww,stat as kw,unlink as vw,writeFile as Sw}from"node:fs/promises";import{join as Ir}from"node:path";function Lu(e){return Ir(an,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function he(e){try{let t=Lu(e);if(!Fu(t))return{};let n=JSON.parse(await bw(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function z(e,t){await yw(an,{recursive:!0,mode:448});let n=Lu(e),r=`${n}.tmp`;await Sw(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await ww(r,n)}async function $u(e=7*24*60*60*1e3,t=Date.now()){try{if(!Fu(an))return;for(let n of await _w(an)){if(!n.endsWith(".json"))continue;let r=Ir(an,n);try{let i=await kw(r);t-i.mtimeMs>e&&await vw(r)}catch{}}}catch{}}var vt,an,St=_(()=>{"use strict";He();vt=Ir(je,"guard"),an=Ir(vt,"sessions");s(Lu,"sessionFile");s(he,"loadGuardSession");s(z,"saveGuardSession");s($u,"sweepOldGuardSessions")});import{existsSync as Ew}from"node:fs";import{appendFile as xw,mkdir as Rw,open as Tw}from"node:fs/promises";import{join as Aw}from"node:path";async function W(e){try{await Rw(vt,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
|
|
185
|
+
`;await xw(Et,t,{mode:384})}catch{}}async function ju(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(!Ew(Et))return t;let n=await Tw(Et,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),o=Buffer.alloc(r-i);await n.read(o,0,o.length,i);let c=o.toString("utf8").split(`
|
|
186
|
+
`);for(let l of i>0?c.slice(1):c)if(l.trim())try{let u=JSON.parse(l);typeof u.event=="string"&&u.event in t&&(t[u.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var Et,xt=_(()=>{"use strict";St();Et=Aw(vt,"events.jsonl");s(W,"appendGuardEvent");s(ju,"readGuardEventCounts")});var Uu={};V(Uu,{runGuard:()=>Dw});import{existsSync as Iw,readFileSync as Cw}from"node:fs";import{homedir as Hu}from"node:os";import{join as Nw}from"node:path";async function Dw(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Ou(n,Hu());case"status":return Mw();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
|
|
187
187
|
`),1):(await kt({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
188
188
|
`),0)}case"off":return await kt({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
|
|
189
189
|
`),0;case"stop-gate":{let r=n[0];return r!=="on"&&r!=="off"?(process.stdout.write(`usage: maind-mcp-bridge guard stop-gate <on|off>
|
|
190
190
|
`),1):(await kt({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
191
|
-
`),0)}case"skip":return Ow(n);default:return process.stdout.write(
|
|
191
|
+
`),0)}case"skip":return Ow(n);default:return process.stdout.write(Pw),t===void 0||t==="--help"||t==="-h"?0:1}}async function Ow(e){let t=null,n=null;for(let o=0;o<e.length;o++)e[o]==="--session"?t=e[++o]??null:e[o]==="--reason"&&(n=e[++o]??null);if(!t||!n||n.trim().length===0)return process.stdout.write(`usage: maind-mcp-bridge guard skip --session <id> --reason "<why consultation is unnecessary here>"
|
|
192
192
|
`),1;let r=n.trim().slice(0,500),i=await he(t);return await z(t,{...i,override_reason:r}),await W({event:"override",session_id:t,reason:r,cwd:process.cwd()}),process.stdout.write(`override recorded for session ${t} \u2014 the gate opens on the next attempt.
|
|
193
193
|
logged (auditable) in ${Et}
|
|
194
|
-
`),0}async function
|
|
194
|
+
`),0}async function Mw(){let e=Q(),t=Nw(Hu(),".claude","settings.json"),n=null;try{Iw(t)&&(n=Cw(t,"utf8"))}catch{}let r=Pt(n,{},Rn),i=await ju();process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",hook_wiring:r.map(a=>({event:a.event,subcommand:a.subcommand,status:a.status,detail:a.detail})),events:i,events_file:Et},null,2)+`
|
|
195
195
|
`);let o=r.filter(a=>a.status!=="ok");if(e.mode==="off"&&process.stderr.write("\n[maind] guard is OFF \u2014 enable with `guard install` (first time) or `guard mode warn|block`.\n"),o.length>0&&e.mode!=="off"){process.stderr.write(`
|
|
196
196
|
[maind] guard hook wiring is incomplete:
|
|
197
197
|
`);for(let a of o)process.stderr.write(` \u2022 ${a.detail}
|
|
198
|
-
`);o.some(a=>a.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var
|
|
199
|
-
`);s(
|
|
200
|
-
`),0):(process.stdout.write(
|
|
198
|
+
`);o.some(a=>a.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var Pw,Gu=_(()=>{"use strict";Dt();Ge();Mu();xt();St();Pw=["usage: maind-mcp-bridge guard <verb>",""," install [--mode warn|block] [--stop-gate] [--full] [--dry-run]"," wire the guard hooks (consent per hook, append-only) + set the mode"," status mode, hook wiring, and local event counts"," mode <warn|block>"," flip enforcement hardness (config-only; settings.json untouched)"," off disable the guard (hooks stay wired, become no-ops)"," stop-gate <on|off>"," toggle the strict completion gate (review before finish)",' skip --session <id> --reason "<why>"'," record a logged override for one session (block-gate exit valve)",""].join(`
|
|
199
|
+
`);s(Dw,"runGuard");s(Ow,"runGuardSkip");s(Mw,"runGuardStatus")});var qu={};V(qu,{BRIEFING_CACHE_FILE:()=>Bu,formatInjection:()=>Vu,resolveBriefingInjection:()=>Wu,runGuardInject:()=>Ww});import{existsSync as Fw}from"node:fs";import{mkdir as Lw,readFile as $w,rename as jw,writeFile as Hw}from"node:fs/promises";import{dirname as Uw,join as Gw}from"node:path";async function Wu(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??Bu,o=n.fetcher??Vd,a=await Vw(i);if(a!==null&&r-Date.parse(a.fetched_at)<Kw&&a.project_key===e)return{text:a.text,via:"cache"};let l=await o({apiKey:t,deviceId:Jw(),projectKey:e,bridgeVersion:P,timeoutMs:Bw});return l!==null?(await qw(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:l}),{text:l,via:"fetch"}):a!==null?{text:a.text,via:"stale-cache"}:{text:null,via:"none"}}async function Ww(){try{if(Q().mode==="off")return 0;let t=await C(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;await $u();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let u=await he(n);return await z(n,{...u,carryover:!0}),0}let i=D();if(i===null)return 0;let o=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=O(),c=await Wu(a,i),l=await he(n);return c.text===null?(await z(n,{...l,inject_failed:!0}),await W({event:"inject_fail",session_id:n,cwd:o,project_key:a??void 0}),process.stderr.write(`[maind] guard: briefing fetch failed and no cache \u2014 session starts unbriefed; the model should call get_session_briefing itself.
|
|
200
|
+
`),0):(process.stdout.write(Vu(c.text,c.via)),await z(n,{...l,injected:!0}),await W({event:"inject_ok",session_id:n,cwd:o,project_key:a??void 0,detail:c.via}),0)}catch{return 0}}function Vu(e,t){let n=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=e;return Buffer.byteLength(r,"utf8")>Ku&&(r=r.slice(0,Ku)+`
|
|
201
201
|
\u2026 [maind guard: briefing truncated at 10KB]`),`[maind guard] Session briefing, injected deterministically (ADR-284)${n} \u2014 the session-start get_session_briefing consultation is satisfied by this block:
|
|
202
202
|
|
|
203
203
|
`+r+`
|
|
204
|
-
`}async function
|
|
204
|
+
`}async function Vw(e){try{if(!Fw(e))return null;let t=JSON.parse(await $w(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 qw(e,t){try{await Lw(Uw(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await Hw(n,JSON.stringify(t,null,2),{mode:384}),await jw(n,e)}catch{}}function Jw(){try{return U()}catch{return null}}var Bu,Kw,Bw,Ku,Ju=_(()=>{"use strict";B();oe();ge();xe();Ge();xt();St();nn();Bu=Gw(vt,"briefing-cache.json"),Kw=12*60*60*1e3,Bw=3e3,Ku=10*1024;s(Wu,"resolveBriefingInjection");s(Ww,"runGuardInject");s(Vu,"formatInjection");s(Vw,"readCache");s(qw,"writeCache");s(Jw,"safeDeviceId")});var Qu={};V(Qu,{decideGate:()=>Xu,runGuardGate:()=>Yw});function Xu(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:zu(n)}:(n.deny_count??0)>=Yu?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. "+zu(n)}:{kind:"deny",reason:zw(e.sessionId,n)}}function zu(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 zw(e,t){return`[maind guard | block] Edit denied \u2014 ${t.inject_failed===!0?"the automatic briefing injection failed for this session, so the consultation is still open":"no maind consultation has happened in this session"} (mandated by proc/maind-consultation-triggers). Two exits:
|
|
205
205
|
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
206
206
|
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
|
|
207
|
-
After ${
|
|
208
|
-
`,{mode:384}),await
|
|
209
|
-
`).filter(r=>r.trim());if(t.length<=
|
|
207
|
+
After ${Yu} denies this gate downgrades itself to warn.`}async function Yw(){try{let e=Q();if(e.mode==="off")return 0;let t=await C(),n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let i=await he(r),o=(await $()).guard_signals?.[r]?.consulted_at!==void 0,a=Xu({mode:e.mode,session:i,consulted:o,sessionId:r}),c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),l=O()??void 0;return a.kind==="deny"?(process.stdout.write(_t(a.reason)),await z(r,{...i,deny_count:(i.deny_count??0)+1}),await W({event:"deny",session_id:r,cwd:c,project_key:l}),0):a.kind==="warn"?(process.stdout.write(ve(a.context)),await z(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await W({event:"warn",session_id:r,cwd:c,project_key:l}),0):(await z(r,{...i,edits_seen:(i.edits_seen??0)+1}),0)}catch{return 0}}var Yu,Zu=_(()=>{"use strict";oe();wt();He();ge();Ge();xt();St();Yu=3;s(Xu,"decideGate");s(zu,"warnText");s(zw,"denyText");s(Yw,"runGuardGate")});var tp={};V(tp,{decideStopGate:()=>ep,runGuardStop:()=>Qw});function ep(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function Qw(){try{let e=Q();if(e.mode==="off"||!e.stopGate)return 0;let t=await C(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=await he(n),i=(await $()).guard_signals?.[n]?.reviewed_at!==void 0;return ep({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:Xw})),await z(n,{...r,stop_blocked:!0}),await W({event:"stop_block",session_id:n})),0}catch{return 0}}var Xw,np=_(()=>{"use strict";oe();He();Ge();xt();St();s(ep,"decideStopGate");Xw="[maind guard] Stop gate (strict, opt-in): this session edited files but review_changes never ran. Run the review over the edit batches \u2014 codebase_review_changes, then review_changes with its review_args (or `maind review` from the CLI) \u2014 report the findings, then finish. This gate blocks only once.";s(Qw,"runGuardStop")});import{appendFile as Zw,mkdir as ek,readFile as ip,rename as op,writeFile as sp}from"node:fs/promises";import{homedir as ap}from"node:os";import{join as cp}from"node:path";function lp(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},o=new Map,a=1/0,c=-1/0;for(let u of e){u.at<a&&(a=u.at),u.at>c&&(c=u.at);let d=i[u.tool]??={calls:0,warns:0,denies:0};if(u.event==="tool_call"?d.calls+=1:u.event==="policy_warn"||u.event==="sha_warn"?d.warns+=1:d.denies+=1,(u.event==="policy_warn"||u.event==="policy_deny")&&u.convention_id!==void 0&&u.convention_version!==void 0){let p=o.get(u.convention_id);(p===void 0||u.convention_version>p)&&o.set(u.convention_id,u.convention_version)}}let l=Object.entries(i).sort((u,d)=>d[1].calls+d[1].warns+d[1].denies-(u[1].calls+u[1].warns+u[1].denies)).slice(0,64);return{window_start:new Date(a).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...o.entries()].slice(0,32).map(([u,d])=>({convention_id:u,convention_version:d})),...r?{project_key:r}:{}}}function Ke(){return cp(ap(),".maind","gateway","attest-spool.jsonl")}async function Qo(e){let t=D();if(t===null)return!1;let n=await Le("gateway_attest",{...e},{apiKey:t,deviceId:U(),projectKey:e.project_key??null,bridgeVersion:P,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function dp(e){try{await ek(cp(ap(),".maind","gateway"),{recursive:!0}),await Zw(Ke(),JSON.stringify(e)+`
|
|
208
|
+
`,{mode:384}),await tk()}catch{}}async function tk(){try{let t=(await ip(Ke(),"utf8")).split(`
|
|
209
|
+
`).filter(r=>r.trim());if(t.length<=rp)return;let n=`${Ke()}.${process.pid}.tmp`;await sp(n,t.slice(-rp).join(`
|
|
210
210
|
`)+`
|
|
211
|
-
`,{mode:384}),await
|
|
212
|
-
`).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await Qo(i)||(n=!0,t.push(r))}try{let r=`${Ke()}.${process.pid}.tmp`;await
|
|
211
|
+
`,{mode:384}),await op(n,Ke())}catch{}}async function up(){let e;try{e=(await ip(Ke(),"utf8")).split(`
|
|
212
|
+
`).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await Qo(i)||(n=!0,t.push(r))}try{let r=`${Ke()}.${process.pid}.tmp`;await sp(r,t.length>0?t.join(`
|
|
213
213
|
`)+`
|
|
214
|
-
`:"",{mode:384}),await
|
|
215
|
-
`,384)}async function
|
|
216
|
-
`),2;let n=ee({entryPath:te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of
|
|
217
|
-
`);continue}let a=
|
|
218
|
-
`);continue}if(!(t.yes||await
|
|
214
|
+
`:"",{mode:384}),await op(r,Ke())}catch{}}var rp,pp=_(()=>{"use strict";B();nn();xe();rp=256;s(lp,"aggregateWindow");s(Ke,"attestSpoolPath");s(Qo,"postAttestation");s(dp,"spoolAttestation");s(tk,"capSpool");s(up,"flushAttestSpool")});function cn(e=process.env,t=ne()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Cr(e=process.env,t=ne()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function fp(e,t=de()){let n={};try{let i=await G(t);if(i!==null&&i.trim().length>0){let o=JSON.parse(i);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(n=o)}}catch{}let r={...n,...e};await F(t,JSON.stringify(r,null,2)+`
|
|
215
|
+
`,384)}async function mp(e,t=de()){await fp({gateway_mode:e},t)}async function hp(e,t=de()){await fp({gateway_attest:e},t)}function gp(e=process.env,t=ne()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var Zo=_(()=>{"use strict";Xe();ce();s(cn,"resolveGatewayMode");s(Cr,"resolveGatewayAttest");s(fp,"writeGatewayConfigPatch");s(mp,"writeGatewayMode");s(hp,"writeGatewayAttest");s(gp,"resolveShaProofMode")});function bp(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,o=i.gateway_gate;if(typeof o!="object"||o===null)continue;let a=o;if(a.enabled!==!0)continue;let c=typeof i.id=="string"&&i.id.length>0&&i.id.length<=64?i.id:null,l=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||l===null)continue;let u=typeof i.severity=="string"&&nk.has(i.severity)?i.severity:"recommended",d=typeof i.summary=="string"?i.summary:"",p=Array.isArray(a.servers)?a.servers.filter(m=>typeof m=="string"&&m.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(m=>typeof m=="string"&&m.length>0):[];for(let m of f){if(n.length>=256)return n;n.push({tool:m,servers:p,conventionId:c,conventionVersion:l,severity:u,summary:d})}}return n}function rk(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function _p(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let o of n)rk(o,e,t)&&(i===null||yp[o.severity]>yp[i.severity])&&(i=o);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function wp(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 nk,yp,es=_(()=>{"use strict";nk=new Set(["required","recommended","info"]);s(bp,"extractGatewayRules");yp={required:2,recommended:1,info:0};s(rk,"ruleMatches");s(_p,"decideToolCall");s(wp,"policyDenyText")});import{mkdirSync as ik,readFileSync as ok,renameSync as sk,writeFileSync as ak}from"node:fs";import{homedir as ck}from"node:os";import{dirname as lk,join as dk}from"node:path";function kp(){return dk(ck(),".maind","gateway","policy-cache.json")}function Nr(e,t,n=new Date().toISOString()){try{let r={version:ts,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=kp();ik(lk(i),{recursive:!0});let o=`${i}.${process.pid}.tmp`;ak(o,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),sk(o,i)}catch{}}function Pr(e){try{let t=ok(kp(),"utf8"),n=JSON.parse(t);return n.version!==ts||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:ts,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var ts,ns=_(()=>{"use strict";ts=1;s(kp,"policyCachePath");s(Nr,"writePolicyCache");s(Pr,"readPolicyCache")});function ln(e=process.env){let t=e.MAIND_MCP_URL??Ko,n=D();return{mcpUrl:t,keyFp:n?fn(n):"anon"}}async function Dr(e=6e3){let t=D();if(t===null)return null;let n=null;try{n=O()}catch{n=null}let r=await Le("get_conventions",{},{apiKey:t,deviceId:U(),projectKey:n,bridgeVersion:P,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return bp(i)}var rs=_(()=>{"use strict";qe();B();nn();ge();xe();es();s(ln,"policyIdentity");s(Dr,"fetchGatewayRules")});function dn(e){let t=Array.isArray(e.args)?e.args.map(String):[],n=t.indexOf("gateway");if(n===-1||t.indexOf("--",n+1)===-1)return!1;if(n===0)return!0;let r=[String(e.command??""),...t.slice(0,n)].join(" ");return/maind-mcp-bridge|@maind-dev\/mcp-bridge|\.js\s*$/.test(r)}function uk(e){if(dn(e))return!1;let t=typeof e.command=="string"?e.command:"",n=Array.isArray(e.args)?e.args:[],r=[t,...n.map(String)].join(" ");return r.includes("maind-mcp-bridge")||/@maind-dev\/mcp-bridge/.test(r)}function pk(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:dn(e)?{action:"skip",reason:"already-wrapped"}:uk(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function vp(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],o=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=o||t.env?{...o??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return a&&(c.env=a),c}function Sp(e){if(!dn(e))return null;let t=e.args.map(String),n=t.indexOf("--",t.indexOf("gateway")+1);return n===-1||n+1>=t.length?null:{...e,command:t[n+1],args:t.slice(n+2)}}function Ep(e){return Object.entries(e).map(([t,n])=>{let r=pk(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var xp=_(()=>{"use strict";s(dn,"isGatewayWrapped");s(uk,"isMaindProxyEntry");s(pk,"classifyServer");s(vp,"wrapServerEntry");s(Sp,"unwrapServerEntry");s(Ep,"planRewrites")});var Np={};V(Np,{runGatewayInstall:()=>bk,runGatewayUninstall:()=>_k});import{existsSync as fk,readFileSync as mk}from"node:fs";import{homedir as hk}from"node:os";import{join as Rp}from"node:path";import{createInterface as gk}from"node:readline";function Tp(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 Ap(){return[{label:"Claude Code (project .mcp.json)",path:Rp(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:Rp(hk(),".claude.json")}]}async function Ip(e){let t=gk({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 Cp(e){let t=yk(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 yk(e){try{return fk(e)?mk(e,"utf8"):null}catch{return null}}async function bk(e){let t=Tp(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
216
|
+
`),2;let n=ee({entryPath:te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of Ap()){let o=Cp(i.path);if(o===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
|
|
217
|
+
`);continue}let a=Ep(o.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
|
|
218
|
+
`);continue}if(!(t.yes||await Ip(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
|
|
219
219
|
Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
|
|
220
220
|
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
|
|
221
|
-
`);continue}o.servers[c.key]=
|
|
221
|
+
`);continue}o.servers[c.key]=vp(o.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
|
|
222
222
|
`)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await F(i.path,JSON.stringify(o.raw,null,2)+`
|
|
223
223
|
`,384)}return process.stderr.write(r>0?`
|
|
224
224
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
|
|
225
225
|
`:`
|
|
226
226
|
Nothing to wrap.
|
|
227
|
-
`),0}async function
|
|
228
|
-
`),2;let n=0;for(let r of
|
|
227
|
+
`),0}async function _k(e){let t=Tp(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
228
|
+
`),2;let n=0;for(let r of Ap()){let i=Cp(r.path);if(i===null)continue;let o=!1;for(let[a,c]of Object.entries(i.servers)){if(!dn(c)||!(t.yes||await Ip(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let u=Sp(c);if(u===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
|
|
229
229
|
`);continue}i.servers[a]=u,o=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
|
|
230
230
|
`)}!t.dryRun&&o&&await F(r.path,JSON.stringify(i.raw,null,2)+`
|
|
231
231
|
`,384)}return process.stderr.write(n>0?`
|
|
232
232
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
|
|
233
233
|
`:`
|
|
234
234
|
Nothing wrapped \u2014 nothing to restore.
|
|
235
|
-
`),0}var
|
|
235
|
+
`),0}var Pp=_(()=>{"use strict";ce();Ye();xp();s(Tp,"parseFlags");s(Ap,"targets");s(Ip,"confirm");s(Cp,"loadConfig");s(yk,"readFileSafeSync");s(bk,"runGatewayInstall");s(_k,"runGatewayUninstall")});var Dp={};V(Dp,{runGatewayAttest:()=>kk,runGatewayMode:()=>wk,runGatewayPolicy:()=>Ek});async function wk(e){let t=e[0];if(t===void 0){let n=cn(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
|
|
236
236
|
`),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
237
|
-
`),2):(await
|
|
237
|
+
`),2):(await mp(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
|
|
238
238
|
`:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
|
|
239
239
|
`:`Convention policy is off; only explicit --deny-tool flags apply.
|
|
240
|
-
`)),0)}async function
|
|
240
|
+
`)),0)}async function kk(e){let t=e[0];if(t===void 0){let n=Cr(),r=process.env.MAIND_GATEWAY_ATTEST!==void 0;return process.stdout.write(`maind: gateway attestation reports are ${n?"ON":"OFF"}${r?" (from MAIND_GATEWAY_ATTEST env)":""}.
|
|
241
241
|
`+(n?"":`maind: enable with 'gateway attest on' \u2014 reports observation windows (per-tool call/warn/deny COUNTERS, tool NAMES, convention citations, server label) to your maind account. Never tool arguments, results, paths, or prompts.
|
|
242
242
|
`)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
|
|
243
|
-
`),2):(await
|
|
243
|
+
`),2):(await hp(t==="on"),process.stdout.write(t==="on"?`maind: attestation reports ON. Each gateway now reports observation windows (tool-name counters + convention citations \u2014 never arguments) to your maind account, at gateway end and every 30 min.
|
|
244
244
|
`:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
|
|
245
|
-
`),0)}function
|
|
245
|
+
`),0)}function vk(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
|
|
246
246
|
`;let t="";for(let n of e){let r=n.servers===null?"*":n.servers.join(","),i=n.severity==="required"?"deny-capable":"warn-only";t+=` ${n.tool} [servers: ${r}] ${n.conventionId} v${n.conventionVersion} (${n.severity} \u2192 ${i})
|
|
247
|
-
`}return t}function
|
|
247
|
+
`}return t}function Sk(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 Ek(e){let t=e.includes("--refresh"),n=cn(),r=ln();if(t){let o=await Dr();o===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
248
248
|
`):(Nr(r,o),process.stdout.write(`maind: policy refreshed (${o.length} rule(s)).
|
|
249
249
|
`))}let i=Pr(r);return process.stdout.write(`maind: gateway mode '${n}'
|
|
250
250
|
`),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
|
|
251
|
-
`),0):(process.stdout.write(`maind: policy from cache (${
|
|
252
|
-
`),process.stdout.write(
|
|
253
|
-
`),0)}var Op=_(()=>{"use strict";Zo();ns();rs();s(
|
|
254
|
-
`,{mode:384})}catch{}}function
|
|
251
|
+
`),0):(process.stdout.write(`maind: policy from cache (${Sk(i)}, ${r.mcpUrl}):
|
|
252
|
+
`),process.stdout.write(vk(i.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
|
|
253
|
+
`),0)}var Op=_(()=>{"use strict";Zo();ns();rs();s(wk,"runGatewayMode");s(kk,"runGatewayAttest");s(vk,"renderRules");s(Sk,"cacheAge");s(Ek,"runGatewayPolicy")});var jp={};V(jp,{gatewayEventsFile:()=>Lp,parseGatewayArgs:()=>$p,runGateway:()=>Nk});import{spawn as xk}from"node:child_process";import{appendFile as Rk,mkdir as Tk}from"node:fs/promises";import{homedir as Mp}from"node:os";import{basename as Ak,join as Fp}from"node:path";import{createInterface as Ik}from"node:readline";function Lp(){return Fp(Mp(),".maind","gateway","events.jsonl")}async function Ck(e){try{let t=Lp();await Tk(Fp(Mp(),".maind","gateway"),{recursive:!0}),await Rk(t,JSON.stringify(e)+`
|
|
254
|
+
`,{mode:384})}catch{}}function $p(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 Nk(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:k,runGatewayUninstall:E}=await Promise.resolve().then(()=>(Pp(),Np));return e[0]==="install"?k(e.slice(1)):E(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:k,runGatewayMode:E,runGatewayPolicy:R}=await Promise.resolve().then(()=>(Op(),Dp));return e[0]==="mode"?E(e.slice(1)):e[0]==="attest"?k(e.slice(1)):R(e.slice(1))}let t=$p(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
|
|
255
255
|
maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
256
256
|
maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
257
257
|
maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
@@ -261,54 +261,54 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
|
|
|
261
261
|
NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
|
|
262
262
|
install/uninstall rewrite Claude Code MCP configs (consent per server).
|
|
263
263
|
mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
|
|
264
|
-
`),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r??
|
|
265
|
-
`),process.exitCode=1});let w=
|
|
266
|
-
`),h(Mr("deny",a,E.toolName,Date.now()));return}let R=
|
|
264
|
+
`),2;let{denyTools:n,label:r,command:i,args:o}=t,a=r??Ak(i),c=cn(),l=gp(),u=l==="off"?null:un(),d=c==="off"?[]:Pr(ln())?.rules??[];c!=="off"&&Dr().then(k=>{k!==null&&(d=k,Nr(ln(),k))}).catch(()=>{});let p=[],f=Cr()&&D()!==null&&c!=="off",m=null;try{m=O()}catch{m=null}let h=s(k=>{Ck(k),f&&p.push(k)},"record"),g=s(async()=>{if(!f)return;let k=lp(p.splice(0),c,a,m);k!==null&&(await Qo(k)||await dp(k))},"attestAndReset");f&&up().catch(()=>{});let y=setInterval(()=>{g()},30*6e4);y.unref();let b=xk(i,o,{stdio:["pipe","pipe","inherit"]});b.stdout.pipe(process.stdout),b.on("error",k=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(k)}
|
|
265
|
+
`),process.exitCode=1});let w=Ik({input:process.stdin,terminal:!1});w.on("line",k=>{let E=bs(k);if(E.kind==="request"&&E.method==="tools/call"&&E.toolName){if(n.has(E.toolName)&&E.id!==void 0){process.stdout.write(We(E.id,E.toolName)+`
|
|
266
|
+
`),h(Mr("deny",a,E.toolName,Date.now()));return}let R=_p(E.toolName,a,d,c);if(R.kind==="deny"&&E.id!==void 0){process.stdout.write(We(E.id,E.toolName,wp(E.toolName,R.rule))+`
|
|
267
267
|
`),h(Fr("policy_deny",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));return}(R.kind==="warn"||R.kind==="deny")&&h(Fr("policy_warn",a,E.toolName,Date.now(),R.rule.conventionId,R.rule.conventionVersion));let I=pn(k,u);if(I.length>0){let A=I.find(N=>N.verdict==="fabricated");if(A!==void 0&&l==="enforce"&&c==="enforce"&&E.id!==void 0&&A!==void 0&&E.id!==void 0){process.stdout.write(We(E.id,E.toolName,Ve(A,!0))+`
|
|
268
268
|
`),h(Lr("sha_deny",a,E.toolName,Date.now()));return}let j=A??I[0];process.stderr.write(`[maind gateway] ${Ve(j,!1)}
|
|
269
269
|
`),h(Lr("sha_warn",a,E.toolName,Date.now()))}h(Mr("tool_call",a,E.toolName,Date.now()))}b.stdin.write(k+`
|
|
270
|
-
`)}),w.on("close",()=>{b.stdin.end()});let v=await new Promise(k=>{b.on("exit",(E,R)=>{k(E??(R?1:0))})});return clearInterval(y),await g(),v}var
|
|
270
|
+
`)}),w.on("close",()=>{b.stdin.end()});let v=await new Promise(k=>{b.on("exit",(E,R)=>{k(E??(R?1:0))})});return clearInterval(y),await g(),v}var Hp=_(()=>{"use strict";$r();pp();Zo();es();jr();ns();rs();B();ge();s(Lp,"gatewayEventsFile");s(Ck,"logEvent");s($p,"parseGatewayArgs");s(Nk,"runGateway")});var ds={};V(ds,{MAX_ENTRIES:()=>is,TTL_MS:()=>as,crossSessionDir:()=>cs,decideCrossSession:()=>Kp,parseSessionDb:()=>Gp,pruneDb:()=>ls,runGuardCrossCheck:()=>Hk,runGuardCrossObserve:()=>jk,staleReason:()=>os});import{mkdir as Pk,readFile as Dk,readdir as Ok,stat as Up,unlink as Mk,writeFile as Fk}from"node:fs/promises";import{homedir as Lk}from"node:os";import{join as ss}from"node:path";function cs(){return ss(Lk(),".maind","cross-session")}function Gp(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[o,a]of Object.entries(n.files)){if(typeof a!="object"||a===null)continue;let c=a;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[o]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[o,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(i[o]=a);return{files:r,warned:i}}function ls(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=as);return n.length>is&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-is)),{files:Object.fromEntries(n),warned:e.warned}}function Kp(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function os(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 Bp(e){let t=cs();return await Pk(t,{recursive:!0}),ss(t,`${e}.json`)}async function Wp(e,t){try{let n=await Dk(await Bp(e),"utf8");return ls(Gp(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function Vp(e,t){try{await Fk(await Bp(e),JSON.stringify(t),{mode:384})}catch{}}async function $k(e){try{let t=cs();for(let n of await Ok(t)){if(!n.endsWith(".json"))continue;let r=ss(t,n),i=await Up(r).catch(()=>null);i&&e-i.mtimeMs>as&&await Mk(r).catch(()=>{})}}catch{}}async function qp(e){try{return(await Up(e)).mtimeMs}catch{return}}async function jk(e,t=Date.now()){try{if(Q().mode==="off")return 0;let r=e??await C(),i=typeof r.session_id=="string"?r.session_id:"",o=ie(r);if(!i||!o)return 0;let a=await qp(o);if(a===void 0)return 0;let c=await Wp(i,t);return c.files[o]={m:a,t},delete c.warned[o],await Vp(i,ls(c,t)),await $k(t),0}catch{return 0}}async function Hk(e,t=Date.now()){try{let n=Q();if(n.mode==="off")return 0;let r=e??await C(),i=typeof r.session_id=="string"?r.session_id:"",o=ie(r);if(!i||!o)return 0;let a=await Wp(i,t),c=Kp(a.files[o]?.m,await qp(o));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(_t(os(o,c))+`
|
|
271
271
|
`),await W({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o}),0):(a.warned[o]===c.current||(process.stdout.write(ve(os(o,c))+`
|
|
272
|
-
`),a.warned[o]=c.current,await
|
|
272
|
+
`),a.warned[o]=c.current,await Vp(i,a),await W({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:o})),0)}catch{return 0}}var as,is,us=_(()=>{"use strict";oe();wt();Ge();xt();as=48*3600*1e3,is=500;s(cs,"crossSessionDir");s(Gp,"parseSessionDb");s(ls,"pruneDb");s(Kp,"decideCrossSession");s(os,"staleReason");s(Bp,"dbPath");s(Wp,"loadDb");s(Vp,"saveDb");s($k,"sweepStaleSessionFiles");s(qp,"fileMtime");s(jk,"runGuardCrossObserve");s(Hk,"runGuardCrossCheck")});var fs={};V(fs,{INDEX_REFRESH_WORKER:()=>Yp,acquireLock:()=>Qp,releaseLock:()=>ps,runIndexRefreshWorker:()=>Jk,runOnIndexRefresh:()=>qk});import{spawn as Uk}from"node:child_process";import{existsSync as Gk,mkdirSync as Kk,rmdirSync as Jp,statSync as Bk}from"node:fs";import{join as zp}from"node:path";function Xp(e){return zp(e,".maind","index-refresh.lock")}function Vk(e){return zp(e,".maind","code-index.sqlite")}function Qp(e,t=Date.now()){let n=Xp(e);try{if(t-Bk(n).mtimeMs<Wk)return!1;Jp(n)}catch{}try{return Kk(n,{recursive:!1}),!0}catch{return!1}}function ps(e){try{Jp(Xp(e))}catch{}}async function qk(){try{let e=await C(),t=J(typeof e.cwd=="string"?e.cwd:process.cwd());if(!Gk(Vk(t))||!Qp(t))return 0;let n=process.argv[1];if(n===void 0)return ps(t),0;Uk(process.execPath,[n,Yp,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function Jk(){let e=process.argv[3]??J();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(mo(),bl)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{ps(e)}return 0}var Wk,Yp,ms=_(()=>{"use strict";oe();Yt();Wk=30*6e4,Yp="index-refresh-run";s(Xp,"lockPath");s(Vk,"indexDbPath");s(Qp,"acquireLock");s(ps,"releaseLock");s(qk,"runOnIndexRefresh");s(Jk,"runIndexRefreshWorker")});import{randomUUID as zk}from"node:crypto";import{createInterface as _f}from"node:readline";var Zp=[["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 ef(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of Zp)if(t.includes(n))return r;return null}s(ef,"mapClientInfoNameToFamily");function ys(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Or(t)||t.method!=="initialize")return null;let n=t.params;if(!Or(n))return null;let r=n.clientInfo;if(!Or(r))return null;let i=r.name,o=ef(typeof i=="string"?i:null);if(o===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:o,version:c}}s(ys,"tryExtractInitializeClient");function Or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Or,"isRecord");$r();jr();qe();var wf="https://mcp.maind.dev/mcp",Rt=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{s(this,"BridgeReauthNeeded")}},bn=class{static{s(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;presenceFrameId=0;sessionId=null;shaRepoRoot;initFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=fn(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=kf(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=vf(r),this.clientVersionLocked=this.clientVersion!==null;let i=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=i&&/^[a-f0-9]{64}$/.test(i)?i:null,this.localRouter=t.localRouter??null,this.presence=t.presence??null,this.shaRepoRoot=un(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??wf}async run(){let t=_f({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=ys(t);d!==null&&(this.clientFamily=d.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=d.version))}this.initFrame===null&&gn(t)&&(this.initFrame=t);let r=xf(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let d=pn(t,this.shaRepoRoot);if(d.length>0){let p=d.find(m=>m.verdict==="fabricated"),f=p??d[0];if(p!==void 0&&vs(p)&&r.id!==null){let m=Ve(p,!0);process.stderr.write(`[maind] ${m}
|
|
273
273
|
`);let h=r.params?.name;process.stdout.write(We(r.id,typeof h=="string"?h:"unknown",m)+`
|
|
274
274
|
`);return}i=Ve(f,!1),process.stderr.write(`[maind] ${i}
|
|
275
275
|
`)}}if(this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let d=await this.localRouter.handleToolCall(r?.id??null,r?.params);process.stdout.write(d+`
|
|
276
|
-
`);return}let o=this.localRouter!==null&&r?.method==="tools/list",a=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:a,body:t})}catch(d){let p=hn(t);if(this.serveInitializeFromCache(t,p))return;yn(p,-32603,`bridge network error: ${
|
|
276
|
+
`);return}let o=this.localRouter!==null&&r?.method==="tools/list",a=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:a,body:t})}catch(d){let p=hn(t);if(this.serveInitializeFromCache(t,p))return;yn(p,-32603,`bridge network error: ${Tf(d)}`);return}let l=c.headers.get("mcp-session-id");if(l&&l!==this.sessionId&&(this.sessionId=l),c.status===401){await this.handle401(c,t);return}if(c.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!gn(t)){let d=await c.text().catch(()=>"");if(Rf(d)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=hn(t);yn(p,-32603,`bridge upstream error (HTTP 404): ${d.slice(0,500)}`);return}if(!c.ok){let d=hn(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,d))return;yn(d,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let u=c.headers.get("content-type")??"";if(o&&this.localRouter){let d=u.startsWith("text/event-stream")?await Ur(c):await c.text(),p=this.localRouter.augmentToolsList(d);p.trim().length>0&&process.stdout.write(p+`
|
|
277
277
|
`);return}if(gn(t)){let d=u.startsWith("text/event-stream")?await Ur(c):await c.text();this.cacheInitializeResult(d),this.presence?.onSessionReady(),d.trim().length>0&&process.stdout.write(d+`
|
|
278
|
-
`);return}if(i!==null){let d=u.startsWith("text/event-stream")?await Ur(c):await c.text(),p=
|
|
279
|
-
`);return}if(u.startsWith("text/event-stream"))await
|
|
280
|
-
`)}}}async handle401(t,n){let r=await t.text().catch(()=>""),i=r.toLowerCase();if(i.includes("device_mismatch")||i.includes("device_revoked")||i.includes("device_required")||i.includes("invalid or revoked"))throw this.terminated=!0,new Rt(
|
|
281
|
-
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${mn(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function
|
|
278
|
+
`);return}if(i!==null){let d=u.startsWith("text/event-stream")?await Ur(c):await c.text(),p=Ef(d,i);p.trim().length>0&&process.stdout.write(p+`
|
|
279
|
+
`);return}if(u.startsWith("text/event-stream"))await Sf(c);else{if(c.status===202)return;{let d=await c.text();d.trim().length>0&&process.stdout.write(d+`
|
|
280
|
+
`)}}}async handle401(t,n){let r=await t.text().catch(()=>""),i=r.toLowerCase();if(i.includes("device_mismatch")||i.includes("device_revoked")||i.includes("device_required")||i.includes("invalid or revoked"))throw this.terminated=!0,new Rt(Af(i));let a=hn(n);yn(a,-32001,`bridge auth error: ${r.slice(0,200)}`)}async postPresenceToolCall(t,n){if(this.sessionId===null)throw new Error("presence: no MCP session established yet");this.presenceFrameId+=1;let r=JSON.stringify({jsonrpc:"2.0",id:`maind-presence-${this.presenceFrameId}`,method:"tools/call",params:{name:t,arguments:n}}),i=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),o=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return If(o)}buildHeaders(t){let n={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${this.apiKey}`,"x-maind-device-id":this.deviceId,"x-maind-bridge-version":this.bridgeVersion};return this.clientFamily!==null&&(n["x-maind-client-family"]=this.clientFamily),this.clientVersion!==null&&(n["x-maind-client-version"]=this.clientVersion),this.projectKey!==null&&(n["x-maind-project-key"]=this.projectKey),t&&this.sessionId!==null&&(n["mcp-session-id"]=this.sessionId),n}async recoverSession(){if(this.initFrame===null)return!1;this.sessionId=null;let t;try{t=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!1),body:this.initFrame})}catch{return!1}let n=t.headers.get("mcp-session-id");if(await t.text().catch(()=>""),!t.ok||!n)return!1;this.sessionId=n;try{await(await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})})).text().catch(()=>"")}catch{}return!0}getRepoRoot(){return this.repoRoot===null&&(this.repoRoot=ae()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&Rs(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!gn(t))return!1;let r=Ts(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(As(n,r)+`
|
|
281
|
+
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${mn(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function kf(e){if(e===null)return null;let t=e.trim().toLowerCase();return t.length===0?null:new Set(["claude-code","codex","copilot","cursor","windsurf","mcp-bridge","vscode-extension","claude-desktop","mcp-inspector"]).has(t)?t:null}s(kf,"normalizeClientFamily");function vf(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}s(vf,"normalizeClientVersion");async function Sf(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=s(()=>{if(i.length===0)return;let a=i.join(`
|
|
282
282
|
`).trim();i=[],a.length>0&&process.stdout.write(a+`
|
|
283
283
|
`)},"flushEvent");try{for(;;){let{value:a,done:c}=await t.read();if(c)break;r+=n.decode(a,{stream:!0});let l;for(;(l=r.indexOf(`
|
|
284
|
-
`))!==-1;){let u=r.slice(0,l);r=r.slice(l+1);let d=u.endsWith("\r")?u.slice(0,-1):u;if(d===""){o();continue}d.startsWith(":")||d.startsWith("data:")&&i.push(d.slice(5).replace(/^\s/,""))}}}finally{o()}}s(
|
|
284
|
+
`))!==-1;){let u=r.slice(0,l);r=r.slice(l+1);let d=u.endsWith("\r")?u.slice(0,-1):u;if(d===""){o();continue}d.startsWith(":")||d.startsWith("data:")&&i.push(d.slice(5).replace(/^\s/,""))}}}finally{o()}}s(Sf,"pipeSseToStdout");function Ef(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return e;let r=n.result;return typeof r!="object"||r===null||!Array.isArray(r.content)?e:(r.content.push({type:"text",text:`[maind] ${t}`}),JSON.stringify(n))}catch{return e}}s(Ef,"appendNoteToToolResult");function xf(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}s(xf,"parseRpc");async function Ur(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],o=[],a=s(()=>{if(o.length===0)return;let c=o.join(`
|
|
285
285
|
`).trim();o=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let u;for(;(u=r.indexOf(`
|
|
286
286
|
`))!==-1;){let d=r.slice(0,u);r=r.slice(u+1);let p=d.endsWith("\r")?d.slice(0,-1):d;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&o.push(p.slice(5).replace(/^\s/,""))}}}finally{a()}return i.join(`
|
|
287
|
-
`)}s(Ur,"collectSseText");function hn(e){try{return JSON.parse(e).id??null}catch{return null}}s(hn,"tryExtractId");function gn(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(gn,"isInitializeRequest");function
|
|
288
|
-
`)}s(yn,"emitJsonRpcError");function
|
|
289
|
-
`).map(a=>a.trim()).filter(a=>a.startsWith("data:"));if(o.length===0)return null;n=o[o.length-1].slice(5).trim()}let i=JSON.parse(n).result?.content?.[0]?.text;return typeof i!="string"?null:JSON.parse(i)}catch{return null}}s(
|
|
287
|
+
`)}s(Ur,"collectSseText");function hn(e){try{return JSON.parse(e).id??null}catch{return null}}s(hn,"tryExtractId");function gn(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}s(gn,"isInitializeRequest");function Rf(e){let t=e.toLowerCase();return t.includes("session not found")||t.includes("session expired")||t.includes("no valid session")||t.includes("reinitialize")||t.includes("session")&&t.includes("expired")}s(Rf,"isSessionLossBody");function Tf(e){return e instanceof Error?e.message:String(e)}s(Tf,"stringifyErr");function yn(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
288
|
+
`)}s(yn,"emitJsonRpcError");function Af(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}s(Af,"extractHint");function If(e){try{let t=e.trim();if(t.length===0)return null;let n=t;if(!t.startsWith("{")){let o=t.split(`
|
|
289
|
+
`).map(a=>a.trim()).filter(a=>a.startsWith("data:"));if(o.length===0)return null;n=o[o.length-1].slice(5).trim()}let i=JSON.parse(n).result?.content?.[0]?.text;return typeof i!="string"?null:JSON.parse(i)}catch{return null}}s(If,"parsePresenceToolResult");B();B();import{spawn as jf}from"node:child_process";import{platform as Hf}from"node:os";var Uf="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function Gf(){let e=process.env.MAIND_FUNCTIONS_ORIGIN;return e&&e.length>0?e.replace(/\/+$/,""):Uf}s(Gf,"functionsOrigin");async function Je(e,t=process.stderr){let n=Gf(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,o=wn(e),a=`mcp-bridge-${o.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:o})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await Vf(l.verification_uri_complete).catch(()=>{}),Wf(l,t);let u=Date.now()+l.expires_in*1e3,d=Math.max(l.interval,3)*1e3;for(;Date.now()<u;){await Bf(d);let p=await Kf(i,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
|
|
290
290
|
`),null));if(p){if(p.status==="approved")return Ee(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
|
|
291
291
|
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
|
|
292
292
|
`),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
|
|
293
293
|
`),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
|
|
294
|
-
`),null}s(Je,"runDeviceFlow");async function
|
|
294
|
+
`),null}s(Je,"runDeviceFlow");async function Kf(e,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:t})});if(!n.ok){let r=await n.text();throw new Error(`poll ${n.status}: ${r}`)}return await n.json()}s(Kf,"pollOnce");function Bf(e){return new Promise(t=>setTimeout(t,e))}s(Bf,"sleep");function Wf(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: ${Ds(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Ds(e.user_code,56)} \u2502`," \u2502 \u2502",` \u2502 (expires in ${Math.round(e.expires_in/60)} minutes)`.padEnd(67)+"\u2502"," \u2502 \u2502"," \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",""];t.write(n.join(`
|
|
295
295
|
`)+`
|
|
296
|
-
`)}s(
|
|
297
|
-
`))}s(
|
|
296
|
+
`)}s(Wf,"printAuthInstructions");function Ds(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}s(Ds,"pad");async function Vf(e){let t,n;switch(Hf()){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=jf(t,n,{stdio:"ignore",detached:!0});o.on("error",i),o.unref(),r()}catch(o){i(o)}})}s(Vf,"openExternalBrowser");xe();ge();xe();import*as Nl from"node:os";function Os(e){let t={projectRoot:null,full:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--no-preamble":t.noPreamble=!0;break;case"--no-hook":t.noHook=!0;break;case"--non-interactive":t.nonInteractive=!0;break;case"--telemetry":t.telemetry=!0;break;case"--skip-codex":t.skipCodex=!0;break;case"--dry-run":t.dryRun=!0;break;case"--auto-working-paths":t.autoWorkingPaths=!0;break;case"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--project-root requires a path argument");t.projectRoot=i,n++;break}case"--token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--token requires a token argument");t.token=i,n++;break}case"--one-click-token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--one-click-token requires a token argument");t.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=i,n++;break}case"--client":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Z("--client requires a family argument (e.g. claude-code, cursor, windsurf, copilot, codex, claude-desktop)");t.client=i,n++;break}default:throw new Z(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}s(Os,"parseInstallFlags");var Z=class extends Error{static{s(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function Ms(){let e=["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Detects your project root, pairs this device with MAIND, merges the","MCP-server entry into every supported AI-client config it finds, and","(optionally) writes the MAIND preamble block into CLAUDE.md / AGENTS.md /","Cursor / Windsurf / Copilot files. Idempotent \u2014 re-running is safe.","","Usage:"," npx -y @maind-dev/mcp-bridge install [flags]","","Common flags:"," --project-root <path> Override project-root detection (default: walk up from cwd)"," --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)"," --no-preamble Skip the 5 preamble files (MCP-config + pairing only)"," --no-hook Never write the Claude Code hooks (overrides --full for hooks)"," --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)"," --token <key> Use a pre-issued mnd_ api-key instead of browser pairing"," --one-click-token <jwt> Exchange the dashboard one-click token for a device-bound"," key \u2014 no browser (needs --one-click-exchange-url; ADR-267)"," --one-click-exchange-url <url> Exchange endpoint (set by the launcher scripts)"," --client <family> Install only for one client family (claude-code, cursor, ...)"," --skip-codex Skip the Codex ~/.codex/config.toml target",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --telemetry Opt-in: post anonymous install_completed event"," -h, --help Show this help text","","Examples:"," npx -y @maind-dev/mcp-bridge install # interactive default"," npx -y @maind-dev/mcp-bridge install --dry-run # preview without writing anything"," npx -y @maind-dev/mcp-bridge install --full --telemetry # full setup, opt-in telemetry"," npx -y @maind-dev/mcp-bridge install --client cursor # only Cursor target","","After it finishes, restart your MCP client so the new server entry takes effect.",""];process.stdout.write(e.join(`
|
|
297
|
+
`))}s(Ms,"printInstallHelp");var kn=class{static{s(this,"InstallReport")}results=[];add(t){this.results.push(t)}results_(){return this.results}summary(){let t=0,n=0,r=0;for(let i of this.results)i.status==="created"||i.status==="merged"||i.status==="skipped"||i.status==="would-create"||i.status==="would-merge"||i.status==="would-pair"?t++:i.status==="needs-user-decision"?n++:i.status==="failed"&&r++;return{total:this.results.length,ok:t,needsDecision:n,failed:r}}hasFailures(){return this.results.some(t=>t.status==="failed")}hasUserDecisionPending(){return this.results.some(t=>t.status==="needs-user-decision")}exitCode(){return this.hasFailures()||this.hasUserDecisionPending()?1:0}toMarkdownTable(){if(this.results.length===0)return`_no steps were attempted_
|
|
298
298
|
`;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(u=>u.target.length)),r=Math.max(t[1].length,...this.results.map(u=>u.action.length)),i=Math.max(t[2].length,...this.results.map(u=>u.status.length)),o=Math.max(t[3].length,...this.results.map(u=>(u.detail??"").length)),a=s((u,d)=>u+" ".repeat(Math.max(0,d-u.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(o)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],i)} | ${a(t[3],o)} |`),l.push(c);for(let u of this.results)l.push(`| ${a(u.target,n)} | ${a(u.action,r)} | ${a(u.status,i)} | ${a(u.detail??"",o)} |`);return l.join(`
|
|
299
299
|
`)+`
|
|
300
300
|
`}print(t){let n=this.summary();t.write(`
|
|
301
301
|
`),t.write(this.toMarkdownTable()),t.write(`
|
|
302
302
|
Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
|
|
303
|
-
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as
|
|
303
|
+
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as Fs from"node:fs/promises";import*as ye from"node:path";import*as Ls from"node:readline";var Zf=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function $s(e){let t=ye.resolve(e),n=t;for(;;){if(await Hs(n))return n;let r=ye.dirname(n);if(r===n)return t;n=r}}s($s,"detectProjectRoot");async function js(e){let n=ye.resolve(e),r=[];for(;;){await Hs(n)&&r.push(n);let i=ye.dirname(n);if(i===n)break;n=i}return r}s(js,"findAllProjectRoots");async function Hs(e){for(let t of Zf)try{return await Fs.access(ye.join(e,t)),!0}catch{}return!1}s(Hs,"hasAnyMarker");async function Us(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
|
|
304
304
|
Multiple project roots found between cwd and the filesystem root:
|
|
305
305
|
`),e.forEach((o,a)=>{process.stdout.write(` [${a+1}] ${o}
|
|
306
306
|
`)}),process.stdout.write(`
|
|
307
|
-
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=
|
|
308
|
-
`),null):e[i-1]}s(
|
|
309
|
-
`;if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await F(e.path,u)}catch(d){return Vr(e,"write",d)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(
|
|
307
|
+
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=Ls.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(o=>{n.question("",a=>o(a.trim()))});if(n.close(),r==="")return e[0];let i=Number.parseInt(r,10);return Number.isNaN(i)||i<1||i>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
|
|
308
|
+
`),null):e[i-1]}s(Us,"disambiguateProjectRoot");Ye();import*as Y from"node:path";function Ws(e){let t=e.launch??ee({entryPath:te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{command:t.command,args:t.args,env:{...t.env,MAIND_CLIENT_FAMILY:e.clientFamily,MAIND_MCP_URL:e.mcpUrl}}}s(Ws,"buildMaindServerEntry");function rm(e){switch(e.platform){case"darwin":return Y.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??Y.join(e.homeDir,"AppData","Roaming");return Y.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??Y.join(e.homeDir,".config");return Y.join(t,"Claude","claude_desktop_config.json")}}}s(rm,"claudeDesktopConfigPath");function Vs(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:Y.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:Y.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:rm(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:Y.join(e.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:Y.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:Y.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}s(Vs,"getClientTargets");function qs(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}s(qs,"filterTargetsByFamily");function Js(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Bs(e.env.XDG_CONFIG_HOME),appData:Bs(e.env.APPDATA)}}s(Js,"makeDefaultContext");function Bs(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}s(Bs,"nonEmpty");Ye();ce();var It="maind";async function Zs(e,t,n=!1){if(e.kind!=="json")return{target:e.key,action:"merge",status:"failed",detail:`expected json target, got ${e.kind}`};let r;try{r=await G(e.path)}catch(d){return Vr(e,"read",d)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{i=JSON.parse(r)}catch(d){return Vr(e,"parse",d)}}if(!be(i))return{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};let a=e.key==="claude-code-user"&&sm(i),c,l=!1;if(a){let d=i[It];be(d)&&Qs(d,t)&&(l=!0),c={...i,[It]:Xs(d,t)}}else{let d=be(i.mcpServers)?i.mcpServers:{},p=d[It];be(p)&&Qs(p,t)&&(l=!0),c={...i,mcpServers:{...d,[It]:Xs(p,t)}}}if(l&&r!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let u=JSON.stringify(c,null,2)+`
|
|
309
|
+
`;if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await F(e.path,u)}catch(d){return Vr(e,"write",d)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(Zs,"mergeJsonConfig");function Xs(e,t){let n=be(e)&&be(e.env)?e.env:{},r={...t.env};for(let[i,o]of Object.entries(n))!(i in r)&&typeof o=="string"&&(r[i]=o);return{command:t.command,args:[...t.args],env:r}}s(Xs,"mergeEntry");function sm(e){return!("mcpServers"in e||!(It in e))}s(sm,"hasRootShape");function Qs(e,t){if(!be(e)||e.command!==t.command||!am(e.args,t.args)||!be(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(Qs,"serverEntriesEqual");function am(e,t){if(!Array.isArray(e)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}s(am,"arrayEquals");function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(be,"isObject");function Vr(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(Vr,"failed");ce();import{parse as cm,stringify as lm}from"smol-toml";async function ea(e,t,n=!1){if(e.kind!=="toml")return{target:e.key,action:"merge",status:"failed",detail:`expected toml target, got ${e.kind}`};let r;try{r=await G(e.path)}catch(h){return xn(e,"read",h)}let i,o="create";if(r===null||r.trim().length===0)i={};else{o="merge";try{let h=cm(r);if(!Re(h))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=h}catch(h){return xn(e,"parse",h)}}let a=Re(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(Re(c)&&dm(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Re(c)&&Re(c.env)?c.env:{},u={...t.env};for(let[h,g]of Object.entries(l))!(h in u)&&typeof g=="string"&&(u[h]=g);let d={command:t.command,args:[...t.args],env:u},p={...i,mcp_servers:{...a,maind:d}},f;try{f=lm(p),f.endsWith(`
|
|
310
310
|
`)||(f+=`
|
|
311
|
-
`)}catch(h){return xn(e,"write",h)}let m=f.match(/^\[mcp_servers\.maind\]/gm)??[];if(m.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${m.length}`};if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await F(e.path,f)}catch(h){return xn(e,"write",h)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(
|
|
311
|
+
`)}catch(h){return xn(e,"write",h)}let m=f.match(/^\[mcp_servers\.maind\]/gm)??[];if(m.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${m.length}`};if(n)return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"would-create":"would-merge",detail:e.path};try{await F(e.path,f)}catch(h){return xn(e,"write",h)}return{target:e.key,action:o==="create"?"write":"merge",status:o==="create"?"created":"merged",detail:e.path}}s(ea,"mergeTomlConfig");function dm(e,t){if(!Re(e)||e.command!==t.command||!Array.isArray(e.args)||e.args.length!==t.args.length)return!1;for(let n=0;n<e.args.length;n++)if(e.args[n]!==t.args[n])return!1;if(!Re(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}s(dm,"tomlServerEntryEqual");function Re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Re,"isObject");function xn(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}s(xn,"failed");import*as le from"node:path";var um="__STACK__";var pm="__INTENT__";var qr="https://mcp.maind.dev/mcp",fm=`?stack=${um}&intent=${pm}`;function mm(e,t){let n=new URLSearchParams;t.stack&&t.stack.length>0&&n.set("stack",t.stack.join(",")),t.intent&&n.set("intent",t.intent),t.project&&n.set("project",t.project),t.verbosity&&n.set("verbosity",t.verbosity);let r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e}s(mm,"buildStackAwareEndpoint");var lS=mm(qr,{stack:["nextjs","supabase"],intent:"mixed"}),Nt=`## maind MCP integration \u2014 Mandatory consultation
|
|
312
312
|
|
|
313
313
|
This project uses the maind MCP server (mcp.maind.dev/mcp) as
|
|
314
314
|
authoritative source for vetted coding conventions and lessons. The
|
|
@@ -377,7 +377,7 @@ For non-trivial changes, resolve documentation path in this order:
|
|
|
377
377
|
If no path is discoverable, provide a guided fallback:
|
|
378
378
|
\`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
|
|
379
379
|
|
|
380
|
-
Full tool set + provenance via \`get_conventions\`.`;function
|
|
380
|
+
Full tool set + provenance via \`get_conventions\`.`;function hm(e){return`I want to add the **maind MCP server** to my AI coding agent.
|
|
381
381
|
|
|
382
382
|
- My stack: \`__STACK__\`
|
|
383
383
|
- MCP endpoint: \`${e}\`
|
|
@@ -573,7 +573,7 @@ written config.
|
|
|
573
573
|
|
|
574
574
|
--- Preamble block ---
|
|
575
575
|
|
|
576
|
-
${Nt}`}s(
|
|
576
|
+
${Nt}`}s(hm,"buildAiPromptBody");function Ct(e,t,n){let r=n?`
|
|
577
577
|
MAIND_CLIENT_FAMILY="${n}"`:"";return`#!/usr/bin/env bash
|
|
578
578
|
set -euo pipefail
|
|
579
579
|
|
|
@@ -608,7 +608,7 @@ ${n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":""}
|
|
|
608
608
|
config.mcpServers.maind = server;
|
|
609
609
|
fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
|
|
610
610
|
console.log("WROTE " + file);
|
|
611
|
-
NODE`}s(Ct,"buildJsonConfigInstaller");function
|
|
611
|
+
NODE`}s(Ct,"buildJsonConfigInstaller");function gm(e){return`#!/usr/bin/env bash
|
|
612
612
|
set -euo pipefail
|
|
613
613
|
|
|
614
614
|
CONFIG_FILE="$HOME/.codex/config.toml"
|
|
@@ -661,7 +661,7 @@ if (serverCount !== 1 || envCount !== 1) {
|
|
|
661
661
|
|
|
662
662
|
fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
|
|
663
663
|
console.log("WROTE " + file);
|
|
664
|
-
NODE`}s(
|
|
664
|
+
NODE`}s(gm,"buildCodexTomlInstaller");function ym(e=qr){let t=`${e}${fm}`;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:hm(t)},{id:"claude-code-cli",label:"Claude Code",description:"Browser-pairing project config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:".mcp.json",lang:"json",template:`{
|
|
665
665
|
"mcpServers": {
|
|
666
666
|
"maind": {
|
|
667
667
|
"command": "npx",
|
|
@@ -689,7 +689,7 @@ args = ["-y", "@maind-dev/mcp-bridge"]
|
|
|
689
689
|
|
|
690
690
|
[mcp_servers.maind.env]
|
|
691
691
|
MAIND_CLIENT_FAMILY = "codex"
|
|
692
|
-
MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codex/config.toml. It replaces only the maind MCP sections and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-codex.sh",lang:"bash",template:
|
|
692
|
+
MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codex/config.toml. It replaces only the maind MCP sections and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-codex.sh",lang:"bash",template:gm(t)}]},{id:"copilot",label:"GitHub Copilot",description:"Browser-pairing VS Code workspace config for Copilot agent mode. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as GitHub Copilot. Replace `__STACK__` with your stack slugs.",filename:".mcp.json",lang:"json",template:`{
|
|
693
693
|
"mcpServers": {
|
|
694
694
|
"maind": {
|
|
695
695
|
"command": "npx",
|
|
@@ -798,15 +798,15 @@ const tools = await mcp.getTools();
|
|
|
798
798
|
"env": {
|
|
799
799
|
"MAIND_MCP_URL": "${t}"
|
|
800
800
|
}
|
|
801
|
-
}`}]}s(
|
|
802
|
-
`:
|
|
803
|
-
`;return await F(e.path,i),{target:e.key,action:r===null?"write":"append",status:r===null?"created":"merged",detail:e.path}}catch(n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"append",status:"failed",detail:r}}}s(
|
|
801
|
+
}`}]}s(ym,"buildSnippetTemplates");var dS=ym(qr);ce();var bm="## maind MCP integration";function _m(e){return[{key:"preamble:CLAUDE.md",path:le.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:le.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:le.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:le.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:le.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:le.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}s(_m,"buildPreambleTargets");async function ta(e,t=!1){let n=_m(e),r=[];for(let i of n)r.push(await wm(i,t));return r}s(ta,"writePreambleFiles");async function wm(e,t){try{if(e.mayNeedParentDir&&!t&&await Wr(le.dirname(e.path)),await zs(e.path,bm))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await G(e.path);if(t)return{target:e.key,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:e.path};let i=r===null||r.length===0?`${Nt}
|
|
802
|
+
`:km(r)+`${Nt}
|
|
803
|
+
`;return await F(e.path,i),{target:e.key,action:r===null?"write":"append",status:r===null?"created":"merged",detail:e.path}}catch(n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"append",status:"failed",detail:r}}}s(wm,"writeOnePreambleFile");function km(e){return e.endsWith(`
|
|
804
804
|
|
|
805
805
|
`)?e:e.endsWith(`
|
|
806
806
|
`)?e+`
|
|
807
807
|
`:e+`
|
|
808
808
|
|
|
809
|
-
`}s(
|
|
809
|
+
`}s(km,"ensureTrailingBlankLine");ti();Xe();ce();import*as ca from"node:readline";var Te="config:auto_working_paths",Dm=`
|
|
810
810
|
Enable presence enrichment (auto working_paths)?
|
|
811
811
|
With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
|
|
812
812
|
locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
|
|
@@ -815,34 +815,34 @@ before editing the same area. Directory names only: never file contents, never
|
|
|
815
815
|
absolute paths. Server-side these paths are account-private (org members never
|
|
816
816
|
see them) and revocable any time on the dashboard consent page or via
|
|
817
817
|
{"auto_working_paths": false} in the bridge config.
|
|
818
|
-
[y/N]: `;async function
|
|
819
|
-
`;if(e.dryRun)return{target:Te,action:"merge",status:"would-merge",detail:t};try{await F(t,o,384)}catch(a){return{target:Te,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:Te,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}s(
|
|
820
|
-
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=
|
|
821
|
-
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw w}if(n.help)return
|
|
822
|
-
`),2;let a;if(n.projectRoot!==null)a=n.projectRoot;else{let w=await
|
|
818
|
+
[y/N]: `;async function la(e){let t=e.configPath??de(),n={};try{let a=await G(t);if(a!==null&&a.trim().length>0){let c=JSON.parse(a);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(n=c)}}catch{}if(typeof n.auto_working_paths=="boolean")return{target:Te,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:Te,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??Om)(e.out,Dm)}else return{target:Te,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:Te,action:"skip",status:"skipped",detail:"user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"};let i={...n,auto_working_paths:!0},o=JSON.stringify(i,null,2)+`
|
|
819
|
+
`;if(e.dryRun)return{target:Te,action:"merge",status:"would-merge",detail:t};try{await F(t,o,384)}catch(a){return{target:Te,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:Te,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}s(la,"applyWorkingPathsConsent");async function Om(e,t){e.write(t);let n=ca.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",o=>i(o.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}s(Om,"promptYesNoDefaultNo");B();async function da(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let i=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),o={};try{o=await i.json()}catch{}return i.ok?o.status!=="exchanged"||typeof o.api_key!="string"||!o.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:o.api_key,plan:o.plan??"unknown"}:{ok:!1,reason:o.error??`http_${i.status}`}}catch(i){return i instanceof Error&&i.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:i instanceof Error?i.message:String(i)}}finally{clearTimeout(r)}}s(da,"exchangeOneClickToken");async function fa(e){let t="browser-pair";if(e.token!==null)try{let o=Mm(e.token);return e.dryRun?{apiKey:o,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(At(),Ee(o),{apiKey:o,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(o){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:ua(o)}}}let n=null;if(e.oneClickToken!==null&&e.oneClickExchangeUrl!==null){if(e.dryRun)return{apiKey:null,result:{target:t,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let o=wn(e.bridgeVersion),a=await da({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:o.device_id,label:Ps(),clientMeta:{...o}});if(a.ok)return At(),Ee(a.apiKey),{apiKey:a.apiKey,result:{target:t,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${a.plan})`}};n=a.reason,pa(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
|
|
820
|
+
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=D();if(i!==null)return{apiKey:i,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let o=await Je(e.bridgeVersion,pa(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:ua(o)}}}}s(fa,"pairOrUseToken");function Mm(e){let t=e.trim();if(t.length===0)throw new Error("--token is empty");if(!/^mnd_[A-Za-z0-9_]+$/.test(t))throw new Error("--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?");return t}s(Mm,"validateTokenShape");function ua(e){return e instanceof Error?e.message:String(e)}s(ua,"errMessage");function pa(e){return e.out??process.stdout}s(pa,"out");var Fm="https://vsddmiosisvfrairepxv.supabase.co/functions/v1",Lm="/install-completed";async function ma(e){if(!e.enabled||e.apiKey===null)return;let n=`${(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"")||Fm}${Lm}`,r={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:jm(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:$m(e.steps),client_family_filter:e.clientFamilyFilter??null},i=new AbortController,o=setTimeout(()=>i.abort(),3e3);try{await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${e.installerVersion}`},body:JSON.stringify(r),signal:i.signal})}catch{}finally{clearTimeout(o)}}s(ma,"postInstallTelemetry");function $m(e){let t={created:0,merged:0,skipped:0,"needs-user-decision":0,failed:0};for(let n of e)t[n.status]=(t[n.status]??0)+1;return t}s($m,"countStatuses");function jm(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}s(jm,"parseNodeMajor");Yt();var Zg="https://mcp.maind.dev/mcp";async function Pl(e){let t=Date.now(),n;try{n=Os(e)}catch(w){if(w instanceof Z)return process.stderr.write(`error: ${w.message}
|
|
821
|
+
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw w}if(n.help)return Ms(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,o=Nl.homedir();if(o.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
|
|
822
|
+
`),2;let a;if(n.projectRoot!==null)a=n.projectRoot;else{let w=await js(process.cwd());if(w.length===0)a=await $s(process.cwd());else if(w.length===1)a=w[0];else{let v=await Us(w,i);if(v===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
|
|
823
823
|
`);for(let k of w)process.stderr.write(` candidate: ${k}
|
|
824
|
-
`);return 2}a=v}}let c=new kn,l=(process.env.MAIND_MCP_URL??"").trim()||
|
|
824
|
+
`);return 2}a=v}}let c=new kn,l=(process.env.MAIND_MCP_URL??"").trim()||Zg;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
|
|
825
825
|
`),process.stdout.write(`maind install \u2014 project root: ${a}
|
|
826
826
|
`),process.stdout.write(` \u2014 mcp endpoint: ${l}
|
|
827
827
|
|
|
828
|
-
`);let u=await
|
|
828
|
+
`);let u=await fa({bridgeVersion:P,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(c.add(u.result),u.result.status==="failed")return process.stderr.write(`
|
|
829
829
|
pairing failed: ${u.result.detail??"unknown"}
|
|
830
830
|
Skipping remaining steps.
|
|
831
|
-
`),c.print(process.stdout),2;let d=
|
|
831
|
+
`),c.print(process.stdout),2;let d=Js({projectRoot:a,homeDir:o,platform:process.platform,env:process.env}),p=Vs(d);if(p=qs(p,n.client),n.skipCodex&&(p=p.filter(w=>w.key!=="codex-cli")),p.length===0)return process.stderr.write(n.client!==null?`error: --client "${n.client}" matched no known target. Run --help for the list.
|
|
832
832
|
`:`error: no client targets selected (did you skip all of them?)
|
|
833
|
-
`),c.print(process.stdout),2;for(let w of p){let v=
|
|
833
|
+
`),c.print(process.stdout),2;for(let w of p){let v=Ws({mcpUrl:l,clientFamily:w.clientFamilyEnv}),k;w.kind==="json"?k=await Zs(w,v,n.dryRun):k=await ea(w,v,n.dryRun),c.add(k)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let w=await ta({projectRoot:a,homeDir:o},n.dryRun);for(let v of w)c.add(v)}let f={homeDir:o,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await sa(f));for(let w of await aa(f))c.add(w);c.add(await la({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let m=xl();m.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${m.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await ma({enabled:n.telemetry||n.full,installerVersion:P,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:u.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let h=c.exitCode(),g=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
|
|
834
834
|
DRY RUN finished in ${g}s. No files were modified. Re-run without --dry-run to apply.
|
|
835
835
|
`):process.stdout.write(`
|
|
836
836
|
Finished in ${g}s. Restart your MCP client so it picks up the new server entry.
|
|
837
837
|
`);let y=ee({entryPath:te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),b=y.fallbackReason===null?`${ze(y)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${b}
|
|
838
838
|
`),h===1&&process.stdout.write(`Note: some steps were skipped or failed \u2014 review the table above. The MCP setup is usable as long as 'browser-pair' and at least one JSON/TOML target succeeded.
|
|
839
|
-
`),h}s(Nl,"runInstall");Yt();import{readFileSync as Zg}from"node:fs";import{join as Pl}from"node:path";function dr(e){return e?Math.ceil(e.length/4):0}s(dr,"estimateTokens");var Ol=1e6,ur=class{static{s(this,"SavingsAggregator")}pendingTokens=0;pendingCalls=0;add(t){!Number.isFinite(t)||t<=0||(this.pendingTokens+=Math.floor(t),this.pendingCalls+=1)}hasPending(){return this.pendingTokens>0}takePending(){let t={tokens:this.pendingTokens,calls:this.pendingCalls};return this.pendingTokens=0,this.pendingCalls=0,t}};function Dl(e){try{let t=Zg(e,"utf8");return t.length>Ol?t.slice(0,Ol):t}catch{return""}}s(Dl,"readFileCapped");function ey(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=n?.filePath;typeof r=="string"&&r.length>0&&t.add(r)}return[...t]}s(ey,"distinctFilePaths");function Ml(e,t,n,r){try{let i=dr(n);if(e==="codebase_search"){let o=ey(t);if(o.length===0)return 0;let a=0;for(let c of o)a+=dr(Dl(Pl(r,c)));return Math.max(0,a-i)}if(e==="codebase_snippet"){let o=t?.filePath;if(typeof o!="string"||o.length===0)return 0;let a=dr(Dl(Pl(r,o)));return Math.max(0,a-i)}return 0}catch{return 0}}s(Ml,"measureLocalToolSaved");Xt();Yt();import{createHash as dy}from"node:crypto";function pr(e){return dy("sha256").update(e,"utf8").digest("hex")}s(pr,"nodeKeyHash");var uy=["module","class","interface","function","method","type_alias","enum","variable"],_o=[{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:uy,description:"Restrict to a symbol kind."},limit:{type:"number",description:"Max results (default 20)."}},required:["query"]}},{name:"codebase_trace",description:"Traverse the call/dependency graph from a symbol. direction 'out' = what this symbol calls/contains/imports; 'in' = what calls/depends on it. Returns edges as node_key \u2192 node_key with the edge kind. CALLS/EXTENDS are best-effort name heuristics.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"Start symbol's node_key (from codebase_search)."},direction:{type:"string",enum:["out","in"],description:"Traversal direction (default out)."},max_depth:{type:"number",description:"BFS depth 1\u20135 (default 3)."},limit:{type:"number",description:"Max edges returned (default 100)."}},required:["node_key"]}},{name:"codebase_snippet",description:"Return the exact source text of a symbol by node_key (read locally from disk \u2014 never uploaded). Use after codebase_search/trace to read a function/class without opening the file.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"The symbol's node_key."}},required:["node_key"]}},{name:"codebase_map",description:"Architecture overview of the indexed repo: symbol-kind distribution, languages, and the most-imported (highest fan-in) modules \u2014 a cheap way to orient in an unfamiliar codebase.",inputSchema:{type:"object",properties:{top_n:{type:"number",description:"How many top modules to list (default 10)."}}}},{name:"codebase_changes",description:"Enumerate the symbols in files you changed (git diff/status against the LOCAL index \u2014 runs on this machine, nothing is uploaded). Call after finishing an edit batch, before committing. The output includes a ready-to-paste `briefing_args` block with paths deliberately stripped \u2014 feed it to the cloud tool codebase_change_briefing to get the maind conventions and lessons that apply to exactly these symbols. Requires a built index (codebase_index) for symbol enumeration; files without index rows are counted but contribute no symbols.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."}}}},{name:"codebase_review_changes",description:"Review-grade change enumeration (ADR-228): like codebase_changes, but hunk-aware \u2014 each symbol is graded added|modified|co_located by intersecting git diff hunks with symbol spans (runs on this machine, nothing is uploaded), plus closed-enum risk_flags from the raw path list (SQL migrations, RLS/SECURITY DEFINER, CI workflows, env files \u2014 files the index itself cannot see). The output's `review_args` block is path-free by construction \u2014 feed it to the cloud tool review_changes for provenance-backed convention findings. It ALSO runs the four repo-health detectors (number collisions, spec drift, dead theme classes, table ACL \u2014 ADR-324) and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full keeps a run attestation-grade. diff_stats carries the attest anchors (head_sha, dirty, resolved base_sha \u2014 commit object hashes, no source): pass them through to review_verdict to persist a replayable review_runs record (ADR-230). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],ql=new Set(_o.map(e=>e.name));function L(e){return typeof e=="string"&&e.length>0?e:void 0}s(L,"str");var py=10;function fy(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,o=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=py&&r++,c>i&&(i=c);for(let u of a.ownership?.topAuthors??[])n.add(u.email.toLowerCase()||u.name);let l=a.lastCommits[0]?.dateIso;if(l){let u=Date.parse(l);Number.isFinite(u)&&u>o&&(o=u)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:o>0?Math.max(0,Math.floor((t-o)/864e5)):0}}s(fy,"aggregateHistoryContext");function Me(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Me,"num");function Wl(e){if(e===void 0)return{repoRoot:J(),scanDirs:void 0};let t=lr(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(Wl,"anchorRepo");function Vl(e,t){return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,projects:[],findings:[],hint:`No opinion \u2014 this directory could not be located, so no repository was scanned. ${t} Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. \`Asgard/Maind\`) or an absolute path. Nothing was verified as ${e}.`}}s(Vl,"dirNotFound");async function Jl(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(a=>a.status==="open").length,o=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:o,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${o} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=L(n.for_path);if(i!==void 0){let d=Tl(i);if(d===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await Ce(d.repoRoot,d.repoRelPath,{minFiles:r}),f=p.namespace,m=s(g=>g===null?null:`${f?.prefix??""}${g}`,"full"),h=f===null?"no_opinion":p.taken?"taken":"free";return{ok:h==="free",mode:"proposed_path",verdict:h,reason:h==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:d.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:m(p.number),taken:h==="no_opinion"?null:p.taken,suggestion:m(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?`${m(p.number)} is already held (see held_by). Create the file as ${m(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.`:`${m(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let o=Array.isArray(n.dirs)?n.dirs.filter(d=>typeof d=="string"):void 0;if(o!==void 0&&o.length>0){let d=new Map,p=[];for(let v of o){let k=lr(v);if(k===null){p.push(v);continue}let E=d.get(k.repoRoot)??new Set;E.add(k.repoRelDir),d.set(k.repoRoot,E)}if(d.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],m=[],h=[],g=[];for(let[v,k]of d){let E=[...k],R=E.includes(""),I=await Ie(v,{dirs:R?void 0:E,minFiles:r});f.push({repo_root:v,dirs:R?null:E}),m.push(...I.findings),h.push(...I.facts.namespaces.map(A=>({repo_root:v,dir:A.dir,prefix:A.prefix,file_count:A.fileCount}))),g.push(...I.facts.skipped)}let y=m.filter(v=>v.status==="open"),b=m.filter(v=>v.status==="info"),w=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:y.length===0,open_count:y.length,preexisting_count:b.length,findings:y,preexisting:b.map(v=>`${v.namespace.prefix}${v.number}`),namespaces:h,skipped:g,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(y.length===0?h.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${y.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+w}}let a=J(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(d=>d.status==="open"),u=c.findings.filter(d=>d.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:u.length,findings:l,preexisting:u.map(d=>`${d.namespace.prefix}${d.number}`),namespaces:c.facts.namespaces.map(d=>({dir:d.dir,prefix:d.prefix,file_count:d.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:L(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=s(p=>r.findings.filter(f=>f.status===p),"of"),o=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let u="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",d=o.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:a.length,preexisting_count:c.length,findings:[...o,...a],preexisting:c.map(p=>p.id),coverage_note:u,hint:(r.ok?"The declared entries agree.":d.length>0?`${d.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${o.length-d.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${o.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+u}}case"check_theme_class_drift":{let r=L(n.dir),i,o;if(r!==void 0){let d=lr(r);if(d===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};i=d.repoRoot,o=d.repoRelDir===""?void 0:[d.repoRelDir]}else i=J(),o=void 0;let a=Oe(i,{dirs:o,baseRef:L(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(d=>d.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(d=>({file:d.file,class:d.klass,status:d.status,missing_token:d.token,namespace:d.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=Wl(L(n.dir));if(r===null)return Vl("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Pe(r.repoRoot,{dirs:r.scanDirs,baseRef:L(n.base_ref),includeBaseline:n.include_baseline!==!1}),o="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+o}}case"check_migration_ledger_drift":{let r=Wl(L(n.dir));if(r===null)return Vl("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=bo(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:L(n.remote_db_url)}),o=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=s(p=>i.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),u=a("info"),d=o.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:o,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:u.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:d,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${d}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${d}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${d}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=L(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:L(n.kind),limit:Me(n.limit)})).map(o=>({...o,nodeKeyHash:pr(o.nodeKey)}))}case"codebase_trace":{let r=L(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:i,maxDepth:Me(n.max_depth),limit:Me(n.limit)})}case"codebase_snippet":{let r=L(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await e.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:pr(r)}}case"codebase_map":return e.getArchitecture({topN:Me(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:L(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Me(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language,file:i.filePath,start_line:i.startLine,node_key:i.nodeKey,node_key_hash:pr(i.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:L(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Me(n.limit)}),i;if(n.include_history!==!1)try{i=fy(await e.fileHistory({since:L(n.since),limit:1}))}catch{i=void 0}let o;try{o=await e.reviewDetectors({baseRef:L(n.since)})}catch(l){o=ot(Bt(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,...r.headSha?{head_sha:r.headSha}:{},dirty:r.dirty,...r.baseSha?{base_sha:r.baseSha}:{},code_index_version:Bl,detector_coverage:o.coverage},c=o.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,u)=>l+u.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:pr(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...i?{history:i}:{}},verdict_args:{detector_findings:o.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:o.coverage,truncated:o.truncated,block_eligible:c,engines:o.engines,findings:o.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${o.findings.length} detector row(s) (${c} block-eligible, coverage ${o.coverage}) are hashes only; keep detector_findings even when it is []. Persisting a replayable record additionally needs commit_sha / diff_stats.head_sha.`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(o=>typeof o=="string"):void 0,i=await e.fileHistory({paths:r,since:L(n.since),limit:Me(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(o=>({path:o.path,last_commits:o.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:o.ownership?{top_authors:o.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:o.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(o=>({sha:o.sha,date_iso:o.dateIso,author_name:o.authorName,subject:o.subject,files_touched:o.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}s(Jl,"dispatchLocalTool");var fr=class{constructor(t=Il,n=null,r=J){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return _o}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&ql.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",o=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=await Jl(this.getEngine(),i,o),c=JSON.stringify(a,null,2);return this.recordSavings(i,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=xl(a)?`${Rl} (${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=Ml(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};var my="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function zl(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:my}s(zl,"functionsOrigin");var hy="/mcp-client-metrics-ingest",gy=4e3,yy="codebase_search_tokens_saved";async function Yl(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${zl()}${hy}`,n=new AbortController,r=setTimeout(()=>n.abort(),gy);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:yy,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await i.text().catch(()=>""),i.ok}catch(i){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${i instanceof Error?i.message:String(i)}
|
|
840
|
-
`),!1}finally{clearTimeout(r)}}s(
|
|
841
|
-
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,
|
|
842
|
-
`),process.exit(1)),n.apiKey}s(
|
|
843
|
-
`),process.exit(1)),e.apiKey}s(
|
|
844
|
-
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(
|
|
845
|
-
`),process.exit(0));let t=U(),n=await
|
|
846
|
-
`),n=await
|
|
847
|
-
`))}s(
|
|
839
|
+
`),h}s(Pl,"runInstall");Yt();import{readFileSync as ey}from"node:fs";import{join as Dl}from"node:path";function dr(e){return e?Math.ceil(e.length/4):0}s(dr,"estimateTokens");var Ol=1e6,ur=class{static{s(this,"SavingsAggregator")}pendingTokens=0;pendingCalls=0;add(t){!Number.isFinite(t)||t<=0||(this.pendingTokens+=Math.floor(t),this.pendingCalls+=1)}hasPending(){return this.pendingTokens>0}takePending(){let t={tokens:this.pendingTokens,calls:this.pendingCalls};return this.pendingTokens=0,this.pendingCalls=0,t}};function Ml(e){try{let t=ey(e,"utf8");return t.length>Ol?t.slice(0,Ol):t}catch{return""}}s(Ml,"readFileCapped");function ty(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=n?.filePath;typeof r=="string"&&r.length>0&&t.add(r)}return[...t]}s(ty,"distinctFilePaths");function Fl(e,t,n,r){try{let i=dr(n);if(e==="codebase_search"){let o=ty(t);if(o.length===0)return 0;let a=0;for(let c of o)a+=dr(Ml(Dl(r,c)));return Math.max(0,a-i)}if(e==="codebase_snippet"){let o=t?.filePath;if(typeof o!="string"||o.length===0)return 0;let a=dr(Ml(Dl(r,o)));return Math.max(0,a-i)}return 0}catch{return 0}}s(Fl,"measureLocalToolSaved");Xt();Yt();import{createHash as uy}from"node:crypto";function pr(e){return uy("sha256").update(e,"utf8").digest("hex")}s(pr,"nodeKeyHash");var py=["module","class","interface","function","method","type_alias","enum","variable"],_o=[{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:py,description:"Restrict to a symbol kind."},limit:{type:"number",description:"Max results (default 20)."}},required:["query"]}},{name:"codebase_trace",description:"Traverse the call/dependency graph from a symbol. direction 'out' = what this symbol calls/contains/imports; 'in' = what calls/depends on it. Returns edges as node_key \u2192 node_key with the edge kind. CALLS/EXTENDS are best-effort name heuristics.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"Start symbol's node_key (from codebase_search)."},direction:{type:"string",enum:["out","in"],description:"Traversal direction (default out)."},max_depth:{type:"number",description:"BFS depth 1\u20135 (default 3)."},limit:{type:"number",description:"Max edges returned (default 100)."}},required:["node_key"]}},{name:"codebase_snippet",description:"Return the exact source text of a symbol by node_key (read locally from disk \u2014 never uploaded). Use after codebase_search/trace to read a function/class without opening the file.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"The symbol's node_key."}},required:["node_key"]}},{name:"codebase_map",description:"Architecture overview of the indexed repo: symbol-kind distribution, languages, and the most-imported (highest fan-in) modules \u2014 a cheap way to orient in an unfamiliar codebase.",inputSchema:{type:"object",properties:{top_n:{type:"number",description:"How many top modules to list (default 10)."}}}},{name:"codebase_changes",description:"Enumerate the symbols in files you changed (git diff/status against the LOCAL index \u2014 runs on this machine, nothing is uploaded). Call after finishing an edit batch, before committing. The output includes a ready-to-paste `briefing_args` block with paths deliberately stripped \u2014 feed it to the cloud tool codebase_change_briefing to get the maind conventions and lessons that apply to exactly these symbols. Requires a built index (codebase_index) for symbol enumeration; files without index rows are counted but contribute no symbols.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."}}}},{name:"codebase_review_changes",description:"Review-grade change enumeration (ADR-228): like codebase_changes, but hunk-aware \u2014 each symbol is graded added|modified|co_located by intersecting git diff hunks with symbol spans (runs on this machine, nothing is uploaded), plus closed-enum risk_flags from the raw path list (SQL migrations, RLS/SECURITY DEFINER, CI workflows, env files \u2014 files the index itself cannot see). The output's `review_args` block is path-free by construction \u2014 feed it to the cloud tool review_changes for provenance-backed convention findings. It ALSO runs the four repo-health detectors (number collisions, spec drift, dead theme classes, table ACL \u2014 ADR-324) and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full keeps a run attestation-grade. diff_stats carries the attest anchors (head_sha, dirty, resolved base_sha \u2014 commit object hashes, no source): pass them through to review_verdict to persist a replayable review_runs record (ADR-230). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],Jl=new Set(_o.map(e=>e.name));function L(e){return typeof e=="string"&&e.length>0?e:void 0}s(L,"str");var fy=10;function my(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,o=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=fy&&r++,c>i&&(i=c);for(let u of a.ownership?.topAuthors??[])n.add(u.email.toLowerCase()||u.name);let l=a.lastCommits[0]?.dateIso;if(l){let u=Date.parse(l);Number.isFinite(u)&&u>o&&(o=u)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:o>0?Math.max(0,Math.floor((t-o)/864e5)):0}}s(my,"aggregateHistoryContext");function Me(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}s(Me,"num");function Vl(e){if(e===void 0)return{repoRoot:J(),scanDirs:void 0};let t=lr(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}s(Vl,"anchorRepo");function ql(e,t){return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,projects:[],findings:[],hint:`No opinion \u2014 this directory could not be located, so no repository was scanned. ${t} Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. \`Asgard/Maind\`) or an absolute path. Nothing was verified as ${e}.`}}s(ql,"dirNotFound");async function zl(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(a=>a.status==="open").length,o=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:o,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${o} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=L(n.for_path);if(i!==void 0){let d=Al(i);if(d===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await Ce(d.repoRoot,d.repoRelPath,{minFiles:r}),f=p.namespace,m=s(g=>g===null?null:`${f?.prefix??""}${g}`,"full"),h=f===null?"no_opinion":p.taken?"taken":"free";return{ok:h==="free",mode:"proposed_path",verdict:h,reason:h==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:d.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:m(p.number),taken:h==="no_opinion"?null:p.taken,suggestion:m(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?`${m(p.number)} is already held (see held_by). Create the file as ${m(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.`:`${m(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let o=Array.isArray(n.dirs)?n.dirs.filter(d=>typeof d=="string"):void 0;if(o!==void 0&&o.length>0){let d=new Map,p=[];for(let v of o){let k=lr(v);if(k===null){p.push(v);continue}let E=d.get(k.repoRoot)??new Set;E.add(k.repoRelDir),d.set(k.repoRoot,E)}if(d.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],m=[],h=[],g=[];for(let[v,k]of d){let E=[...k],R=E.includes(""),I=await Ie(v,{dirs:R?void 0:E,minFiles:r});f.push({repo_root:v,dirs:R?null:E}),m.push(...I.findings),h.push(...I.facts.namespaces.map(A=>({repo_root:v,dir:A.dir,prefix:A.prefix,file_count:A.fileCount}))),g.push(...I.facts.skipped)}let y=m.filter(v=>v.status==="open"),b=m.filter(v=>v.status==="info"),w=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:y.length===0,open_count:y.length,preexisting_count:b.length,findings:y,preexisting:b.map(v=>`${v.namespace.prefix}${v.number}`),namespaces:h,skipped:g,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(y.length===0?h.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${y.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+w}}let a=J(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(d=>d.status==="open"),u=c.findings.filter(d=>d.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:u.length,findings:l,preexisting:u.map(d=>`${d.namespace.prefix}${d.number}`),namespaces:c.facts.namespaces.map(d=>({dir:d.dir,prefix:d.prefix,file_count:d.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:L(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=s(p=>r.findings.filter(f=>f.status===p),"of"),o=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let u="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",d=o.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:o.length,warn_count:a.length,preexisting_count:c.length,findings:[...o,...a],preexisting:c.map(p=>p.id),coverage_note:u,hint:(r.ok?"The declared entries agree.":d.length>0?`${d.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${o.length-d.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${o.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+u}}case"check_theme_class_drift":{let r=L(n.dir),i,o;if(r!==void 0){let d=lr(r);if(d===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};i=d.repoRoot,o=d.repoRelDir===""?void 0:[d.repoRelDir]}else i=J(),o=void 0;let a=De(i,{dirs:o,baseRef:L(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(d=>d.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(d=>({file:d.file,class:d.klass,status:d.status,missing_token:d.token,namespace:d.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=Vl(L(n.dir));if(r===null)return ql("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Pe(r.repoRoot,{dirs:r.scanDirs,baseRef:L(n.base_ref),includeBaseline:n.include_baseline!==!1}),o="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+o}}case"check_migration_ledger_drift":{let r=Vl(L(n.dir));if(r===null)return ql("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=bo(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:L(n.remote_db_url)}),o=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=s(p=>i.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),u=a("info"),d=o.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:o,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:u.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:d,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${d}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${d}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${d}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=L(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:L(n.kind),limit:Me(n.limit)})).map(o=>({...o,nodeKeyHash:pr(o.nodeKey)}))}case"codebase_trace":{let r=L(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:i,maxDepth:Me(n.max_depth),limit:Me(n.limit)})}case"codebase_snippet":{let r=L(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await e.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:pr(r)}}case"codebase_map":return e.getArchitecture({topN:Me(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:L(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Me(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language,file:i.filePath,start_line:i.startLine,node_key:i.nodeKey,node_key_hash:pr(i.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:L(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Me(n.limit)}),i;if(n.include_history!==!1)try{i=my(await e.fileHistory({since:L(n.since),limit:1}))}catch{i=void 0}let o;try{o=await e.reviewDetectors({baseRef:L(n.since)})}catch(l){o=ot(Bt(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,...r.headSha?{head_sha:r.headSha}:{},dirty:r.dirty,...r.baseSha?{base_sha:r.baseSha}:{},code_index_version:Wl,detector_coverage:o.coverage},c=o.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,u)=>l+u.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:pr(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...i?{history:i}:{}},verdict_args:{detector_findings:o.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:o.coverage,truncated:o.truncated,block_eligible:c,engines:o.engines,findings:o.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${o.findings.length} detector row(s) (${c} block-eligible, coverage ${o.coverage}) are hashes only; keep detector_findings even when it is []. Persisting a replayable record additionally needs commit_sha / diff_stats.head_sha.`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(o=>typeof o=="string"):void 0,i=await e.fileHistory({paths:r,since:L(n.since),limit:Me(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(o=>({path:o.path,last_commits:o.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:o.ownership?{top_authors:o.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:o.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(o=>({sha:o.sha,date_iso:o.dateIso,author_name:o.authorName,subject:o.subject,files_touched:o.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}s(zl,"dispatchLocalTool");var fr=class{constructor(t=Cl,n=null,r=J){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{s(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return _o}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Jl.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",o=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=await zl(this.getEngine(),i,o),c=JSON.stringify(a,null,2);return this.recordSavings(i,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=Rl(a)?`${Tl} (${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=Fl(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};var hy="https://vsddmiosisvfrairepxv.supabase.co/functions/v1";function Yl(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:hy}s(Yl,"functionsOrigin");var gy="/mcp-client-metrics-ingest",yy=4e3,by="codebase_search_tokens_saved";async function Xl(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Yl()}${gy}`,n=new AbortController,r=setTimeout(()=>n.abort(),yy);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:by,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await i.text().catch(()=>""),i.ok}catch(i){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${i instanceof Error?i.message:String(i)}
|
|
840
|
+
`),!1}finally{clearTimeout(r)}}s(Xl,"postSavingsMetric");vo();hr();yr();tn();import{join as Yb}from"node:path";var Xb="<synthetic>";function Bd(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:Yb(Uo,Go(e.cwd),`${e.transcript_stem}.jsonl`)}s(Bd,"transcriptPathFromSideChannel");var vr=class{constructor(t){this.deps=t}static{s(this,"TranscriptMetaReader")}path=null;offset=0;model=null;title=null;async read(){try{let n=this.deps.resolvePath();if(n!==this.path&&(this.path=n,this.offset=0,this.model=null,this.title=null),n!==null){let i=await(this.deps.stream??Ho)(n,{start:this.offset});for(let o of i.events)if(o.kind==="title"){let a=o.title.trim();a.length>0&&(this.title=a)}else o.kind==="assistant"&&!o.isSidechain&&typeof o.model=="string"&&o.model.length>0&&o.model!==Xb&&(this.model=o.model);i.bytesRead>this.offset&&(this.offset=i.bytesRead)}}catch{}let t=null;try{t=this.deps.fallbackModel?.()??null}catch{t=null}return{model:this.model??t,title:this.title}}};import{execFile as Qb}from"node:child_process";var Zb=8,e_=32;function t_(e){return e.split(`
|
|
841
|
+
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,e_)}s(t_,"parsePorcelain");function n_(e,t=Zb){let n=[];for(let r of e){let i=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(i.length===0)continue;let o=i.includes("/")?i.slice(0,i.lastIndexOf("/")):i;if(!(o.length===0||n.includes(o))&&(n.push(o),n.length>=t))break}return n}s(n_,"condenseToDirs");async function Wd(e=r_){let t=await e();if(t===null)return null;let n=n_(t_(t));return n.length>0?n:null}s(Wd,"deriveWorkingPaths");async function r_(){return await new Promise(e=>{Qb("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}s(r_,"defaultGitStatus");var Yk=1,Xk=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function Qk(e){return Xk.includes(e)}s(Qk,"isHookSubcommand");var Zk=6e4;async function ev(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==D()&&Ee(e),e;let t=D();if(t!==null)return t;let n=await Je(P);return n===null&&(process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
|
|
842
|
+
`),process.exit(1)),n.apiKey}s(ev,"ensureApiKey");async function tv(){let e=await Je(P);return e===null&&(process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
|
|
843
|
+
`),process.exit(1)),e.apiKey}s(tv,"reauth");async function nv(){let e=process.argv.slice(2).find(y=>!y.startsWith("-"));if(e==="install"){let y=process.argv.indexOf("install"),b=process.argv.slice(y+1),w=await Pl(b);process.exit(w)}if(e==="on-session-end"){let{runOnSessionEnd:y}=await Promise.resolve().then(()=>(Du(),Pu));process.exit(await y())}if(e==="guard"){let y=process.argv.indexOf("guard"),{runGuard:b}=await Promise.resolve().then(()=>(Gu(),Uu));process.exit(await b(process.argv.slice(y+1)))}if(e==="guard-inject"){let{runGuardInject:y}=await Promise.resolve().then(()=>(Ju(),qu));process.exit(await y())}if(e==="guard-gate"){let{runGuardGate:y}=await Promise.resolve().then(()=>(Zu(),Qu));process.exit(await y())}if(e==="guard-stop"){let{runGuardStop:y}=await Promise.resolve().then(()=>(np(),tp));process.exit(await y())}if(e==="gateway"){let y=process.argv.indexOf("gateway"),{runGateway:b}=await Promise.resolve().then(()=>(Hp(),jp));process.exit(await b(process.argv.slice(y+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:y}=await Promise.resolve().then(()=>(us(),ds));process.exit(await y())}if(e==="guard-cross-check"){let{runGuardCrossCheck:y}=await Promise.resolve().then(()=>(us(),ds));process.exit(await y())}if(e==="on-index-refresh"){let{runOnIndexRefresh:y}=await Promise.resolve().then(()=>(ms(),fs));process.exit(await y())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:y}=await Promise.resolve().then(()=>(ms(),fs));process.exit(await y())}if(e!==void 0&&Qk(e)){let y=await Promise.resolve().then(()=>(Xo(),Eu)),b={"on-session-start":y.runOnSessionStart,"on-tool-use":y.runOnToolUse,"on-file-write":y.runOnFileWrite,"on-file-edit":y.runOnFileEdit,"on-repo-health":y.runOnRepoHealth,"on-write-health":y.runOnWriteHealth,"sync-config":y.runSyncConfig,flush:y.runFlush,status:y.runHookStatus}[e];process.exit(await b())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(P+`
|
|
844
|
+
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(rv(),process.exit(0)),process.argv.includes("--reauth")&&(At(),await Je(P,process.stdout)===null&&process.exit(1),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
|
|
845
|
+
`),process.exit(0));let t=U(),n=await ev(),r=O(),o=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new ur:null,a=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new fr(void 0,o),c=`bridge-${zk()}`,l=s(async()=>{if(!o)return;let y=o.takePending();y.tokens<=0||await Xl({apiKey:n,deviceId:t,sessionId:c,tokensSaved:y.tokens,bridgeVersion:P})},"flushSavings"),u=o?setInterval(()=>{l()},Zk):null;u?.unref();let d=null,p=new gr({projectKey:r}),f=new vr({resolvePath:s(()=>Bd(p.sideChannel()),"resolvePath"),fallbackModel:s(()=>p.sideChannel()?.model??null,"fallbackModel")}),m=new mr({projectKey:r,identity:p,sessionMeta:s(()=>f.read(),"sessionMeta"),postToolCall:s((y,b)=>d===null?Promise.reject(new Error("presence: no active forwarder")):d.postPresenceToolCall(y,b),"postToolCall"),deriveWorkingPaths:s(()=>Wd(),"deriveWorkingPaths"),snapshot:r!==null?ld({projectKey:r}):void 0}),h=m.isEnabled?setInterval(()=>{m.pollActivity()},ed):null;if(h?.unref(),m.isEnabled){let y=s(b=>{m.end().finally(()=>process.exit(b))},"endAndExit");process.on("SIGTERM",()=>y(143)),process.on("SIGINT",()=>y(130))}let g=0;try{for(;;){let y=new bn({apiKey:n,deviceId:t,bridgeVersion:P,projectKey:r,localRouter:a,presence:m});d=y;try{await y.run();return}catch(b){if(b instanceof Rt&&g<Yk){g+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${b.message}; re-authorizing\u2026
|
|
846
|
+
`),n=await tv();continue}throw b}}}finally{u&&clearInterval(u),h&&clearInterval(h),await m.end(),await l()}}s(nv,"main");function rv(){let e=["","@maind-dev/mcp-bridge \u2014 local MCP wrapper that pins your maind API key to this device.","","Usage:"," npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)"," npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble, hooks)"," npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow"," npx -y @maind-dev/mcp-bridge --version"," npx -y @maind-dev/mcp-bridge --help","","Run `install --help` for full setup flags:"," npx -y @maind-dev/mcp-bridge install --help","","Claude Code hook subcommands (wired by `install`; run them by hand only for","diagnostics). They read the hook payload on stdin and use the bridge's own","paired credential \u2014 no separate init:"," on-session-start open a tracked session (Tier-3 flat metrics)"," on-tool-use bump counters + evaluate the ADR-039 context advisory"," on-file-write block a Write that claims a taken number (ADR-263)"," on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)"," on-repo-health surface this worktree's repo-health findings before the first edit in it (ADR-323, never blocks)"," on-write-health after an edit, run the path-relevant checks (spec/theme/table-acl) and report what this branch introduced (ADR-323, never blocks)"," on-session-end session analytics + close/flush the tracked session"," sync-config pull your context thresholds from the server (ADR-039)"," flush post queued Tier-3 metrics now"," status show pairing, queued metrics and active thresholds","","Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:"," guard install wire the guard hook pack (consent per hook) + set mode"," guard status mode, guard-hook wiring, local enforcement-event counts"," guard mode <warn|block> | guard off | guard stop-gate <on|off>",' guard skip --session <id> --reason "\u2026" logged override (block-gate exit)'," (hook subcommands, wired by `guard install`: guard-inject, guard-gate, guard-stop)","","Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent","Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.","","Environment overrides (rarely needed):"," MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)"," MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)"," MAIND_CLIENT_VERSION Optional client version marker (max 64 chars)"," MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth"," MAIND_AUTO_ANNOUNCE Set to 'off' to disable automatic presence announces (ADR-242)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," XDG_CONFIG_HOME Override config-dir parent on Linux/BSD","","Auto-presence (ADR-242): the bridge announces this session on the repo's","shared working tree (project_key hash + branch only \u2014 no hostname, no paths),","refreshes while tools are actually called, and ends the row on exit.","Persistent opt-out / explicit machine_label via config.json in the maind",'config dir: { "auto_announce": false, "machine_label": "my-box" }',"","Place this in your .mcp.json (or equivalent):",""," {",' "mcpServers": {',' "maind": {',' "command": "npx",',' "args": ["-y", "@maind-dev/mcp-bridge"]'," }"," }"," }",""];process.stderr.write(e.join(`
|
|
847
|
+
`))}s(rv,"printHelp");nv().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
|
|
848
848
|
`),process.exit(1)});
|