@maind-dev/mcp-bridge 0.72.0 → 0.73.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 +181 -173
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -1,41 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
`,{encoding:"utf8",mode:384});try{$c(n,384)}catch{}}function K(){let e=xi();if(!Mr(e))return null;let t=Lc(e,"utf8").trim();return t.length>0?t:null}function Fn(){let e=xi();Mr(e)&&Si(e,"",{encoding:"utf8",mode:384})}function jc(){try{return`mcp-bridge-${n_()}`}catch{return"mcp-bridge"}}function Lr(e){return{os:`${ki()} ${r_()}`,ide:"mcp-bridge",ext_version:e,device_id:te()}}var i_,o_,a_,ae=b(()=>{"use strict";o($n,"configDir");o(Fc,"ensureDir");i_="device-id",o_="api-key";o(te,"ensureDeviceId");a_=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;o(c_,"isUuid");o(xi,"apiKeyPath");o(rt,"writeApiKey");o(K,"readApiKey");o(Fn,"clearApiKey");o(jc,"bridgeLabel");o(Lr,"clientMeta")});function jn(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:l_}function Bt(e){return`${jn()}/${e.replace(/^\/+/,"")}`}var l_,Kt=b(()=>{"use strict";l_="https://fn.maind.dev/functions/v1";o(jn,"functionsOrigin");o(Bt,"functionsUrl")});var W,st=b(()=>{"use strict";W="0.72.0"});import{execFileSync as g_}from"node:child_process";import{createHash as y_}from"node:crypto";function __(e){return y_("sha256").update(e).digest("hex")}function b_(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 Ei(e){let t=b_(e);return t?__(t):null}function V(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&w_.test(e))return e;let t;try{t=g_("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Ei(t):null}var w_,We=b(()=>{"use strict";o(__,"sha256Hex");o(b_,"normalizeRemoteUrl");o(Ei,"projectKeyFromRemote");w_=/^[a-f0-9]{64}$/;o(V,"computeProjectKey")});import k_ from"node:path";import{fileURLToPath as S_}from"node:url";function x_(e,t=k_.sep){return e.split(t).includes("_npx")}function be(e){let t=e.extraArgs??[],n=o(r=>({command:"npx",args:["-y",Jc,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):x_(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 we(){try{let e=S_(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function zt(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Yc(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Yc(n)).join(" ")}function Fr(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Jc)}function jr(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Yc(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Jc,qt=b(()=>{"use strict";Jc="@maind-dev/mcp-bridge";o(x_,"isEphemeralEntry");o(be,"resolveBridgeLaunch");o(we,"currentBridgeEntry");o(zt,"launchToShellCommand");o(Fr,"isNpxForm");o(jr,"isLegacyHookForm");o(Yc,"shellQuote")});import*as z from"node:fs/promises";import*as Ur from"node:path";async function ne(e){try{return await z.readFile(e,"utf8")}catch(t){if(T_(t))return null;throw t}}async function Ti(e){await z.mkdir(e,{recursive:!0})}async function q(e,t,n){let r=Ur.dirname(e);await Ti(r);let s=Ur.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await z.writeFile(s,t,{encoding:"utf8",mode:n});try{await z.rename(s,e)}catch(i){if(R_(i))try{await z.copyFile(s,e),await z.unlink(s).catch(()=>{}),n!==void 0&&await z.chmod(e,n).catch(()=>{});return}catch(a){throw await z.unlink(s).catch(()=>{}),a}throw await z.unlink(s).catch(()=>{}),i}}async function nl(e,t){let n=await ne(e);return n===null?!1:n.split(/\r?\n/).some(s=>s.startsWith(t))}function T_(e){return rl(e)&&e.code==="ENOENT"}function R_(e){return!rl(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function rl(e){return typeof e=="object"&&e!==null&&"code"in e}var Ne=b(()=>{"use strict";o(ne,"readFileSafe");o(Ti,"ensureDir");o(q,"atomicWriteFile");o(nl,"hasLinePrefix");o(T_,"isNoEnt");o(R_,"isWindowsRenameFailure");o(rl,"isNodeError")});import{existsSync as B_}from"node:fs";import*as ll from"node:path";function Wn(e,t={},n=Ci){let r=t.fileExists??B_,s=t.expectedCommand??K_,i={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Ii(a)&&(i=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=V_(i,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 d=` Replace its command with: ${s(a.subcommand)}`;if(jr(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.`+d};if(Fr(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.`+d};let u=z_(l);return u!==null&&!r(u)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${u}, which does not exist \u2014 the hook fails silently on every run.`+d}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function Ni(e){return e.some(t=>t.status!=="ok")}function Wr(e){return e.some(t=>t.remedy==="run-install")}function K_(e){return zt(be({entryPath:we(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function V_(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let s of r){if(!Ii(s))continue;let i=s.hooks;if(Array.isArray(i))for(let a of i){if(!Ii(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function z_(e){for(let t of q_(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return ll.isAbsolute(t)?t:null;return null}function q_(e){let t=[],n="",r=!1;for(let s of e){if(s==="'"){r=!r;continue}if(!r&&/\s/.test(s)){n.length>0&&t.push(n),n="";continue}n+=s}return n.length>0&&t.push(n),t}function Ii(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ci,Gr,Bn=b(()=>{"use strict";qt();Ci=[{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."}],Gr=[{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."}];o(Wn,"inspectHookWiring");o(Ni,"hasWiringDrift");o(Wr,"needsInstallRun");o(K_,"defaultExpectedCommand");o(V_,"findCommand");o(z_,"extractScriptPath");o(q_,"tokenize");o(Ii,"isObject")});import*as Pi from"node:path";import*as ul from"node:readline";async function pl(e,t){let n=Pi.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let s;try{s=await ne(n)}catch(m){return{target:r,action:"merge",status:"failed",detail:`read: ${Oi(m)}`}}let i,a="create";if(s===null||s.trim().length===0)i={};else{a="merge";try{let m=JSON.parse(s);if(!Di(m))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};i=m}catch(m){return{target:r,action:"merge",status:"failed",detail:`parse: ${Oi(m)}`}}}let c=J_(i,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 X_(e.out,`
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},d=i.hooks?.[t.event]??[],u={...i,hooks:{...i.hooks??{},[t.event]:[...d,l]}},p=JSON.stringify(u,null,2)+`
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
`).
|
|
13
|
-
`))
|
|
14
|
-
`)){if(
|
|
15
|
-
`))
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
`),_=sd(y[0]??"");if(!_)continue;let w=y.slice(1).filter(k=>k.trim().length>0).length;h.push({sha:_.sha,dateIso:_.dateIso,authorName:_.authorName,subject:_.subject,filesTouched:w})}d={sinceInput:n.since,sinceResolved:u,commits:h.slice(0,is),truncated:h.length>is}}return{history:l,regression:d,ownershipWindowCommits:i,pathsTruncated:a.length>Vi}}var Ub,Hb,id,Vi,is,nd,zi=b(()=>{"use strict";re();Ub="",Hb="\0",id=200,Vi=50,is=100,nd="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";o(Gb,"clamp");o(rd,"splitRecords");o(sd,"parseHistoryRecord");o(Wb,"aggregateOwnership");o(od,"readFileHistory")});import{execFileSync as Bb}from"node:child_process";import{readdirSync as Kb,statSync as ad}from"node:fs";import{isAbsolute as Vb,join as qi,relative as zb,resolve as qb}from"node:path";function Jb(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function Xb(e,t){try{let n=Bb("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 Zb(e){let t;try{t=Kb(e)}catch{return null}for(let n of t.filter(Jb))try{let r=ad(qi(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function Qb(e){try{return ad(e).isDirectory()}catch{return!1}}function ew(e,t){let n=zb(e,t);return!n||n.startsWith("..")?t:n}function Yi(e){let t=Yb.filter(c=>Qb(qi(e,c))),n=Xb(e,"core.hooksPath"),r=n?Vb(n)?n:qb(e,n):qi(e,".git","hooks"),s=ew(e,r),i=Zb(r);if(i===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:s};let a=n?i===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:s}}function Ji(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 Yb,Xi=b(()=>{"use strict";Yb=[".githooks",".husky"];o(Jb,"isRealHook");o(Xb,"gitConfig");o(Zb,"hasExecutableHook");o(Qb,"isDir");o(ew,"displayPath");o(Yi,"resolveHookState");o(Ji,"describeHookState")});import{posix as cd}from"node:path";function Zt(e){let t=tw.exec(e);return t?t[1]:null}function Pe(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function at(e,t){let n=R(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=o(i=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||i===c||i.startsWith(`${c}/`)}),"wanted"),s=new Map;for(let i of n.split("\0").filter(Boolean)){if(!r(i))continue;let a=cd.basename(i),c=Zt(a);if(c===null)continue;let l=cd.dirname(i),d=s.get(l)??[];d.push({path:i,name:a,version:c}),s.set(l,d)}return[...s.entries()].map(([i,a])=>({dir:i,files:a.sort((c,l)=>Pe(c.version,l.version))})).sort((i,a)=>i.dir.localeCompare(a.dir))}function ld(e){let t=R(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(R(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var tw,zn=b(()=>{"use strict";re();tw=/^(\d+)_.+\.sql$/;o(Zt,"parseMigrationVersion");o(Pe,"compareVersions");o(at,"discoverSupabaseProjects");o(ld,"resolveDefaultBranch")});import{execFileSync as nw}from"node:child_process";import{existsSync as Z,readFileSync as ze,readdirSync as os,statSync as Qi}from"node:fs";import{posix as P}from"node:path";function ow(e,t){let n=(()=>{let s=R(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return s?s.trim():null})(),r=P.dirname(e);for(let s=0;s<8&&r&&r!==P.dirname(r);s++){if(Z(P.join(r,".git"))){let i=(()=>{let c=R(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&i!=null&&to(n,i))){let c=aw(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=P.dirname(r)}return null}function aw(e,t){let n=[];for(let r of sw){let s;try{s=os(P.join(e,r),{withFileTypes:!0}).filter(i=>i.isFile()).map(i=>i.name)}catch{continue}for(let i of s){let a=`${r}/${i}`,c=P.join(e,a),l=P.join(t,a);try{let d=Qi(c),u=Qi(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>iw)continue;ze(c).equals(ze(l))||n.push(a)}catch{continue}}}return n.sort()}function gd(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let c=e.upstream.split("/").slice(1).join("/");c&&c!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,s=e.ahead??0;r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${s>0?` (and ${s} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let i=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(i){let c=e.ahead??0;t.push({id:"worktree.commit-on-shared-base",status:"open",scope:"worktree",title:"Commit on the shared base tree",detail:`${c} commit(s) sit on the shared '${e.defaultBranch}' checkout and not on ${e.upstream??`origin/${e.defaultBranch}`} \u2014 in a workflow that reaches the base branch only through a pull request, a commit here is one that landed in the wrong place. A branch switch in a tree other sessions share can be undone by one of them between the switch and the commit, and nothing reports it.`,hint:`Move the commit onto its branch, then reset the base tree: git branch -f <branch> HEAD && git reset --hard ${e.upstream??`origin/${e.defaultBranch}`} (check for uncommitted work first). Do the work in its own worktree.`})}if(!i&&e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let c=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${c} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let c=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${c.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${no}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let c=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${c.map(l=>l.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:c.map(l=>`${l.install} (in ${P.dirname(l.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:c,diverging:l}=e.toolCopyDrift,d=l.slice(0,3).join(", "),u=l.length>3?` (+${l.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${c} ships ${d}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${l[0]}\` from this repo root), not via a path into ${c}.`})}if(e.stalePackageBuilds.length>0){let c=e.stalePackageBuilds,l=o(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),d=c.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".`:c.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:`${c.map(l).join(", ")}: src/ is newer than the built ${[...new Set(c.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${d}`,hint:`Rebuild: pnpm --filter ./${c[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let a=cw(e.hooks);return a&&t.push(a),lw(t)}function cw(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:Ji(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 lw(e){return[...e].sort((t,n)=>dd[t.status]-dd[n.status]||t.id.localeCompare(n.id))}function yd(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function Me(e){let t=e?.trim();return t||null}function dw(e){let t=Me(R(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(R(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function uw(e){let t=Me(R(e,["rev-parse","--git-dir"]));if(!t)return null;let n=P.isAbsolute(t)?t:P.join(e,t);return Z(P.join(n,"rebase-merge"))||Z(P.join(n,"rebase-apply"))?"rebase":Z(P.join(n,"MERGE_HEAD"))?"merge":Z(P.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function pw(e){let t=[],n=null,r=o(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let s of e.split(`
|
|
19
|
-
`))if(s.startsWith("worktree "))r(),n={path:s.slice(9).trim(),detached:!1};else if(n)s.startsWith("branch ")?n.branch=s.slice(7).trim().replace(/^refs\/heads\//,""):s.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function fw(e){let t=P.join(e,no);if(!Z(t))return[];try{return ze(t,"utf8").split(`
|
|
20
|
-
`).
|
|
21
|
-
`).
|
|
22
|
-
`).map(
|
|
23
|
-
|
|
24
|
-
`).filter(Boolean)
|
|
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 Zn(e){return e==='"'||e==="'"||e==="`"}function ps(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function cs(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,s=t;for(;s<e.length;){let i=e[s];if(Zn(i)){s=ds(e,s);continue}if(ps(e,s)){s=us(e,s);continue}if(i==="["||i==="{")r++;else if((i==="]"||i==="}")&&(r--,r===0))return e.slice(t,s+1);s++}return null}function Cw(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(ps(e,t)){t=us(e,t);continue}break}return e.slice(t)}function nn(e){let t=[],n=0,r=0,s=0;for(;s<e.length;){let i=e[s];if(Zn(i)){s=ds(e,s);continue}if(ps(e,s)){s=us(e,s);continue}i==="["||i==="{"||i==="("?n++:i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(t.push(e.slice(r,s)),r=s+1),s++}return t.push(e.slice(r)),t.map(i=>Cw(i).trim()).filter(i=>i.length>0)}function Od(e){let t=ds(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,s)=>s==="n"?`
|
|
26
|
-
`:s==="r"?"\r":s==="t"?" ":s)}function Nw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bo(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${Nw(t)}\b`,"m").exec(e);if(!r)return null;let s=r.index+r[0].length,i=!1;for(;s<e.length;){let a=e[s];if(Zn(a)){s=ds(e,s);continue}if(ps(e,s)){s=us(e,s);continue}if(!i){if(a==="="&&e[s+1]!=="="&&!"=!<>".includes(e[s-1]??" "))i=!0;else if(a===";")return null;s++;continue}if(a==="[")return cs(e,s);if(a===";")return null;s++}return null}function wo(e){let t={};if(!e.startsWith("{"))return t;for(let n of nn(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let s=r[2]??r[3],i=r[4].trim();Zn(i[0]??"")&&(t[s]=Od(i))}return t}function Ow(e,t){if(!e.startsWith("{"))return null;for(let n of nn(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 Dd(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Pd(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Md(e,t){let n=bo(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Pd(),s=[],i=0;for(let a of nn(n.slice(1,-1))){if(!a.startsWith("{")){i++;continue}let c=wo(a),l=c[t.key_field];if(!l){i++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");s.push({key:l,fields:Dd(c,t.fields),orderPath:d,ordinal:r(d)})}return s.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:i}:{records:s,error:null,dropped:i}}function Ld(e,t){let n=bo(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=Pd(),s=[],i=0,a=o((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let m of nn(c.slice(1,-1))){let h={...d},g=null;if(u.shape==="object"){if(!m.startsWith("{")){i++;continue}let y=wo(m);for(let[_,w]of Object.entries(u.fields??{}))h[_]=y[String(w)]??"";if(!p&&typeof u.children=="string"){let _=Ow(m,u.children);g=_&&_.startsWith("[")?cs(_,0):null}}else{if(!m.startsWith("[")){i++;continue}let y=nn(m.slice(1,-1));for(let[_,w]of Object.entries(u.fields??{})){let k=y[Number(w)];h[_]=k!==void 0&&Zn(k[0]??"")?Od(k):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?cs(_,0):null}}if(p){let y=h[t.key_field];if(!y){i++;continue}let _=(t.partition_by??[]).map(w=>h[w]??"");s.push({key:y,fields:Dd(h,t.fields),orderPath:_,ordinal:r(_)});continue}g!==null&&a(g,l+1,h)}},"walk");return a(n,0,{}),s.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:i}:{records:s,error:null,dropped:i}}function Id(e,t){return t.extractor==="object-array"?Md(e,t):Ld(e,t)}function $d(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(s=>n.has(s.replace("{key}",r).replace(/\/{2,}/g,"/")))}function Fd(e,t,n){return`spec.drift:${e}#${t}:${n}`}function Dw(e){return e.orderPath.join(" / ")||"(flat)"}function jd(e,t,n,r){let s=[],i=o((d,u,p,m,h,g)=>{s.push({id:Fd(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:m,detail:h,hint:g})},"push"),a=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=a.get(d.key);if(!u){i("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${Dw(d)}, position ${d.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let m=d.fields[p]??"",h=u.fields[p]??"";m!==h&&i("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${h||"\u2014"}", the specification says "${m||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),p=l.get(u);p?p.push(d):l.set(u,[d])}for(let[d,u]of l){let p=u.filter(y=>a.has(y.key)).map(y=>y.key),m=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),h=new Set(m),g=p.filter(y=>h.has(y));if(m.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";i("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${m.join(" \u2192 ")}
|
|
27
|
-
specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let d of n)c.has(d.key)||i("extra","warn",d.key,`${d.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let d of new Set([...a.keys(),...c.keys()])){if($d(d,e.grounding,r))continue;let u=a.has(d);i("unrealized",u?"open":"warn",d,u?`${d} is referenced by the implementation but has no artefact`:`${d} is declared by the specification but not built yet`,u?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return s}function Pw(e,t,n){let r=[];for(let s of e.assertions??[]){let i=n.get(s.path);if(!i)continue;let a=i.indexOf(s.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(i.slice(a+s.prefix.length));if(!c)continue;let l=Number(c[1]),d=t[s.counts];l!==d&&r.push({id:`spec.drift:${e.id}#assertion:${s.path}`,contract:e.id,dimension:"assertion",status:"warn",key:s.path,title:`${s.path} states ${l} where the ${s.counts} side has ${d}`,detail:`Counted after "${s.prefix}". ${s.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function Cd(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 Ud(e,t={}){let n=o(u=>({ok:!1,verdict:"no_opinion",reason:u,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(u=>t.contracts.includes(u.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(u=>`"${u}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let s=o(u=>{let p=[],m=[];for(let h of r){let g=u.get(h.spec.path),y=u.get(h.impl.path);if(g==null||y==null){let x=g==null?h.spec.path:h.impl.path;p.push(Cd(h.id,`Declared file could not be read: ${x}`)),m.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=Id(g,h.spec),w=Id(y,h.impl);if(_.error||w.error){p.push(Cd(h.id,_.error??w.error??"unknown")),m.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let k=_.dropped>0||w.dropped>0;m.push({id:h.id,measured:!0,specRecords:_.records.length,implRecords:w.records.length,partial:k}),k&&p.push({id:`contract.partial:${h.id}`,contract:h.id,dimension:"contract",status:"warn",key:null,title:`Contract "${h.id}" was measured incompletely`,detail:`${_.dropped} specification and ${w.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(...jd(h,_.records,w.records,e.files)),p.push(...Pw(h,{spec:_.records.length,impl:w.records.length},u))}return{findings:p,contracts:m}},"runOnce"),i=s(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let u of s(e.baselineSources).findings)u.id.startsWith("contract.unreadable:")||a.add(u.id);let c=new Map;for(let u of r)for(let p of u.exceptions??[])c.set(Fd(u.id,p.dimension,p.key),p);let l=i.findings.map(u=>{let p=c.get(u.id);return p?{...u,status:"info",exceptionReason:p.reason}:a.has(u.id)?{...u,status:"info",detail:`${u.detail}
|
|
28
|
-
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>Nd[u.status]-Nd[p.status]||u.id.localeCompare(p.id));let d=l.some(u=>u.status==="open");return{ok:!d,verdict:d?"drifted":"aligned",reason:null,findings:l,contracts:i.contracts}}function _o(e){let t=e?.trim();return t||null}function fs(e){let t;try{t=JSON.parse(e)}catch(a){return{manifest:null,error:`manifest is not valid JSON: ${a.message}`}}let n=o(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,"obj"),r=o(a=>typeof a=="string"?a:"","str"),s=n(t);if(!s||!Array.isArray(s.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let i=o(a=>({manifest:null,error:a}),"bad");for(let[a,c]of s.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${a+1}`;if(!l)return i(`${u}: not an object`);if(!d)return i(`${u}: \`id\` is missing`);if(!r(l.reason))return i(`${u}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let p of["spec","impl"]){let m=n(l[p]);if(!m)return i(`${u}: \`${p}\` is missing`);let h=r(m.extractor);if(!h)return i(`${u}: \`${p}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return i(`${u}: unknown \`${p}.extractor\` "${h}"`);if(!r(m.path)||!r(m.symbol)||!r(m.key_field))return i(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(m.levels))return i(`${u}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(l.exceptions)?l.exceptions:[]){let m=n(p);if(!m||!r(m.reason))return i(`${u}: exception for "${r(m?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:s,error:null}}function Mw(e){let t=_o(R(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(R(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Lw(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 Hd(e,t={}){let n=o((g,y)=>Iw.join(g,y),"join"),r=t.manifestPath??ls,s=[],i={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:s};if(_o(R(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...i,manifestError:"not a git work tree"};let a=n(e,r);if(!Aw(a))return{...i,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}=fs(Ad(a,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...i,isRepo:!0,manifestError:l};let d=new Map;for(let g of Lw(c))try{d.set(g,Ad(n(e,g),"utf8"))}catch{d.set(g,null),s.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=R(e,["ls-files","-z"]);if(p===null)s.push("could not list tracked files \u2014 grounding is skipped");else for(let g of p.split("\0"))g&&u.add(g);let m=null,h=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:Mw(e),y=t.baseRef??(g?`origin/${g}`:null);if(!y)s.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(m=_o(R(e,["merge-base",y,"HEAD"])),!m)s.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let _ of d.keys())h.set(_,R(e,["show",`${m}:${_}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:h,baseRef:m,files:u,skipped:s}}async function dt(e,t={}){let n=await Hd(e,t);return{...Ud(n,t),facts:n}}function vo(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var ls,Nd,Qn=b(()=>{"use strict";re();ls=".maind/spec-contracts.json";o(ds,"endOfString");o(us,"skipComment");o(Zn,"isQuote");o(ps,"isCommentStart");o(cs,"sliceBalanced");o(Cw,"stripLeadingTrivia");o(nn,"splitTopLevel");o(Od,"readStringLiteral");o(Nw,"escapeRe");o(bo,"findSymbolArray");o(wo,"parseObjectFields");o(Ow,"objectFieldRaw");o(Dd,"pickFields");o(Pd,"makeOrdinals");o(Md,"extractObjectArray");o(Ld,"extractNestedList");o(Id,"extractRecords");o($d,"isGrounded");o(Fd,"findingId");o(Dw,"partitionOf");o(jd,"compareContract");o(Pw,"checkAssertions");o(Cd,"unreadable");Nd={open:0,warn:1,info:2,passed:3};o(Ud,"computeSpecDrift");o(_o,"trimOrNull");o(fs,"parseManifest");o(Mw,"resolveDefaultBranch");o(Lw,"declaredPaths");o(Hd,"gatherSpecDriftFacts");o(dt,"checkSpecDrift");o(vo,"isSpecDriftGraded")});var M,ko,T,Se,er=b(()=>{(function(e){e.assertEqual=s=>{};function t(s){}o(t,"assertIs"),e.assertIs=t;function n(s){throw new Error}o(n,"assertNever"),e.assertNever=n,e.arrayToEnum=s=>{let i={};for(let a of s)i[a]=a;return i},e.getValidEnumValues=s=>{let i=e.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(let c of i)a[c]=s[c];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(i){return s[i]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},e.find=(s,i)=>{for(let a of s)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}o(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(M||(M={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ko||(ko={}));T=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Se=o(e=>{switch(typeof e){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(e)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":return Array.isArray(e)?T.array:e===null?T.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?T.promise:typeof Map<"u"&&e instanceof Map?T.map:typeof Set<"u"&&e instanceof Set?T.set:typeof Date<"u"&&e instanceof Date?T.date:T.object;default:return T.unknown}},"getParsedType")});var v,$w,se,ms=b(()=>{er();v=M.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$w=o(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),se=class e extends Error{static{o(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(i){return i.message},r={_errors:[]},s=o(i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}},"processError");return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};se.create=e=>new se(e)});var Fw,Le,So=b(()=>{ms();er();Fw=o((e,t)=>{let n;switch(e.code){case v.invalid_type:e.received===T.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case v.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:n=`Unrecognized key(s) in object: ${M.joinValues(e.keys,", ")}`;break;case v.invalid_union:n="Invalid input";break;case v.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case v.invalid_enum_value:n=`Invalid enum value. Expected ${M.joinValues(e.options)}, received '${e.received}'`;break;case v.invalid_arguments:n="Invalid function arguments";break;case v.invalid_return_type:n="Invalid function return type";break;case v.invalid_date:n="Invalid date";break;case v.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:M.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case v.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case v.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case v.custom:n="Invalid input";break;case v.invalid_intersection_types:n="Intersection results could not be merged";break;case v.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case v.not_finite:n="Number must be finite";break;default:n=t.defaultError,M.assertNever(e)}return{message:n}},"errorMap"),Le=Fw});function jw(e){Gd=e}function rn(){return Gd}var Gd,hs=b(()=>{So();Gd=Le;o(jw,"setErrorMap");o(rn,"getErrorMap")});function E(e,t){let n=rn(),r=tr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Le?void 0:Le].filter(s=>!!s)});e.common.issues.push(r)}var tr,Uw,Y,C,ut,Q,gs,ys,qe,sn,xo=b(()=>{hs();So();tr=o(e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:t,defaultError:c}).message;return{...s,path:i,message:c}},"makeIssue"),Uw=[];o(E,"addIssueToContext");Y=class e{static{o(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return C;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let i=await s.key,a=await s.value;r.push({key:i,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return C;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}},C=Object.freeze({status:"aborted"}),ut=o(e=>({status:"dirty",value:e}),"DIRTY"),Q=o(e=>({status:"valid",value:e}),"OK"),gs=o(e=>e.status==="aborted","isAborted"),ys=o(e=>e.status==="dirty","isDirty"),qe=o(e=>e.status==="valid","isValid"),sn=o(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var Wd=b(()=>{});var A,Bd=b(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(A||(A={}))});function O(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:o((a,c)=>{let{message:l}=e;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:s}}function qd(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function rv(e){return new RegExp(`^${qd(e)}$`)}function Yd(e){let t=`${zd}T${qd(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function sv(e,t){return!!((t==="v4"||!t)&&Jw.test(e)||(t==="v6"||!t)&&Zw.test(e))}function iv(e,t){if(!Vw.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function ov(e,t){return!!((t==="v4"||!t)&&Xw.test(e)||(t==="v6"||!t)&&Qw.test(e))}function av(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(e.toFixed(s).replace(".","")),a=Number.parseInt(t.toFixed(s).replace(".",""));return i%a/10**s}function on(e){if(e instanceof ie){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=le.create(on(r))}return new ie({...e._def,shape:o(()=>t,"shape")})}else return e instanceof je?new je({...e._def,type:on(e.element)}):e instanceof le?le.create(on(e.unwrap())):e instanceof Ee?Ee.create(on(e.unwrap())):e instanceof xe?xe.create(e.items.map(t=>on(t))):e}function To(e,t){let n=Se(e),r=Se(t);if(e===t)return{valid:!0,data:e};if(n===T.object&&r===T.object){let s=M.objectKeys(t),i=M.objectKeys(e).filter(c=>s.indexOf(c)!==-1),a={...e,...t};for(let c of i){let l=To(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===T.array&&r===T.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let i=0;i<e.length;i++){let a=e[i],c=t[i],l=To(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===T.date&&r===T.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function Jd(e,t){return new kt({values:e,typeName:N.ZodEnum,...O(t)})}function Vd(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Xd(e,t={},n){return e?Je.create().superRefine((r,s)=>{let i=e(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=Vd(t,r),l=c.fatal??n??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=Vd(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}}):Je.create()}var de,Kd,D,Hw,Gw,Ww,Bw,Kw,Vw,zw,qw,Yw,Eo,Jw,Xw,Zw,Qw,ev,tv,zd,nv,Ye,pt,ft,mt,ht,an,gt,yt,Je,Fe,he,cn,je,ie,_t,$e,_s,bt,xe,bs,ln,dn,ws,wt,vt,kt,St,Xe,ue,le,Ee,xt,Et,un,cv,nr,rr,Tt,lv,N,dv,Zd,Qd,uv,pv,eu,fv,mv,hv,gv,yv,_v,bv,wv,vv,kv,Sv,xv,Ev,Tv,Rv,Av,Iv,Cv,Nv,Ov,Dv,Pv,Mv,Lv,$v,Fv,jv,Uv,Hv,Gv,Wv,Bv,Kv,Vv,tu=b(()=>{ms();hs();Bd();xo();er();de=class{static{o(this,"ParseInputLazyPath")}constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Kd=o((e,t)=>{if(qe(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new se(e.common.issues);return this._error=n,this._error}}},"handleResult");o(O,"processCreateParams");D=class{static{o(this,"ZodType")}get description(){return this._def.description}_getType(t){return Se(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Se(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Y,ctx:{common:t.parent.common,data:t.data,parsedType:Se(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(sn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Se(t)},s=this._parseSync({data:t,path:r.path,parent:r});return Kd(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Se(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return qe(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>qe(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Se(t)},s=this._parse({data:t,path:r.path,parent:r}),i=await(sn(s)?s:Promise.resolve(s));return Kd(r,i)}refine(t,n){let r=o(s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n,"getIssueProperties");return this._refinement((s,i)=>{let a=t(s),c=o(()=>i.addIssue({code:v.custom,...r(s)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ue({schema:this,typeName:N.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:o(n=>this["~validate"](n),"validate")}}optional(){return le.create(this,this._def)}nullable(){return Ee.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return je.create(this)}promise(){return Xe.create(this,this._def)}or(t){return _t.create([this,t],this._def)}and(t){return bt.create(this,t,this._def)}transform(t){return new ue({...O(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new xt({...O(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new nr({typeName:N.ZodBranded,type:this,...O(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Et({...O(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return rr.create(this,t)}readonly(){return Tt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Hw=/^c[^\s-]{8,}$/i,Gw=/^[0-9a-z]+$/,Ww=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Bw=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Kw=/^[a-z0-9_-]{21}$/i,Vw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,qw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Yw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Jw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Xw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Zw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Qw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ev=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zd="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",nv=new RegExp(`^${zd}$`);o(qd,"timeRegexSource");o(rv,"timeRegex");o(Yd,"datetimeRegex");o(sv,"isValidIP");o(iv,"isValidJWT");o(ov,"isValidCidr");Ye=class e extends D{static{o(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==T.string){let i=this._getOrReturnCtx(t);return E(i,{code:v.invalid_type,expected:T.string,received:i.parsedType}),C}let r=new Y,s;for(let i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:v.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:v.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=t.data.length>i.value,c=t.data.length<i.value;(a||c)&&(s=this._getOrReturnCtx(t,s),a?E(s,{code:v.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&E(s,{code:v.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")qw.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"email",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Eo||(Eo=new RegExp(Yw,"u")),Eo.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"emoji",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Bw.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"uuid",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Kw.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"nanoid",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Hw.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cuid",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Gw.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cuid2",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ww.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"ulid",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),E(s,{validation:"url",code:v.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"regex",code:v.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Yd(i).test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?nv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?rv(i).test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?zw.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"duration",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?sv(t.data,i.version)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"ip",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?iv(t.data,i.alg)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"jwt",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?ov(t.data,i.version)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cidr",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?ev.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"base64",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?tv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"base64url",code:v.invalid_string,message:i.message}),r.dirty()):M.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:v.invalid_string,...A.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...A.errToObj(t)})}url(t){return this._addCheck({kind:"url",...A.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...A.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...A.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...A.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...A.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...A.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...A.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...A.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...A.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...A.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...A.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...A.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...A.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...A.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...A.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...A.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...A.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...A.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...A.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...A.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...A.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...A.errToObj(n)})}nonempty(t){return this.min(1,A.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Ye.create=e=>new Ye({checks:[],typeName:N.ZodString,coerce:e?.coerce??!1,...O(e)});o(av,"floatSafeRemainder");pt=class e extends D{static{o(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==T.number){let i=this._getOrReturnCtx(t);return E(i,{code:v.invalid_type,expected:T.number,received:i.parsedType}),C}let r,s=new Y;for(let i of this._def.checks)i.kind==="int"?M.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:v.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?av(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:v.not_finite,message:i.message}),s.dirty()):M.assertNever(i);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,A.toString(n))}gt(t,n){return this.setLimit("min",t,!1,A.toString(n))}lte(t,n){return this.setLimit("max",t,!0,A.toString(n))}lt(t,n){return this.setLimit("max",t,!1,A.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:A.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:A.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:A.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:A.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&M.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};pt.create=e=>new pt({checks:[],typeName:N.ZodNumber,coerce:e?.coerce||!1,...O(e)});ft=class e extends D{static{o(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==T.bigint)return this._getInvalidInput(t);let r,s=new Y;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):M.assertNever(i);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return E(n,{code:v.invalid_type,expected:T.bigint,received:n.parsedType}),C}gte(t,n){return this.setLimit("min",t,!0,A.toString(n))}gt(t,n){return this.setLimit("min",t,!1,A.toString(n))}lte(t,n){return this.setLimit("max",t,!0,A.toString(n))}lt(t,n){return this.setLimit("max",t,!1,A.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:A.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:A.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};ft.create=e=>new ft({checks:[],typeName:N.ZodBigInt,coerce:e?.coerce??!1,...O(e)});mt=class extends D{static{o(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==T.boolean){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:T.boolean,received:r.parsedType}),C}return Q(t.data)}};mt.create=e=>new mt({typeName:N.ZodBoolean,coerce:e?.coerce||!1,...O(e)});ht=class e extends D{static{o(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==T.date){let i=this._getOrReturnCtx(t);return E(i,{code:v.invalid_type,expected:T.date,received:i.parsedType}),C}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return E(i,{code:v.invalid_date}),C}let r=new Y,s;for(let i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:v.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:v.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):M.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:A.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:A.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};ht.create=e=>new ht({checks:[],coerce:e?.coerce||!1,typeName:N.ZodDate,...O(e)});an=class extends D{static{o(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==T.symbol){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:T.symbol,received:r.parsedType}),C}return Q(t.data)}};an.create=e=>new an({typeName:N.ZodSymbol,...O(e)});gt=class extends D{static{o(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==T.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:T.undefined,received:r.parsedType}),C}return Q(t.data)}};gt.create=e=>new gt({typeName:N.ZodUndefined,...O(e)});yt=class extends D{static{o(this,"ZodNull")}_parse(t){if(this._getType(t)!==T.null){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:T.null,received:r.parsedType}),C}return Q(t.data)}};yt.create=e=>new yt({typeName:N.ZodNull,...O(e)});Je=class extends D{static{o(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return Q(t.data)}};Je.create=e=>new Je({typeName:N.ZodAny,...O(e)});Fe=class extends D{static{o(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return Q(t.data)}};Fe.create=e=>new Fe({typeName:N.ZodUnknown,...O(e)});he=class extends D{static{o(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return E(n,{code:v.invalid_type,expected:T.never,received:n.parsedType}),C}};he.create=e=>new he({typeName:N.ZodNever,...O(e)});cn=class extends D{static{o(this,"ZodVoid")}_parse(t){if(this._getType(t)!==T.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:T.void,received:r.parsedType}),C}return Q(t.data)}};cn.create=e=>new cn({typeName:N.ZodVoid,...O(e)});je=class e extends D{static{o(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==T.array)return E(n,{code:v.invalid_type,expected:T.array,received:n.parsedType}),C;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&(E(n,{code:a?v.too_big:v.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(E(n,{code:v.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(E(n,{code:v.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>s.type._parseAsync(new de(n,a,n.path,c)))).then(a=>Y.mergeArray(r,a));let i=[...n.data].map((a,c)=>s.type._parseSync(new de(n,a,n.path,c)));return Y.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:A.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:A.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:A.toString(n)}})}nonempty(t){return this.min(1,t)}};je.create=(e,t)=>new je({type:e,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...O(t)});o(on,"deepPartialify");ie=class e extends D{static{o(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=M.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==T.object){let d=this._getOrReturnCtx(t);return E(d,{code:v.invalid_type,expected:T.object,received:d.parsedType}),C}let{status:r,ctx:s}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof he&&this._def.unknownKeys==="strip"))for(let d in s.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let u=i[d],p=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new de(s,p,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof he){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(d==="strict")c.length>0&&(E(s,{code:v.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=s.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new de(s,p,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let p=await u.key,m=await u.value;d.push({key:p,value:m,alwaysSet:u.alwaysSet})}return d}).then(d=>Y.mergeObjectSync(r,d)):Y.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return A.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:o((n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:A.errToObj(t).message??s}:{message:s}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:o(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:o(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:N.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of M.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:o(()=>n,"shape")})}omit(t){let n={};for(let r of M.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:o(()=>n,"shape")})}deepPartial(){return on(this)}partial(t){let n={};for(let r of M.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:o(()=>n,"shape")})}required(t){let n={};for(let r of M.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof le;)i=i._def.innerType;n[r]=i}return new e({...this._def,shape:o(()=>n,"shape")})}keyof(){return Jd(M.objectKeys(this.shape))}};ie.create=(e,t)=>new ie({shape:o(()=>e,"shape"),unknownKeys:"strip",catchall:he.create(),typeName:N.ZodObject,...O(t)});ie.strictCreate=(e,t)=>new ie({shape:o(()=>e,"shape"),unknownKeys:"strict",catchall:he.create(),typeName:N.ZodObject,...O(t)});ie.lazycreate=(e,t)=>new ie({shape:e,unknownKeys:"strip",catchall:he.create(),typeName:N.ZodObject,...O(t)});_t=class extends D{static{o(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new se(c.ctx.common.issues));return E(n,{code:v.invalid_union,unionErrors:a}),C}if(o(s,"handleResults"),n.common.async)return Promise.all(r.map(async i=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i,a=[];for(let l of r){let d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(l=>new se(l));return E(n,{code:v.invalid_union,unionErrors:c}),C}}get options(){return this._def.options}};_t.create=(e,t)=>new _t({options:e,typeName:N.ZodUnion,...O(t)});$e=o(e=>e instanceof wt?$e(e.schema):e instanceof ue?$e(e.innerType()):e instanceof vt?[e.value]:e instanceof kt?e.options:e instanceof St?M.objectValues(e.enum):e instanceof xt?$e(e._def.innerType):e instanceof gt?[void 0]:e instanceof yt?[null]:e instanceof le?[void 0,...$e(e.unwrap())]:e instanceof Ee?[null,...$e(e.unwrap())]:e instanceof nr||e instanceof Tt?$e(e.unwrap()):e instanceof Et?$e(e._def.innerType):[],"getDiscriminator"),_s=class e extends D{static{o(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.object)return E(n,{code:v.invalid_type,expected:T.object,received:n.parsedType}),C;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(E(n,{code:v.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),C)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let i of n){let a=$e(i.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of a){if(s.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);s.set(c,i)}}return new e({typeName:N.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...O(r)})}};o(To,"mergeValues");bt=class extends D{static{o(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=o((i,a)=>{if(gs(i)||gs(a))return C;let c=To(i.value,a.value);return c.valid?((ys(i)||ys(a))&&n.dirty(),{status:n.value,value:c.data}):(E(r,{code:v.invalid_intersection_types}),C)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};bt.create=(e,t,n)=>new bt({left:e,right:t,typeName:N.ZodIntersection,...O(n)});xe=class e extends D{static{o(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.array)return E(r,{code:v.invalid_type,expected:T.array,received:r.parsedType}),C;if(r.data.length<this._def.items.length)return E(r,{code:v.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),C;!this._def.rest&&r.data.length>this._def.items.length&&(E(r,{code:v.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new de(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Y.mergeArray(n,a)):Y.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};xe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xe({items:e,typeName:N.ZodTuple,rest:null,...O(t)})};bs=class e extends D{static{o(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.object)return E(r,{code:v.invalid_type,expected:T.object,received:r.parsedType}),C;let s=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)s.push({key:i._parse(new de(r,c,r.path,c)),value:a._parse(new de(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?Y.mergeObjectAsync(n,s):Y.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof D?new e({keyType:t,valueType:n,typeName:N.ZodRecord,...O(r)}):new e({keyType:Ye.create(),valueType:t,typeName:N.ZodRecord,...O(n)})}},ln=class extends D{static{o(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.map)return E(r,{code:v.invalid_type,expected:T.map,received:r.parsedType}),C;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new de(r,c,r.path,[d,"key"])),value:i._parse(new de(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return C;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return C;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};ln.create=(e,t,n)=>new ln({valueType:t,keyType:e,typeName:N.ZodMap,...O(n)});dn=class e extends D{static{o(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.set)return E(r,{code:v.invalid_type,expected:T.set,received:r.parsedType}),C;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(E(r,{code:v.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(E(r,{code:v.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function a(l){let d=new Set;for(let u of l){if(u.status==="aborted")return C;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}o(a,"finalizeSet");let c=[...r.data.values()].map((l,d)=>i._parse(new de(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new e({...this._def,minSize:{value:t,message:A.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:A.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};dn.create=(e,t)=>new dn({valueType:e,minSize:null,maxSize:null,typeName:N.ZodSet,...O(t)});ws=class e extends D{static{o(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.function)return E(n,{code:v.invalid_type,expected:T.function,received:n.parsedType}),C;function r(c,l){return tr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,rn(),Le].filter(d=>!!d),issueData:{code:v.invalid_arguments,argumentsError:l}})}o(r,"makeArgsIssue");function s(c,l){return tr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,rn(),Le].filter(d=>!!d),issueData:{code:v.invalid_return_type,returnTypeError:l}})}o(s,"makeReturnsIssue");let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Xe){let c=this;return Q(async function(...l){let d=new se([]),u=await c._def.args.parseAsync(l,i).catch(h=>{throw d.addIssue(r(l,h)),d}),p=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(p,i).catch(h=>{throw d.addIssue(s(p,h)),d})})}else{let c=this;return Q(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new se([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,i);if(!p.success)throw new se([s(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:xe.create(t).rest(Fe.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||xe.create([]).rest(Fe.create()),returns:n||Fe.create(),typeName:N.ZodFunction,...O(r)})}},wt=class extends D{static{o(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};wt.create=(e,t)=>new wt({getter:e,typeName:N.ZodLazy,...O(t)});vt=class extends D{static{o(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return E(n,{received:n.data,code:v.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:t.data}}get value(){return this._def.value}};vt.create=(e,t)=>new vt({value:e,typeName:N.ZodLiteral,...O(t)});o(Jd,"createZodEnum");kt=class e extends D{static{o(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return E(n,{expected:M.joinValues(r),received:n.parsedType,code:v.invalid_type}),C}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return E(n,{received:n.data,code:v.invalid_enum_value,options:r}),C}return Q(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};kt.create=Jd;St=class extends D{static{o(this,"ZodNativeEnum")}_parse(t){let n=M.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==T.string&&r.parsedType!==T.number){let s=M.objectValues(n);return E(r,{expected:M.joinValues(s),received:r.parsedType,code:v.invalid_type}),C}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=M.objectValues(n);return E(r,{received:r.data,code:v.invalid_enum_value,options:s}),C}return Q(t.data)}get enum(){return this._def.values}};St.create=(e,t)=>new St({values:e,typeName:N.ZodNativeEnum,...O(t)});Xe=class extends D{static{o(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.promise&&n.common.async===!1)return E(n,{code:v.invalid_type,expected:T.promise,received:n.parsedType}),C;let r=n.parsedType===T.promise?n.data:Promise.resolve(n.data);return Q(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Xe.create=(e,t)=>new Xe({type:e,typeName:N.ZodPromise,...O(t)});ue=class extends D{static{o(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:o(a=>{E(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return C;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?C:l.status==="dirty"?ut(l.value):n.value==="dirty"?ut(l.value):l});{if(n.value==="aborted")return C;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?C:c.status==="dirty"?ut(c.value):n.value==="dirty"?ut(c.value):c}}if(s.type==="refinement"){let a=o(c=>{let l=s.refinement(c,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!qe(a))return C;let c=s.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>qe(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):C);M.assertNever(s)}};ue.create=(e,t,n)=>new ue({schema:e,typeName:N.ZodEffects,effect:t,...O(n)});ue.createWithPreprocess=(e,t,n)=>new ue({schema:t,effect:{type:"preprocess",transform:e},typeName:N.ZodEffects,...O(n)});le=class extends D{static{o(this,"ZodOptional")}_parse(t){return this._getType(t)===T.undefined?Q(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};le.create=(e,t)=>new le({innerType:e,typeName:N.ZodOptional,...O(t)});Ee=class extends D{static{o(this,"ZodNullable")}_parse(t){return this._getType(t)===T.null?Q(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ee.create=(e,t)=>new Ee({innerType:e,typeName:N.ZodNullable,...O(t)});xt=class extends D{static{o(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===T.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};xt.create=(e,t)=>new xt({innerType:e,typeName:N.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...O(t)});Et=class extends D{static{o(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return sn(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new se(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new se(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Et.create=(e,t)=>new Et({innerType:e,typeName:N.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...O(t)});un=class extends D{static{o(this,"ZodNaN")}_parse(t){if(this._getType(t)!==T.nan){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:T.nan,received:r.parsedType}),C}return{status:"valid",value:t.data}}};un.create=e=>new un({typeName:N.ZodNaN,...O(e)});cv=Symbol("zod_brand"),nr=class extends D{static{o(this,"ZodBranded")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},rr=class e extends D{static{o(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return o(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?C:i.status==="dirty"?(n.dirty(),ut(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})},"handleAsync")();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?C:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:N.ZodPipeline})}},Tt=class extends D{static{o(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=o(s=>(qe(s)&&(s.value=Object.freeze(s.value)),s),"freeze");return sn(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Tt.create=(e,t)=>new Tt({innerType:e,typeName:N.ZodReadonly,...O(t)});o(Vd,"cleanParams");o(Xd,"custom");lv={object:ie.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(N||(N={}));dv=o((e,t={message:`Input not instance of ${e.name}`})=>Xd(n=>n instanceof e,t),"instanceOfType"),Zd=Ye.create,Qd=pt.create,uv=un.create,pv=ft.create,eu=mt.create,fv=ht.create,mv=an.create,hv=gt.create,gv=yt.create,yv=Je.create,_v=Fe.create,bv=he.create,wv=cn.create,vv=je.create,kv=ie.create,Sv=ie.strictCreate,xv=_t.create,Ev=_s.create,Tv=bt.create,Rv=xe.create,Av=bs.create,Iv=ln.create,Cv=dn.create,Nv=ws.create,Ov=wt.create,Dv=vt.create,Pv=kt.create,Mv=St.create,Lv=Xe.create,$v=ue.create,Fv=le.create,jv=Ee.create,Uv=ue.createWithPreprocess,Hv=rr.create,Gv=o(()=>Zd().optional(),"ostring"),Wv=o(()=>Qd().optional(),"onumber"),Bv=o(()=>eu().optional(),"oboolean"),Kv={string:o(e=>Ye.create({...e,coerce:!0}),"string"),number:o(e=>pt.create({...e,coerce:!0}),"number"),boolean:o(e=>mt.create({...e,coerce:!0}),"boolean"),bigint:o(e=>ft.create({...e,coerce:!0}),"bigint"),date:o(e=>ht.create({...e,coerce:!0}),"date")},Vv=C});var f={};oe(f,{BRAND:()=>cv,DIRTY:()=>ut,EMPTY_PATH:()=>Uw,INVALID:()=>C,NEVER:()=>Vv,OK:()=>Q,ParseStatus:()=>Y,Schema:()=>D,ZodAny:()=>Je,ZodArray:()=>je,ZodBigInt:()=>ft,ZodBoolean:()=>mt,ZodBranded:()=>nr,ZodCatch:()=>Et,ZodDate:()=>ht,ZodDefault:()=>xt,ZodDiscriminatedUnion:()=>_s,ZodEffects:()=>ue,ZodEnum:()=>kt,ZodError:()=>se,ZodFirstPartyTypeKind:()=>N,ZodFunction:()=>ws,ZodIntersection:()=>bt,ZodIssueCode:()=>v,ZodLazy:()=>wt,ZodLiteral:()=>vt,ZodMap:()=>ln,ZodNaN:()=>un,ZodNativeEnum:()=>St,ZodNever:()=>he,ZodNull:()=>yt,ZodNullable:()=>Ee,ZodNumber:()=>pt,ZodObject:()=>ie,ZodOptional:()=>le,ZodParsedType:()=>T,ZodPipeline:()=>rr,ZodPromise:()=>Xe,ZodReadonly:()=>Tt,ZodRecord:()=>bs,ZodSchema:()=>D,ZodSet:()=>dn,ZodString:()=>Ye,ZodSymbol:()=>an,ZodTransformer:()=>ue,ZodTuple:()=>xe,ZodType:()=>D,ZodUndefined:()=>gt,ZodUnion:()=>_t,ZodUnknown:()=>Fe,ZodVoid:()=>cn,addIssueToContext:()=>E,any:()=>yv,array:()=>vv,bigint:()=>pv,boolean:()=>eu,coerce:()=>Kv,custom:()=>Xd,date:()=>fv,datetimeRegex:()=>Yd,defaultErrorMap:()=>Le,discriminatedUnion:()=>Ev,effect:()=>$v,enum:()=>Pv,function:()=>Nv,getErrorMap:()=>rn,getParsedType:()=>Se,instanceof:()=>dv,intersection:()=>Tv,isAborted:()=>gs,isAsync:()=>sn,isDirty:()=>ys,isValid:()=>qe,late:()=>lv,lazy:()=>Ov,literal:()=>Dv,makeIssue:()=>tr,map:()=>Iv,nan:()=>uv,nativeEnum:()=>Mv,never:()=>bv,null:()=>gv,nullable:()=>jv,number:()=>Qd,object:()=>kv,objectUtil:()=>ko,oboolean:()=>Bv,onumber:()=>Wv,optional:()=>Fv,ostring:()=>Gv,pipeline:()=>Hv,preprocess:()=>Uv,promise:()=>Lv,quotelessJson:()=>$w,record:()=>Av,set:()=>Cv,setErrorMap:()=>jw,strictObject:()=>Sv,string:()=>Zd,symbol:()=>mv,transformer:()=>$v,tuple:()=>Rv,undefined:()=>hv,union:()=>xv,unknown:()=>_v,util:()=>M,void:()=>wv});var Ro=b(()=>{hs();xo();Wd();er();tu();ms()});var ee=b(()=>{Ro();Ro()});var Ao,Io=b(()=>{"use strict";ee();Ao=f.object({id:f.string().min(1),title:f.string().min(1).max(200),type:f.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:f.enum(["community","curated"]),lesson_class:f.enum(["general","architecture"]).default("general"),quality_tier:f.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:f.object({source:f.enum(["memory","vault","claude-md"]),source_id:f.string().min(1),migrated_at:f.string(),migrated_from_workspace:f.string().optional()}).optional(),context:f.object({tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tags:f.array(f.string()).default([])}),summary:f.string().min(1).max(500),problem:f.string().optional(),solution:f.string().optional(),gotchas:f.array(f.string()).default([]),template_body:f.string().min(1).optional(),target_file:f.string().min(1).optional(),submitted_by:f.string().optional(),evidence:f.string().optional(),last_validated_at:f.string().optional(),tool_versions:f.record(f.string(),f.string()).optional(),upvotes:f.number().int().nonnegative().default(0),version:f.number().int().min(1).default(1),changed_at:f.string().optional(),changelog:f.string().max(500).optional(),revision_of:f.string().optional(),org_id:f.string().uuid().optional(),org_name:f.string().optional(),scope:f.literal("private").optional(),body:f.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:f.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:f.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))})});var zv,nu=b(()=>{"use strict";ee();Io();zv=Ao.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:f.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:f.ZodIssueCode.custom,path:["template_body"],message:"template_body is required and must be non-empty"}),(!e.target_file||e.target_file.length===0)&&t.addIssue({code:f.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:f.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})})});var ru,su,iu,ou,Co,au,cu,lu,qv,du=b(()=>{"use strict";ee();ru=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],su=f.enum(ru),iu=["new_to_ai_agents","new_to_this_client","experienced"],ou=f.enum(iu),Co=[{id:"model-selection",header:"Model selection"},{id:"effort-levels",header:"Effort levels"},{id:"modes",header:"Modes"},{id:"language",header:"Language"},{id:"context-economy",header:"Context economy"},{id:"permissions",header:"Permissions"},{id:"cost",header:"Cost"},{id:"hooks",header:"Hooks"},{id:"learnings",header:"Learnings"},{id:"mcp-snippet",header:"MCP snippet"},{id:"first-week",header:"First week"}],au=Co.map(e=>e.header),cu=f.object({experience_level:f.array(ou).default([]),stack_filters:f.array(f.string()).default([])}).default({experience_level:[],stack_filters:[]}),lu=f.object({id:f.string().min(1),client:su,title:f.string().min(1),last_updated:f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:cu,version:f.number().int().min(1).default(1),changelog:f.string().max(500).optional()}),qv=lu.extend({body:f.string().min(1)})});var pu,vs,fu,ks,Yv,Jv,mu,hu,gu,yu,Ss,Xv,Zv,uu,Qv,_u,ek,bu=b(()=>{"use strict";ee();pu=["operating_procedure","code_review","communication_style"],vs=f.enum(pu),fu=["info","recommended","required"],ks=f.enum(fu),Yv=["optional","default_on","mandatory"],Jv=f.enum(Yv),mu=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],hu=f.enum(mu),gu=["verify","contribute","mixed"],yu=f.enum(gu),Ss=f.object({clients:f.array(hu).default([]),stacks:f.array(f.string()).default([]),intents:f.array(yu).default([])}).default({clients:[],stacks:[],intents:[]}),Xv=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,Zv=64,uu=200,Qv=f.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),_u=f.object({id:f.string().min(5).max(Zv).regex(Xv,"id must match conv_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),scope:vs,version:f.number().int().min(1),changed_at:Qv,changelog:f.string().max(500).optional(),applies_to:Ss,severity:ks.default("recommended"),disableability:Jv.default("default_on"),summary:f.string().min(1).max(uu,`summary must be \u2264 ${uu} chars (rendered as one line in init-push)`),review_gate:f.object({enabled:f.boolean(),min_matched_symbols:f.number().int().min(1).max(8).default(2),hard:f.boolean().default(!1)}).optional(),gateway_gate:f.object({enabled:f.boolean(),deny_tools:f.array(f.string().min(1).max(128)).min(1).max(16),servers:f.array(f.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),ek=_u.extend({body:f.string().min(1)})});var Ze=b(()=>{"use strict";Io();nu();du();bu()});var No,xs,Oo,wu,vu,ku,tk,Su=b(()=>{"use strict";ee();No=f.object({type:f.literal("text"),md:f.string().min(1).max(2e4)}),xs=f.number().min(0).max(1).optional(),Oo=f.object({type:f.literal("media"),kind:f.enum(["image","video"]),url:f.string().url().max(2048),alt:f.string().max(500).optional(),caption:f.string().max(500).optional(),fog:f.object({top:xs,right:xs,bottom:xs,left:xs}).optional()}),wu=f.object({label:f.string().min(1).max(40),color:f.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),vu=f.object({type:f.literal("accordion"),title:f.string().min(1).max(200),subtag:wu.optional(),blocks:f.array(f.discriminatedUnion("type",[No,Oo])).max(50)}),ku=f.discriminatedUnion("type",[No,Oo,vu]),tk=f.array(ku).max(100)});var xu,nk,Eu,Tu,rk,sk,ik,Ru=b(()=>{"use strict";ee();xu=["free","solo_pro","team","enterprise"],nk=f.enum(xu),Eu=["solo_pro","team","enterprise"],Tu=f.enum(Eu),rk=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),sk=f.object({user_id:f.string().uuid(),tier:Tu,reason:f.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:rk.nullable().optional(),auto_revoke_on_stripe:f.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),ik=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Au=b(()=>{"use strict"});var ok,ak,ck,Iu=b(()=>{"use strict";ee();ok=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),ak=f.object({org_id:f.string().uuid(),seats:f.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:f.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:ok.nullable().optional(),auto_revoke_on_stripe:f.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),ck=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Cu,lk,Nu,Ou,Du,Pu,dk,Mu=b(()=>{"use strict";ee();Cu=f.enum(["info","important","critical"]),lk=f.enum(["pass","warn","fail"]),Nu=f.object({type:f.enum(["template","lesson"]),id:f.string().min(1)}),Ou=f.object({languages:f.array(f.string()).optional(),tools:f.array(f.string()).optional()}).optional(),Du=f.discriminatedUnion("kind",[f.object({kind:f.literal("file-exists"),path:f.string().min(1)}),f.object({kind:f.literal("any-file-exists"),paths:f.array(f.string().min(1)).min(1)}),f.object({kind:f.literal("any-agent-config")}),f.object({kind:f.literal("file-size-budget"),field:f.enum(["claude_md","readme"]),max_chars:f.number().int().positive()}),f.object({kind:f.literal("readme-section-present"),headers:f.array(f.string().min(1)).min(1)}),f.object({kind:f.literal("adr-dir-present")}),f.object({kind:f.literal("git-present")}),f.object({kind:f.literal("quality-gates-configured"),pass_if_at_least:f.number().int().min(1).max(4).optional(),warn_if_at_least:f.number().int().min(0).max(4).optional()}),f.object({kind:f.literal("storage-risk-safe"),allow_unknown:f.boolean().optional()}),f.object({kind:f.literal("doc-path-discoverability")})]),Pu=f.object({id:f.string().min(1),title:f.string().min(1),severity:Cu,weight:f.number().int().positive().max(100),applies_when:Ou,check:Du,fail_message:f.string().min(1),warn_message:f.string().optional(),remediation:Nu.optional()}),dk=f.object({version:f.literal(1),checks:f.array(Pu).min(1)})});function pk(e){if(!uk.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Es(e){return[e.input_above_200k,e.output_above_200k,e.cache_read_above_200k,e.cache_write_5m_above_200k,e.cache_write_1h_above_200k].filter(t=>t!==void 0).length}function fk(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var uk,Ts,Lu,$u,Te,Fu,mk,ju=b(()=>{"use strict";ee();uk=/^\d{4}-\d{2}-\d{2}$/;o(pk,"isRealDate");Ts=f.string().refine(pk,{message:"expected a real calendar date as YYYY-MM-DD"}),Lu=["exact","prefix"],$u=f.enum(Lu),Te=f.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Fu=f.object({model_pattern:f.string().min(1).max(100),match_kind:$u,valid_from:Ts,valid_to:Ts.nullable().optional(),input:Te,output:Te,cache_read:Te,cache_write_5m:Te,cache_write_1h:Te,long_context:f.enum(["same_price","tiered"]).optional(),input_above_200k:Te.optional(),output_above_200k:Te.optional(),cache_read_above_200k:Te.optional(),cache_write_5m_above_200k:Te.optional(),cache_write_1h_above_200k:Te.optional(),context_threshold_tokens:f.number().int().positive().nullable().optional(),source_url:f.string().url().max(500).nullable().optional(),note:f.string().max(500).nullable().optional()}).strict().refine(e=>!e.valid_to||e.valid_to>e.valid_from,{message:"valid_to must be after valid_from",path:["valid_to"]}).refine(e=>Es(e)===0||Es(e)===5,{message:"above-200k rates must be given for all five classes or none",path:["input_above_200k"]}).refine(e=>e.long_context==="tiered"||Es(e)===0,{message:'above-200k rates require long_context: "tiered"',path:["long_context"]}).refine(e=>e.context_threshold_tokens==null||e.long_context==="tiered",{message:'context_threshold_tokens requires long_context: "tiered"',path:["context_threshold_tokens"]}).refine(e=>Es(e)===0||e.context_threshold_tokens==null||e.context_threshold_tokens===2e5,{message:"above-rates are only supported at context_threshold_tokens: 200000 \u2014 the analyzer groups against that constant and cannot see another boundary",path:["context_threshold_tokens"]});o(Es,"aboveRateCount");o(fk,"rowKey");mk=f.object({changelog:f.string().min(1).max(500),as_of:Ts,source_url:f.string().url().max(500),rows:f.array(Fu).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((s,i)=>{let a=fk(s),c=n.get(a);c!==void 0?t.addIssue({code:f.ZodIssueCode.custom,path:["rows",i],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,i)});let r=new Map;e.rows.forEach((s,i)=>{let a=`${s.model_pattern}|${s.match_kind}`,c=r.get(a)??[];c.push({i,r:s}),r.set(a,c)});for(let s of r.values())if(!(s.length<2)){s.sort((i,a)=>i.r.valid_from.localeCompare(a.r.valid_from));for(let i=0;i<s.length-1;i++){let a=s[i],c=s[i+1];(!a.r.valid_to||a.r.valid_to>c.r.valid_from)&&t.addIssue({code:f.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var pn=b(()=>{"use strict"});var sr=b(()=>{"use strict"});var Wu=b(()=>{"use strict";sr();pn()});var Bu=b(()=>{"use strict";pn()});var Ku=b(()=>{"use strict";Ze();sr();pn()});var Vu=b(()=>{"use strict";sr();pn()});var zu=b(()=>{"use strict";pn();Wu();Bu();Ku();Vu();sr()});var Dk,Pk,qu,Mk,Yu,Do,Ju,Xu,Zu,Qu,Lk,Po=b(()=>{"use strict";ee();Ze();Dk=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,Pk=64,qu=200,Mk=1e3,Yu=f.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),Do=f.enum(["low","medium","high"]),Ju=f.object({owner:f.string().min(1).max(160).optional(),risk_level:Do.optional(),reviewed_at:Yu.optional()}).default({}),Xu=f.object({tags:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),limit:f.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),Zu=f.object({lesson_query:Xu,lesson_pins:f.array(f.string()).default([]),lesson_excludes:f.array(f.string()).default([]),convention_ids:f.array(f.string()).default([]),template_ids:f.array(f.string()).default([]),setup_guide_ids:f.array(f.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),Qu=f.object({id:f.string().min(6).max(Pk).regex(Dk,"id must match skill_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),version:f.number().int().min(1),changed_at:Yu,tier:f.enum(["community","curated"]).default("curated"),summary:f.string().min(1).max(qu,`summary must be \u2264 ${qu} chars (rendered as one line in skill_index)`),description:f.string().max(Mk).optional(),applies_to:Ss,membership:Zu,governance:Ju}),Lk=Qu.extend({body:f.string().default(""),org_id:f.string().uuid().optional(),org_name:f.string().optional()})});var ep,tp,np,rp,sp,ip,$k,op,Fk,jk,ap=b(()=>{"use strict";ee();Po();ep=f.enum(["maind","agent-skill"]),tp=f.enum(["ready","needs_attention","blocked"]),np=f.enum(["info","important","critical"]),rp=f.enum(["pass","warn","fail"]),sp=f.enum(["structure","governance","scope","membership","package","references"]),ip=f.object({id:f.string().min(1),title:f.string().min(1),status:rp,severity:np,category:sp,field:f.string().nullable().optional(),message:f.string().min(1),hint:f.string().optional()}),$k=f.object({lesson_ids:f.array(f.string()).optional(),convention_ids:f.array(f.string()).optional(),template_ids:f.array(f.string()).optional(),setup_guide_ids:f.array(f.string()).optional()}).default({}),op=f.object({name:f.string().min(1).max(64),description:f.string().min(1).max(1024),license:f.string().optional(),compatibility:f.union([f.string(),f.array(f.string())]).optional(),metadata:f.record(f.string()).default({}),"allowed-tools":f.union([f.string(),f.array(f.string())]).optional()}).passthrough(),Fk=f.object({directory_name:f.string().min(1).max(120).optional(),frontmatter:op,body:f.string().default(""),file_listing:f.array(f.string()).optional()}),jk=f.object({format:ep,subject:f.string().min(1),status:tp,summary:f.string().min(1),counts:f.object({pass:f.number().int().min(0),warn:f.number().int().min(0),fail:f.number().int().min(0)}),checks:f.array(ip),next_steps:f.array(f.string()),trust_note:f.string().min(1)})});var cp,Uk,lp,dp,up,fn,Hk,pp,fp,mp,hp,gp,Gk,Wk,yp,Bk,_p=b(()=>{"use strict";ee();Ze();cp=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],Uk=f.enum(cp),lp=["verdict","advisory"],dp=f.enum(lp),up=["block","warn","note"],fn=f.enum(up),Hk=f.object({convention_id:f.string().min(1).max(64),convention_version:f.number().int().min(1),severity:ks,scope:vs,grade:dp,matched_symbols:f.array(f.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:f.array(f.string().min(1).max(512)).max(64).default([]),summary:f.string().max(2e3),hard:f.boolean().optional()}),pp=["open","warn","info"],fp=f.enum(pp),mp=["introduced","pre_existing"],hp=f.enum(mp),gp=["full","partial","none"],Gk=f.enum(gp),Wk=f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:f.string().regex(/^\d+\.\d+\.\d+$/),rule_id:f.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:fp,baseline:hp,evidence_hash:f.string().regex(/^[a-f0-9]{64}$/),count:f.number().int().min(1).max(1e5)}),yp=f.object({version:f.literal(1).default(1),actions:f.object({required:fn.default("block"),recommended:fn.default("warn"),info:fn.default("note")}).default({}),overrides:f.array(f.object({convention_id:f.string().min(1).max(64),action:fn})).max(64).default([]),risk_flag_action:f.enum(["warn","note","ignore"]).default("warn"),detector_overrides:f.array(f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),action:fn,reason:f.string().min(1).max(200)})).max(32).optional()}),Bk=yp.parse({})});var bp,wp,vp,kp,Sp,Mo,Kk,Vk,xp,Ep,Tp,Rp,Ap,zk,qk,Ip,Cp,Yk,Np=b(()=>{"use strict";ee();bp=14,wp=14,vp=14,kp=1,Sp=365,Mo=f.number().int().min(kp).max(Sp),Kk=["propose","direct"],Vk="propose",xp=["propose","direct"],Ep="propose",Tp=["propose","direct"],Rp="propose",Ap=["off","propose","direct"],zk=["member","admin","owner"],qk="member",Ip="off",Cp=f.object({version:f.literal(1).default(1),at_risk_days:Mo.default(bp),stagnation_days:Mo.default(wp),agent_date_mode:f.enum(Kk).default(Vk),health_manual_ttl_days:Mo.default(vp),agent_event_mode:f.enum(xp).default(Ep),agent_update_mode:f.enum(Tp).default(Rp),agent_pull_mode:f.enum(Ap).default(Ip),org_wide_authoring_min_role:f.enum(zk).default(qk)}),Yk=Cp.parse({})});var Op,Jk,Dp=b(()=>{"use strict";ee();Op=f.object({version:f.literal(1).default(1),org_visibility:f.boolean().default(!1),session_span_visibility:f.boolean().default(!0)}),Jk=Op.parse({})});var Pp,Mp,Xk,Zk,Lp=b(()=>{"use strict";ee();Pp=f.object({tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tags:f.array(f.string()).default([])}),Mp=f.object({id:f.string().uuid(),user_id:f.string().uuid(),project:f.string().max(200).nullable().optional(),title:f.string().min(1).max(200),body:f.string().min(1).max(2e4),context:Pp.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:f.string(),updated_at:f.string(),last_recalled_at:f.string().nullable().optional(),recall_count:f.number().int().nonnegative().default(0),graduated_draft_id:f.string().uuid().nullable().optional(),deleted_at:f.string().nullable().optional()}),Xk=Mp.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:f.number()}),Zk=f.object({id:f.string().uuid(),title:f.string(),summary:f.string(),tags:f.array(f.string()).default([])})});var $p=b(()=>{"use strict"});var Fp=b(()=>{"use strict"});function Rs(e){let t=[],n=null;return e.split(`
|
|
29
|
-
`).forEach((r,s)=>{let i=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(i===""||a>n)return;n=null}if(i===""||i.startsWith("#"))return;let c=eS.exec(r);if(!c)return;let l=c[3]??"";if(Qk.has(l.trim())){n=a;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&t.push({line:s+1,value:d})}),t}var Qk,eS,jp=b(()=>{"use strict";Qk=new Set(["|",">","|-",">-","|+",">+"]),eS=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;o(Rs,"plainScalarViolations")});function or(e,t){let n=o(c=>{let[l,d=""]=c.split("-",2),u=l.split(".").map(p=>{let m=Number(p);return Number.isFinite(m)?m:0});for(;u.length<3;)u.push(0);return[u,d.length>0?d.split("."):[]]},"split"),[r,s]=n(e),[i,a]=n(t);for(let c=0;c<Math.max(r.length,i.length);c+=1){let l=(r[c]??0)-(i[c]??0);if(l!==0)return l<0?-1:1}if(s.length===0&&a.length===0)return 0;if(s.length===0)return 1;if(a.length===0)return-1;for(let c=0;c<Math.max(s.length,a.length);c+=1){let l=s[c],d=a[c];if(l===void 0)return-1;if(d===void 0)return 1;let u=/^\d+$/.test(l),p=/^\d+$/.test(d);if(u&&p){let m=Number(l)-Number(d);if(m!==0)return m<0?-1:1}else{if(u!==p)return u?-1:1;if(l!==d)return l<d?-1:1}}return 0}var Up=b(()=>{"use strict";o(or,"compareSemver")});var Lo=b(()=>{"use strict";Ze();Su();Ze();Ze();Ru();Au();Iu();Mu();ju();zu();Ze();Po();ap();_p();Np();Dp();Lp();$p();Fp();jp();Up()});import{execFileSync as tS}from"node:child_process";import{existsSync as nS,readFileSync as rS}from"node:fs";import{join as sS}from"node:path";function ar(e){let t=[],n=e.split(`
|
|
30
|
-
`);for(let r=0;r<n.length;r+=1){let s=n[r]??"";if(!/^##(?!#)\s/.test(s))continue;let i=/(\d+\.\d+\.\d+)/.exec(s);i&&t.push({version:i[1],line:r+1,raw:s.trim(),shape:/^##\s+Unreleased\b/i.test(s)?"unreleased-labelled":iS.test(s)?"never-published":"released"})}return t}function Gp(e){let t=new Map;for(let n of ar(e)){let r=t.get(n.version);r?r.push(n):t.set(n.version,[n])}return[...t.entries()].filter(([,n])=>n.length>1).map(([n,r])=>({version:n,count:r.length,lines:r.map(s=>s.line),shapes:r.map(s=>s.shape)})).sort((n,r)=>(n.lines[0]??0)-(r.lines[0]??0))}function Wp(e,t){let n=Gp(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of ar(t))r.set(a.version,(r.get(a.version)??0)+1);let s=[],i=[];for(let a of n){let c=r.get(a.version)??0;(a.count>c?s:i).push({...a,countBefore:c})}return{introduced:s,preExisting:i,baseResolved:!0}}function Bp(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no CHANGELOG.md tracked",findings:[],facts:e};let t=[];for(let r of e.files){if(r.head===null)continue;let s=Wp(r.head,e.baseRef===null?null:r.base);for(let i of s.introduced)t.push({path:r.path,version:i.version,level:"open",count:i.count,countBefore:i.countBefore,lines:i.lines,title:`${r.path}: version ${i.version} has ${i.count} headings (was ${i.countBefore})`});for(let i of s.preExisting)t.push({path:r.path,version:i.version,level:"info",count:i.count,countBefore:i.countBefore,lines:i.lines,title:`${r.path}: version ${i.version} already had ${i.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function Hp(e,t){try{return tS("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function oS(e,t={}){let n=Hp(["ls-files","-z","--","*CHANGELOG.md","CHANGELOG.md"],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),s=t.baseRef??null,i=r.map(a=>{let c=sS(e,a);return{path:a,head:nS(c)?rS(c,"utf8"):null,base:s===null?null:Hp(["show",`${s}:${a}`],e)}});return{isRepo:!0,baseRef:s,files:i}}function $o(e,t={}){return Bp(oS(e,t))}var iS,As=b(()=>{"use strict";iS=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;o(ar,"parseVersionHeadings");o(Gp,"findDuplicateHeadings");o(Wp,"classifyIntroduced");o(Bp,"computeChangelogDuplicates");o(Hp,"git");o(oS,"gatherChangelogFacts");o($o,"checkChangelogDuplicates")});import{execFileSync as aS}from"node:child_process";import{existsSync as cS,readFileSync as Kp}from"node:fs";import{dirname as Vp,join as zp}from"node:path";function Yp(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.packages.length===0)return{ok:!1,verdict:"no_opinion",reason:"no publishable package.json tracked",findings:[],facts:e};if(!e.registryReachable)return{ok:!1,verdict:"no_opinion",reason:e.registryError??"registry unreachable",findings:[],facts:e};let t=[];for(let n of e.packages){let r=new Set(e.published[n.name]??[]),s=new Set(n.documentedBase??n.documented),i=[...n.documented].sort(or);for(let a of i){if(r.has(a)||or(a,n.version)>=0)continue;let c=!s.has(a);t.push({package:n.name,version:a,level:c?"open":"info",rule:"release.phantom",title:c?`${n.name}@${a} is newly documented as released but the registry never served it`:`${n.name}@${a} is documented as released but the registry never served it`})}for(let a of[...n.neverPublished??[]].sort(or))r.has(a)&&t.push({package:n.name,version:a,level:"info",rule:"release.mislabelled",title:`${n.name}@${a} is marked never published but the registry serves it`});r.has(n.version)||t.push({package:n.name,version:n.version,level:"info",rule:"release.unpublished",title:`${n.name}@${n.version} is not published yet`})}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"mismatch",reason:null,findings:t,facts:e}}function qp(e){let t=ar(e),n=[...new Set(t.filter(i=>i.shape!=="never-published").map(i=>i.version))],r=new Set(n),s=[...new Set(t.filter(i=>i.shape==="never-published"&&!r.has(i.version)).map(i=>i.version))];return{documented:n,neverPublished:s}}function Fo(e,t){try{return aS("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function Jp(e,t=null){let n=Fo(["ls-files","-z","--","package.json","*/package.json"],e);if(n===null)return[];let r=[];for(let s of[...new Set(n.split("\0").filter(Boolean))].sort()){let i;try{i=JSON.parse(Kp(zp(e,s),"utf8"))}catch{continue}if(i.private===!0||typeof i.name!="string"||typeof i.version!="string")continue;let a=Vp(s)==="."?"":Vp(s),c=zp(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=cS(c)?qp(Kp(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,p=t===null?null:Fo(["show",`${t}:${u}`],e),m=t===null?null:p===null?[]:qp(p).documented;r.push({dir:a,name:i.name,version:i.version,documented:l,documentedBase:m,neverPublished:d})}return r}async function lS(e){let t=`https://registry.npmjs.org/${e.replace("/","%2F")}`,n=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(n.status===404)return[];if(!n.ok)throw new Error(`HTTP ${n.status}`);let r=await n.json();return Object.keys(r.versions??{})}async function Xp(e,t={}){if(Fo(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=Jp(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??lS,s={};for(let i of n)try{s[i.name]=await r(i.name)}catch(a){return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:`${i.name}: ${a.message}`}}return{isRepo:!0,packages:n,published:s,registryReachable:!0,registryError:null}}async function jo(e,t={}){return Yp(await Xp(e,t))}var Uo=b(()=>{"use strict";Lo();As();o(Yp,"computeReleaseClaims");o(qp,"claimsOf");o(Fo,"git");o(Jp,"discoverPackages");o(lS,"packument");o(Xp,"gatherReleaseClaimsFacts");o(jo,"checkReleaseClaims")});import{execFileSync as dS}from"node:child_process";import{existsSync as uS,readFileSync as pS}from"node:fs";import{join as fS}from"node:path";function Qp(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no workflow files under .github/workflows",findings:[],facts:e};let t=[];for(let n of e.files){if(n.content===null)continue;let r=new Set(n.base===null?[]:Rs(n.base).map(s=>s.value));for(let s of Rs(n.content)){let i=s.value.length>60?`${s.value.slice(0,57)}\u2026`:s.value,a=e.baseRef!==null&&!r.has(s.value);t.push({path:n.path,level:a?"open":"info",line:s.line,value:s.value,title:`${n.path}:${s.line}: unquoted plain scalar containing ": " \u2014 ${i}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function Zp(e,t){try{return dS("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function ef(e,t={}){let n=Zp(["ls-files","-z","--",".github/workflows/*.yml",".github/workflows/*.yaml"],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),s=t.baseRef??null;return{isRepo:!0,baseRef:s,files:r.map(i=>{let a=fS(e,i);return{path:i,content:uS(a)?pS(a,"utf8"):null,base:s===null?null:Zp(["show",`${s}:${i}`],e)}})}}function Ho(e,t={}){return Qp(ef(e,t))}var Go=b(()=>{"use strict";Lo();o(Qp,"computeWorkflowYaml");o(Zp,"git");o(ef,"gatherWorkflowYamlFacts");o(Ho,"checkWorkflowYaml")});import{readFileSync as mS}from"node:fs";import{join as hS,posix as gS}from"node:path";function tf(e){let t="",n=0,r=e.length;for(;n<r;){let s=e[n],i=e[n+1];if(s==="-"&&i==="-"){for(;n<r&&e[n]!==`
|
|
31
|
-
`;)n++;continue}if(s==="/"&&i==="*"){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(s==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let a=(s==="E"||s==="e")&&i==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(s==="'"||a){let c=s!=="'";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+=s,n++}return t}function ge(e){let t=[],n="",r=!1,s=!1,i=o(()=>{t.push(s?n:n.toLowerCase()),n="",s=!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,s=!0;continue}if(l==="."&&!r){i();continue}n+=l}i();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 Ue(e){let t=[],n=0,r="";for(let s of e){if(s==="("&&n++,s===")"&&(n=Math.max(0,n-1)),s===","&&n===0){t.push(r.trim()),r="";continue}r+=s}return r.trim()&&t.push(r.trim()),t}function yS(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,s,i]=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&&!Ue(a[1]).map(m=>ge(m)?.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||!Ue(c[1]).map(p=>ge(p)?.name??"").filter(Boolean).includes("public"))return null;let d=Ue(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>ge(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of Ue(s)){let m=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!m)continue;let h=m[1].toUpperCase();if(h==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...cr]};m[2]!=="("&&cr.includes(h)&&u.push(h)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function nf(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,s,i]=t;if(n)return null;let a=s.trim();if(_S.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!Ue(l[1]).map(m=>ge(m)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),m=Ue(p).map(h=>ge(h)).filter(h=>h!==null).filter(h=>h.schema==="public").map(h=>h.name);if(m.length===0)return null;c=m}let d=Ue(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>ge(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of Ue(r)){let m=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!m)continue;let h=m[1].toUpperCase(),g=m[2]==="(";if(h==="ALL")return{tables:c,roles:d,writePrivs:[...cr]};!g&&cr.includes(h)&&u.push(h)}return{tables:c,roles:d,writePrivs:u}}function Bo(e){let t=new Map,n=[...e].sort((s,i)=>Pe(s.version,i.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let s of n){let i=tf(s.content);for(let a of i.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=yS(c);if(!p)continue;let m=p.roles.includes("anon"),h=p.roles.includes("authenticated");if(p.action==="revoke"){if(m&&(r.anonAddressed=!0),h)for(let g of p.writePrivs)r.authWritesRevoked.add(g)}else if(m&&(r.anonAddressed=!1),h)for(let g of p.writePrivs)r.authWritesRevoked.delete(g);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=ge(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:s.version,anonAddressed:r.anonAddressed,authWritesRevoked:new Set(r.authWritesRevoked)});continue}let d=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(c);if(d){let p=d[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let m of Ue(p)){let h=ge(m);h&&h.schema==="public"&&t.delete(h.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(u){let p=ge(u[1]),m=ge(u[2]);if(p&&m&&p.schema==="public"){let h=t.get(p.name);h&&(t.delete(p.name),t.set(m.name,h))}continue}if(/^REVOKE\b/i.test(c)){let p=nf(c);if(!p)continue;let m=p.tables==="all_in_public"?[...t.keys()]:p.tables,h=p.roles.includes("anon"),g=p.roles.includes("authenticated");if(!h&&!g)continue;for(let y of m){let _=t.get(y);if(_&&(h&&(_.anonAddressed=!0),g))for(let w of p.writePrivs)_.authWritesRevoked.add(w)}continue}}}return t}function Wo(e){let t=[];for(let[n,r]of Bo(e)){let s=[];r.anonAddressed||s.push("anon"),cr.every(i=>r.authWritesRevoked.has(i))||s.push("authenticated_writes"),s.length>0&&t.push({table:n,createdIn:r.createdIn,missing:s})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function rf(e){let t=Wo(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Wo(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let s=e.baseFiles===null?null:n.get(r.table),a=s!=null&&r.missing.every(l=>s.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 sf(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function Vo(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(Is)||t.endsWith(Ko))}function wS(e,t){try{let n=mS(e,"utf8");return n.length>t?null:n}catch{return null}}function vS(e,t,n,r,s){let i=R(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(i===null)return s.push(`could not diff ${t} against ${r} ${Is}`),null;let a=new Set,c=[];for(let u of i.split(`
|
|
32
|
-
`).filter(Boolean)){let[p,...m]=u.split(" ");p.startsWith("A")?a.add(m[0]):p.startsWith("R")?(c.push(m[0]),a.add(m[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(m[0])}let l=[],d=new Set(c);for(let{ref:u,content:p}of n)!a.has(u.path)&&!d.has(u.path)&&l.push({name:u.name,version:u.version,content:p});for(let u of c){let p=gS.basename(u),m=Zt(p);if(m===null)continue;let h=R(e,["show",`${r}:${u}`]);if(h===null)return s.push(`could not read ${u} at ${r} ${Ko}`),null;l.push({name:p,version:m,content:h})}return l}function Rt(e,t={}){let n=t.maxFileBytes??bS,r=[],s=at(e,t.dirs);if(s.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let i=t.includeBaseline!==!1,a=null;if(i)if(t.baseRef)a=t.baseRef;else{let m=ld(e);a=m?`origin/${m}`:null,a===null&&r.push(`no default branch resolvable ${Is}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let m of s){let h=[];for(let _ of m.files){let w=wS(hS(e,_.path),n);if(w===null){r.push(`could not read ${_.path} \u2014 excluded from the fold`);continue}h.push({ref:_,content:w})}let g=h.map(({ref:_,content:w})=>({name:_.name,version:_.version,content:w})),y=a===null?null:vS(e,m.dir,h,a,r);c.push(...rf({dir:m.dir,files:g,baseFiles:y})),l.push({dir:m.dir,migrationCount:g.length,tableCount:Bo(g).size})}let d=l.reduce((m,h)=>m+h.migrationCount,0),u=sf(d,c.length),p={open:0,info:1};return c.sort((m,h)=>p[m.status]-p[h.status]||m.id.localeCompare(h.id)),{ok:u!=="no_opinion"&&!c.some(m=>m.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var cr,_S,bS,Is,Ko,Cs=b(()=>{"use strict";re();zn();o(tf,"stripSql");o(ge,"normalizeQualifiedIdent");o(Ue,"splitTopLevel");cr=["INSERT","UPDATE","DELETE"];o(yS,"parseDefaultAclTables");_S=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;o(nf,"parseTableRevoke");o(Bo,"foldTableAcl");o(Wo,"evaluateTableAcl");o(rf,"computeTableAclFindings");o(sf,"deriveTableAclVerdict");bS=5e6,Is="\u2014 findings reported ungraded (open)",Ko="\u2014 baseline degraded";o(Vo,"isTableAclGraded");o(wS,"safeRead");o(vS,"baseFilesFor");o(Rt,"checkTableAclLint")});import{readFileSync as kS}from"node:fs";import{join as zo}from"node:path";function Yo(e){return e.verdict!=="no_opinion"&&e.graded}function Jo(e){let t=new Set;for(let n of e.matchAll(SS))t.add(n[1]);return t}function Xo(e){return new Set([...e].map(t=>t.split("-")[0]))}function uf(e){return e.split(`
|
|
2
|
+
var Wc=Object.defineProperty;var o=(e,t)=>Wc(e,"name",{value:t,configurable:!0});var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var se=(e,t)=>{for(var n in t)Wc(e,n,{get:t[n],enumerable:!0})};function Kc(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,s=typeof n.method=="string"?n.method:void 0;if(s!==void 0){let i={kind:r!==void 0?"request":"notification",method:s,id:r};if(s==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(i.toolName=c)}}return i}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function Vt(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 Ai(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Ti(e,t,n,r,s,i){return{at:r,event:e,server:t,tool:n,convention_id:s,convention_version:i}}function Ri(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Ii=b(()=>{"use strict";o(Kc,"parseFrame");o(Vt,"denyResult");o(Ai,"toolEvent");o(Ti,"policyEvent");o(Ri,"shaEvent")});import{execFileSync as qc}from"node:child_process";function Yc(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=p_}function f_(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 s=[];for(let i of l_){let a=r[i];typeof a=="string"&&Vc.test(a)&&s.push({field:i,sha:a})}for(let[i,a]of d_){let c=r[i];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&Vc.test(l)&&s.push({field:`${i}.${a}`,sha:l})}return s}function m_(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,zc);for(let s=zc;s>=u_;s--){let i=r.slice(0,s),a=t(i);if(a!==null&&a.startsWith(i))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:s}}return{field:"",sha:e,verdict:"unknown"}}function zt(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 Jc(){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 Pr(e=process.cwd()){try{let n=qc("git",["rev-parse","--show-toplevel"],{cwd:e,env:Jc(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function h_(e){return t=>{try{let r=qc("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Jc(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function Mr(e,t){if(t===null)return[];let n=f_(e);if(n.length===0)return[];let r=h_(t),s=[];for(let{field:i,sha:a}of n){let c=m_(a,r);c.verdict!=="proven"&&s.push({...c,field:i})}return s}var l_,d_,Vc,u_,zc,p_,Ci=b(()=>{"use strict";l_=["commit_sha","base_sha","head_sha"],d_=[["diff_stats","head_sha"],["diff_stats","base_sha"]],Vc=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,u_=7,zc=12,p_=10;o(Yc,"isDenyGrade");o(f_,"extractShaArgs");o(m_,"classifySha");o(zt,"shaFindingText");o(Jc,"cleanGitEnv");o(Pr,"resolveRepoRootForSha");o(h_,"gitShaResolver");o(Mr,"inspectLineForShas")});var Xc=b(()=>{"use strict"});function Zc(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
|
|
3
|
+
`).slice(0,1e3)}var Qc=b(()=>{"use strict";o(Zc,"nodeEmbedText")});var Ni,Oi=b(()=>{"use strict";Ni=["function","method","class","interface","enum","type_alias"]});function el(e,t){let n=Math.min(e.length,t.length),r=0,s=0,i=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,s+=c*c,i+=l*l}return s===0||i===0?0:r/(Math.sqrt(s)*Math.sqrt(i))}var tl=b(()=>{"use strict";o(el,"cosineSimilarity")});function $r(e){return`${e}#<module>`}function Lr(e,t,n){return`${e}#${t}:${n}`}var Bn=b(()=>{"use strict";o($r,"moduleKey");o(Lr,"symbolKey")});import{posix as Di}from"node:path";function nl(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!g_.has(r.kind))continue;let s=t.get(r.name);s?s.push(r.nodeKey):t.set(r.name,[r.nodeKey])}return{nameToKeys:t,files:n}}function rl(e,t){let n=new Set,r=[],s=new Set,i=o((a,c,l)=>{if(a===c)return;let d=`${a}\0${c}\0${l}`;n.has(d)||(n.add(d),r.push({srcKey:a,dstKey:c,kind:l}),s.add(a))},"push");for(let a of e.edges)i(a.srcKey,a.dstKey,a.kind);for(let a of e.nodes)s.add(a.nodeKey);for(let a of e.refs){let c=t.nameToKeys.get(a.targetName);!c||c.length!==1||i(a.fromKey,c[0],a.kind)}for(let a of e.imports){let c=y_(e.filePath,a.specifier,t.files);c&&i(a.fromModuleKey,$r(c),"imports")}return{filePath:e.filePath,srcKeys:[...s],edges:r}}function y_(e,t,n){if(!t.startsWith("."))return null;let r=Di.normalize(Di.join(Di.dirname(e),t)),s=[],i=Fr.some(c=>r.endsWith(c));i&&s.push(r);let a=/\.(js|jsx|mjs|cjs)$/.exec(r);if(a){let c=r.slice(0,-a[0].length);for(let l of Fr)s.push(c+l)}if(!i){for(let c of Fr)s.push(r+c);for(let c of Fr)s.push(`${r}/index${c}`)}for(let c of s)if(n.has(c))return c;return null}var g_,Fr,sl=b(()=>{"use strict";Bn();g_=new Set(["function","method","class","interface","enum","type_alias"]),Fr=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];o(nl,"buildResolutionIndex");o(rl,"resolveFileEdges");o(y_,"resolveImportTarget")});function jr(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 Pi(e){return e.toLowerCase().endsWith(".d.ts")}var Ur=b(()=>{"use strict";o(jr,"languageForPath");o(Pi,"isSkippablePath")});import{execFileSync as __}from"node:child_process";import{createHash as b_}from"node:crypto";import{readdirSync as w_,statSync as v_}from"node:fs";import{posix as cl,sep as il}from"node:path";function T(e,t){try{return __("git",[...k_,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function S_(e){return il==="/"?e:e.split(il).join("/")}function Hr(e){let t=[];for(let n of e){let r=S_(n).trim();if(!r||Pi(r))continue;let s=jr(r);s&&t.push({path:r,language:s})}return t}function ll(e){return Hr(e)}function dl(e){let t=qt(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Hr(t.split(`
|
|
4
|
+
`));let n=[];return ul(e,"",n),Hr(n)}function ul(e,t,n){let r;try{r=w_(cl.join(e,t),{withFileTypes:!0})}catch{return}for(let s of r){if(s.name.startsWith(".")&&s.name!=="."&&ol.has(s.name)||ol.has(s.name))continue;let i=t?`${t}/${s.name}`:s.name;s.isDirectory()?ul(e,i,n):s.isFile()&&n.push(i)}}function Mi(e,t){let r=T(e,["merge-base",t,"HEAD"])?.trim();return r&&r.length>0?r:t}function Gr(e,t={}){if(Kn(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Mi(e,t.since):"HEAD",s=["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");s.push("HEAD")}let i=qt(e,s);if(i===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of i.split(`
|
|
5
|
+
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=al((l.length>=3?l[l.length-1]:l[1]).trim());u&&(d==="A"||d==="C"?a.set(u,"added"):d==="R"?a.set(u,"renamed"):a.set(u,"modified"))}if(n){let c=qt(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
|
|
6
|
+
`)){if(l.length<4)continue;let d=l[0],u=l[1];if(d==="D"||u==="D")continue;let p=l.slice(3),m=p.indexOf(" -> ");m>=0&&(p=p.slice(m+4)),p=al(p),!(!p||a.has(p))&&(d==="?"||d==="A"||u==="A"?a.set(p,"added"):d==="R"?a.set(p,"renamed"):a.set(p,"modified"))}}return a}function al(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function pl(e,t={}){let n=Gr(e,t);return n===null?null:Hr(n.keys())}function fl(e,t){try{let n=v_(cl.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Wr(e){return b_("sha256").update(e).digest("hex")}function Kn(e){return qt(e,["rev-parse","HEAD"])?.trim()??null}function Br(e,t){return qt(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function ml(e){let t=qt(e,["status","--porcelain","-uall"]);return t!==null&&t.trim().length>0}var ol,k_,qt,ie=b(()=>{"use strict";Ur();ol=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),k_=["-c","diff.renames=true","-c","core.quotePath=false"];o(T,"runGit");qt=T;o(S_,"toPosix");o(Hr,"classify");o(ll,"classifyPaths");o(dl,"discoverSourceFiles");o(ul,"walk");o(Mi,"resolveDiffBase");o(Gr,"enumerateChangedPaths");o(al,"unquote");o(pl,"changedSourceFiles");o(fl,"statFile");o(Wr,"hashContent");o(Kn,"headCommit");o(Br,"resolveCommitSha");o(ml,"isWorktreeDirty")});function gl(e,t={}){if(T(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Mi(e,t.since):"HEAD",s=["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");s.push("HEAD")}let i=T(e,s);if(i===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(i,"utf8")>x_?c="none":R_(i,a,()=>{c="partial"}),n){let l=T(e,["status","--porcelain","-uall"])??"";for(let d of l.split(`
|
|
7
|
+
`)){if(d.length<4||d[0]!=="?")continue;let u=d.slice(3);u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),!(!u||a.has(u))&&a.set(u,{path:u,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:a,coverage:c}}function R_(e,t,n){let r=null,s=0,i=!1,a=!1,c=o(()=>{r&&t.set(r.path,r),r=null,s=0},"commit");for(let l of e.split(`
|
|
8
|
+
`)){if(l.startsWith("diff --git ")){c(),i=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){i=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:a?"added":i?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=T_.exec(l);if(d){if(s++,s>E_){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let u=Number(d[1]),p=d[2]===void 0?1:Number(d[2]);p>0?r.addedRanges.push({start:u,end:u+p-1}):r.deletionPoints.push(u);continue}l.startsWith("+")&&!l.startsWith("+++")&&!r.degraded&&r.addedLines.length<A_&&r.addedLines.push(l.slice(1))}c()}var x_,E_,A_,hl,T_,yl=b(()=>{"use strict";ie();x_=16*1024*1024,E_=500,A_=4e3,hl=256*1024,T_=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;o(gl,"changedHunks");o(R_,"parseUnifiedDiff")});function N_(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function bl(e){return e.split(I_).filter(t=>t.trim().length>0)}function wl(e){let[t,n,r,s,i]=e.replace(/\n+$/,"").split(C_);return!t||!s?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:s,subject:i??""}}function O_(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,s=t.get(r);s?s.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 kl(e,t,n={}){let r=N_(n.limit,20,100),s=n.includeOwnership!==!1,i=Math.max(r,vl),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,$i),l=[];for(let u of c){let p=T(e,["log","-n",String(i),_l,"--",u]),m=p===null?[]:bl(p).map(wl).filter(h=>h!==null);l.push({path:u,lastCommits:m.slice(0,r),ownership:s?{topAuthors:O_(m),commitsInWindow:m.length}:null})}let d=null;if(n.since){let u=Br(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],m=T(e,["log",...p,"-n",String(Kr+1),_l,"--name-only","--",...c]),h=[];if(m!==null)for(let g of bl(m)){let y=g.split(`
|
|
9
|
+
`),_=wl(y[0]??"");if(!_)continue;let w=y.slice(1).filter(k=>k.trim().length>0).length;h.push({sha:_.sha,dateIso:_.dateIso,authorName:_.authorName,subject:_.subject,filesTouched:w})}d={sinceInput:n.since,sinceResolved:u,commits:h.slice(0,Kr),truncated:h.length>Kr}}return{history:l,regression:d,ownershipWindowCommits:i,pathsTruncated:a.length>$i}}var I_,C_,vl,$i,Kr,_l,Li=b(()=>{"use strict";ie();I_="",C_="\0",vl=200,$i=50,Kr=100,_l="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";o(N_,"clamp");o(bl,"splitRecords");o(wl,"parseHistoryRecord");o(O_,"aggregateOwnership");o(kl,"readFileHistory")});import{execFileSync as D_}from"node:child_process";import{readdirSync as P_,statSync as Sl}from"node:fs";import{isAbsolute as M_,join as Fi,relative as $_,resolve as L_}from"node:path";function j_(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function U_(e,t){try{let n=D_("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 H_(e){let t;try{t=P_(e)}catch{return null}for(let n of t.filter(j_))try{let r=Sl(Fi(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function G_(e){try{return Sl(e).isDirectory()}catch{return!1}}function W_(e,t){let n=$_(e,t);return!n||n.startsWith("..")?t:n}function ji(e){let t=F_.filter(c=>G_(Fi(e,c))),n=U_(e,"core.hooksPath"),r=n?M_(n)?n:L_(e,n):Fi(e,".git","hooks"),s=W_(e,r),i=H_(r);if(i===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:s};let a=n?i===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:s}}function Ui(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 F_,Hi=b(()=>{"use strict";F_=[".githooks",".husky"];o(j_,"isRealHook");o(U_,"gitConfig");o(H_,"hasExecutableHook");o(G_,"isDir");o(W_,"displayPath");o(ji,"resolveHookState");o(Ui,"describeHookState")});import{posix as xl}from"node:path";function Yt(e){let t=B_.exec(e);return t?t[1]:null}function Ne(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function it(e,t){let n=T(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=o(i=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||i===c||i.startsWith(`${c}/`)}),"wanted"),s=new Map;for(let i of n.split("\0").filter(Boolean)){if(!r(i))continue;let a=xl.basename(i),c=Yt(a);if(c===null)continue;let l=xl.dirname(i),d=s.get(l)??[];d.push({path:i,name:a,version:c}),s.set(l,d)}return[...s.entries()].map(([i,a])=>({dir:i,files:a.sort((c,l)=>Ne(c.version,l.version))})).sort((i,a)=>i.dir.localeCompare(a.dir))}function El(e){let t=T(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(T(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var B_,Vn=b(()=>{"use strict";ie();B_=/^(\d+)_.+\.sql$/;o(Yt,"parseMigrationVersion");o(Ne,"compareVersions");o(it,"discoverSupabaseProjects");o(El,"resolveDefaultBranch")});import{execFileSync as K_}from"node:child_process";import{existsSync as Z,readFileSync as Ke,readdirSync as Vr,statSync as Wi}from"node:fs";import{posix as P}from"node:path";function Y_(e,t){let n=(()=>{let s=T(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return s?s.trim():null})(),r=P.dirname(e);for(let s=0;s<8&&r&&r!==P.dirname(r);s++){if(Z(P.join(r,".git"))){let i=(()=>{let c=T(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&i!=null&&Ki(n,i))){let c=J_(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=P.dirname(r)}return null}function J_(e,t){let n=[];for(let r of z_){let s;try{s=Vr(P.join(e,r),{withFileTypes:!0}).filter(i=>i.isFile()).map(i=>i.name)}catch{continue}for(let i of s){let a=`${r}/${i}`,c=P.join(e,a),l=P.join(t,a);try{let d=Wi(c),u=Wi(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>q_)continue;Ke(c).equals(Ke(l))||n.push(a)}catch{continue}}}return n.sort()}function Ol(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let c=e.upstream.split("/").slice(1).join("/");c&&c!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,s=e.ahead??0;r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${s>0?` (and ${s} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let i=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(i){let c=e.ahead??0;t.push({id:"worktree.commit-on-shared-base",status:"open",scope:"worktree",title:"Commit on the shared base tree",detail:`${c} commit(s) sit on the shared '${e.defaultBranch}' checkout and not on ${e.upstream??`origin/${e.defaultBranch}`} \u2014 in a workflow that reaches the base branch only through a pull request, a commit here is one that landed in the wrong place. A branch switch in a tree other sessions share can be undone by one of them between the switch and the commit, and nothing reports it.`,hint:`Move the commit onto its branch, then reset the base tree: git branch -f <branch> HEAD && git reset --hard ${e.upstream??`origin/${e.defaultBranch}`} (check for uncommitted work first). Do the work in its own worktree.`})}if(!i&&e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let c=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${c} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let c=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${c.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${Vi}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let c=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${c.map(l=>l.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:c.map(l=>`${l.install} (in ${P.dirname(l.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:c,diverging:l}=e.toolCopyDrift,d=l.slice(0,3).join(", "),u=l.length>3?` (+${l.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${c} ships ${d}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${l[0]}\` from this repo root), not via a path into ${c}.`})}if(e.stalePackageBuilds.length>0){let c=e.stalePackageBuilds,l=o(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),d=c.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".`:c.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:`${c.map(l).join(", ")}: src/ is newer than the built ${[...new Set(c.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${d}`,hint:`Rebuild: pnpm --filter ./${c[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let a=X_(e.hooks);return a&&t.push(a),Z_(t)}function X_(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:Ui(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 Z_(e){return[...e].sort((t,n)=>Al[t.status]-Al[n.status]||t.id.localeCompare(n.id))}function Dl(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function Oe(e){let t=e?.trim();return t||null}function Q_(e){let t=Oe(T(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(T(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function eb(e){let t=Oe(T(e,["rev-parse","--git-dir"]));if(!t)return null;let n=P.isAbsolute(t)?t:P.join(e,t);return Z(P.join(n,"rebase-merge"))||Z(P.join(n,"rebase-apply"))?"rebase":Z(P.join(n,"MERGE_HEAD"))?"merge":Z(P.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function tb(e){let t=[],n=null,r=o(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let s of e.split(`
|
|
10
|
+
`))if(s.startsWith("worktree "))r(),n={path:s.slice(9).trim(),detached:!1};else if(n)s.startsWith("branch ")?n.branch=s.slice(7).trim().replace(/^refs\/heads\//,""):s.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function nb(e){let t=P.join(e,Vi);if(!Z(t))return[];try{return Ke(t,"utf8").split(`
|
|
11
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function rb(e){try{return it(e).map(t=>P.join(P.dirname(t.dir),"config.toml"))}catch{return[]}}function sb(e){let t=T(e,["ls-files","-z","--",...V_]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let s=Nl[P.basename(r)];if(s===void 0)continue;let i=P.dirname(r);if(!ib(e,i))continue;let a=i==="."?"node_modules":P.join(i,"node_modules");n.has(a)||n.set(a,{dir:a,install:s})}return[...n.values()]}function ib(e,t){return t==="."?!0:Bi(e,t)}function Bi(e,t){if(Z(P.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(Ke(P.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Pl(e,t={}){if(Oe(T(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=Oe(T(e,["rev-parse","--abbrev-ref","HEAD"])),s=r==="HEAD",i=s?null:r,a=Q_(e),c=Oe(T(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let j=Oe(T(e,["rev-parse","HEAD"])),K=Oe(T(e,["rev-parse","@{u}"]));l=j!=null&&K!=null?j===K:null,d=T(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,p=null;if(a){let j=Oe(T(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(j){let[K,L]=j.split(/\s+/).map(W=>Number.parseInt(W,10));Number.isFinite(K)&&(p=K),Number.isFinite(L)&&(u=L)}}let h=(T(e,["status","--porcelain"])??"").split(`
|
|
12
|
+
`).filter(j=>j.trim().length>0).length,g=eb(e),y=Oe(T(e,["rev-parse","--show-toplevel"]))??e,_=tb(T(e,["worktree","list","--porcelain"])??""),w=_[0]?.path??null,k=w!=null&&Ki(w,y),x=Math.max(0,_.length-1),S=null;if(w&&!Ki(w,y)){let j=o(L=>Z(P.join(w,L))&&!Z(P.join(y,L)),"here"),K=[...Cl,...rb(y),...nb(y),...t.probePaths??[]];S={mainWorktreePath:w,currentWorktreePath:y,missing:[...new Set(K.filter(j))],missingDeps:sb(y).filter(L=>j(L.dir))}}let I=Y_(y,e),$=t.includeRelease===!1?null:pb(e,i),U=[];return a&&(U=(T(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
|
|
13
|
+
`).map(K=>K.trim()).filter(K=>K.length>0)),{isRepo:!0,branch:i,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:p,uncommitted:h,detachedHead:s,inProgressOp:g,isSharedMainTree:k,otherWorktrees:x,worktreeParity:S,toolCopyDrift:I,stalePackageBuilds:Ml(y),release:$,unmergedMigrations:U,hooks:ji(e)}}function Ki(e,t){let n=o(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function cb(e){let t=new Set;Bi(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<Rl;){let s=n.pop();if(s===void 0)break;if(s.depth>=ab)continue;let i;try{i=Vr(P.join(e,s.rel),{withFileTypes:!0})}catch{continue}for(let a of i){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=s.rel==="."?a.name:P.join(s.rel,a.name);if(r+=1,r>=Rl)break;Bi(e,c)&&t.add(c),n.push({rel:c,depth:s.depth+1})}}return[...t].sort()}function lb(e){let t=[];try{let n=P.join(e,"pnpm-workspace.yaml");if(Z(n)){let r=!1;for(let s of Ke(n,"utf8").split(`
|
|
14
|
+
`)){let i=s.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(i)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(i);a?t.push(a[1]):i.trim().length>0&&!/^\s/.test(i)&&(r=!1)}}}else{let r=P.join(e,"package.json");if(Z(r)){let s=JSON.parse(Ke(r,"utf8")),i=Array.isArray(s.workspaces)?s.workspaces:s.workspaces?.packages;Array.isArray(i)&&t.push(...i.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function db(e){let t=[];for(let n of cb(e)){let r=n==="."?e:P.join(e,n),s=o(i=>n==="."?i:P.join(n,i),"prefix");for(let i of lb(r)){if(t.length>=Gi)break;if(!(i.startsWith("!")||i.includes("**")))try{if(i.endsWith("/*")){let a=i.slice(0,-2),c=P.join(r,a);if(!Z(c))continue;for(let l of Vr(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(s(P.join(a,l.name))),t.length>=Gi)break}else i.includes("*")||t.push(s(i))}catch{}}}return t.slice(0,Gi)}function Il(e){let t=null,n=0,r=[e];for(;r.length>0&&n<Tl;){let s=r.pop();if(s===void 0)break;let i;try{i=Vr(s,{withFileTypes:!0})}catch{continue}for(let a of i){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=P.join(s,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=Wi(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=Tl)break}}}return t}function ub(e,t){let n=new Set;for(let r of t)try{let s=P.join(e,r,"package.json");if(!Z(s))continue;let i=JSON.parse(Ke(s,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=i[a];if(!(c===null||typeof c!="object"))for(let[l,d]of Object.entries(c))typeof d=="string"&&d.startsWith("workspace:")&&n.add(l)}}catch{}return n}function Ml(e){let t=[],n=db(e),r=ub(e,n);for(let s of n)try{let i=P.join(e,s,"package.json");if(!Z(i))continue;let a=JSON.parse(Ke(i,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=o(w=>{if(typeof w!="string")return null;let k=w.replace(/^\.\//,"").split("/")[0];return k==="build"||k==="dist"?k:null},"builtSeg"),l=c(a.types??a.typings),d=c(a.main),u=l??d;if(u===null)continue;let p=l!==null&&d!==null?"both":l!==null?"types":"runtime",m=P.join(e,s,"src"),h=P.join(e,s,u);if(!Z(m)||!Z(h))continue;let g=Il(m),y=Il(h);if(g===null||y===null)continue;let _=g-y;_>ob&&t.push({packageDir:s,buildDir:u,srcNewerByMs:Math.round(_),impact:p})}catch{}return t.sort((s,i)=>s.packageDir.localeCompare(i.packageDir))}function pb(e,t){if(!t)return null;let n=fb(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 s=r.filter(i=>i.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:s,allRed:s===r.length&&r.length>0}}function fb(e,t){try{return K_("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function zn(e,t={}){let n=await Pl(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=Ol(n),s=Dl(r);return{ok:s,verdict:s?"clean":"diverged",reason:null,findings:r,facts:n}}var Cl,Vi,Nl,V_,z_,q_,Al,ob,Gi,Tl,ab,Rl,zi=b(()=>{"use strict";Hi();ie();Vn();Cl=["supabase/config.toml","supabase/.temp",".env"],Vi=".maind/worktree-requirements",Nl={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},V_=Object.keys(Nl).flatMap(e=>[e,"*/"+e]),z_=["scripts"],q_=512*1024;o(Y_,"gatherToolCopyDrift");o(J_,"compareToolDirs");o(Ol,"computeDivergence");o(X_,"computeHookFinding");Al={open:0,warn:1,info:2,passed:3};o(Z_,"sortFindings");o(Dl,"isHealthy");o(Oe,"trimOrNull");o(Q_,"resolveDefaultBranch");o(eb,"detectInProgressOp");o(tb,"parseWorktrees");o(nb,"readWorktreeRequirements");o(rb,"discoverSupabaseConfigProbes");o(sb,"discoverDependencyDirs");o(ib,"isWorkspaceRoot");o(Bi,"hasWorkspaceMarkers");o(Pl,"gatherRepoHealthFacts");o(Ki,"samePath");ob=2e3,Gi=64,Tl=4e3,ab=3,Rl=400;o(cb,"findWorkspaceRoots");o(lb,"workspacePatternsAt");o(db,"listWorkspacePackageDirs");o(Il,"newestMtimeUnder");o(ub,"consumedWorkspaceNames");o(Ml,"gatherStalePackageBuilds");o(pb,"gatherReleaseFact");o(fb,"runGh");o(zn,"checkDivergence")});import{existsSync as qi,readdirSync as $l}from"node:fs";import{posix as be}from"node:path";function Ji(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Yi)}function Fl(e,t={}){let n=t.minFiles??Xi;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Ll)}function Xt(e){return`${e.dir}#${e.prefix}`}function qn(e){let t=mb.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function jl(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let s of e.namespaces){let i=Xt(s),a=e.sightingsByNamespace.get(i);if(!a)continue;let c=new Set(a.keys());for(let[l,d]of a){let u=[...new Set(d.map(g=>g.path))];if(u.length<2)continue;let p=u.find(g=>n.has(g)),m=u.filter(g=>g!==p),h=`${s.prefix}${l}`;t.push(p?{id:`number.collision:${i}#${l}`,status:"open",namespace:s,number:l,title:`${h} is already taken`,detail:`This branch adds ${p}, but ${h} already exists as ${m.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${h} stop being unambiguous.`,ownPath:p,sightings:d.filter(g=>g.path!==p),suggestion:`${s.prefix}${Zi(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:${i}#${l}`,status:"info",namespace:s,number:l,title:`${h} is used more than once (pre-existing)`,detail:`${h} is carried by ${u.length} files: ${u.join(", ")}.`,sightings:d,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((s,i)=>r[s.status]-r[i.status]||s.id.localeCompare(i.id))}function Ul(e){return!e.some(t=>t.status==="open")}function Zi(e,t){let n=0;for(let r of e){let s=Number(r);Number.isFinite(s)&&(n=Math.max(n,s))}return String(n+1).padStart(t.length,"0")}function Qi(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Hl(e,t){let n=Qi(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},s=qn(be.basename(n));if(!s)return r;let i=`${be.dirname(n)}#${s.prefix}`,a=e.namespaces.find(u=>Xt(u)===i)??null;if(!a)return{...r,number:s.number};let c=e.sightingsByNamespace.get(i)??new Map,l=new Set,d=[];for(let u of c.get(s.number)??[])u.path===n||l.has(u.path)||(l.add(u.path),d.push(u));return{path:n,namespace:a,number:s.number,taken:d.length>0,sightings:d,suggestion:Zi(c.keys(),s.number)}}function zr(e){let t=e?.trim();return t||null}function Jt(e){return e?e.split(`
|
|
15
|
+
`).filter(Boolean):[]}function hb(e){let t=zr(T(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(T(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Gl(e,t={}){let n=t.minFiles??Xi,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let s=T(e,r);if(s===null)return[];let i=new Map;for(let a of s.split("\0").filter(Boolean)){let c=be.dirname(a),l=qn(be.basename(a));if(!l)continue;let d=`${c}#${l.prefix}`,u=i.get(d);u?u.numbers.push(l.number):i.set(d,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...i.values()].filter(a=>Fl(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)=>Xt(a).localeCompare(Xt(c)))}async function eo(e,t={}){let n=[];if(zr(T(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 s=Gl(e,t),i=new Map(s.map(g=>[Xt(g),g])),a=[...new Set(s.map(g=>g.dir))],c=new Map,l=o((g,y,_)=>{let w=be.dirname(g),k=qn(be.basename(g));if(!k)return;let x=`${w}#${k.prefix}`;if(!i.has(x))return;let S=c.get(x)??new Map,I=S.get(k.number)??[];I.push({kind:y,where:_,path:g}),S.set(k.number,I),c.set(x,S)},"record"),d=o((g,y,_)=>{if(a.length===0)return;let w=T(e,["ls-tree","-r","--name-only",g,"--",...a]);if(w===null){n.push(`could not read ${_}`);return}for(let k of Jt(w))l(k,y,_)},"scanTree");for(let g of a){let y=be.join(e,g);if(qi(y))try{for(let _ of $l(y))l(`${g}/${_}`,"self","this worktree")}catch{n.push(`could not read ${g}`)}}let u=hb(e),p=t.baseRef??(u?`origin/${u}`:null);p?d(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");let m=zr(T(e,["rev-parse","--abbrev-ref","HEAD"]));for(let g of Jt(T(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))g!==m&&d(g,"branch",`Branch ${g}`);if(t.includeWorktrees!==!1){let g=zr(T(e,["rev-parse","--show-toplevel"]));for(let y of Jt(T(e,["worktree","list","--porcelain"]))){if(!y.startsWith("worktree "))continue;let _=y.slice(9).trim();if(!(!_||_===g||!qi(_)))for(let w of a){let k=be.join(_,w);if(qi(k))try{for(let x of $l(k))l(`${w}/${x}`,"worktree",`Worktree ${_}`)}catch{n.push(`could not read ${w} in ${_}`)}}}}let h=[];if(p&&a.length>0){let g=T(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);g===null?n.push(Yi):h=Jt(g);let y=T(e,["ls-files","--others","--exclude-standard","--",...a]);y!==null&&(h=[...h,...Jt(y)]);let _=T(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);_!==null&&(h=[...h,...Jt(_)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:s,sightingsByNamespace:c,addedPaths:h,skipped:n}}async function ot(e,t={}){let n=await eo(e,t),r=jl(n);return{ok:Ul(r),findings:r,facts:n}}async function at(e,t,n={}){let r=Qi(t);if(!qn(be.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let s=await eo(e,{...n,dirs:n.dirs??[be.dirname(r)]});return Hl(s,r)}var Yi,mb,Xi,Ll,Yn=b(()=>{"use strict";ie();Yi="could not diff against the base ref \u2014 everything reported as info";o(Ji,"isNumberCollisionsGraded");mb=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Xi=3,Ll=.8;o(Fl,"isCounterNamespace");o(Xt,"namespaceKey");o(qn,"parseNumbered");o(jl,"computeNumberCollisions");o(Ul,"isCollisionFree");o(Zi,"suggestNextNumber");o(Qi,"normaliseRepoPath");o(Hl,"checkProposedNumber");o(zr,"trimOrNull");o(Jt,"lines");o(hb,"resolveDefaultBranch");o(Gl,"detectNamespaces");o(eo,"gatherNumberCollisionFacts");o(ot,"checkNumberCollisions");o(at,"checkNumberForPath")});import{execFileSync as gb}from"node:child_process";import{createHash as yb}from"node:crypto";function to(e){return yb("sha256").update(e).digest("hex")}function _b(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 bb(e){let t=_b(e);return t?to(t):null}function vb(e){return typeof e=="string"&&wb.test(e)}function Wl(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(vb(t))return t;let n;try{n=gb("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?bb(n):null}var wb,no=b(()=>{"use strict";o(to,"sha256Hex");o(_b,"normalizeRemoteUrl");o(bb,"projectKeyFromRemote");wb=/^[a-f0-9]{64}$/;o(vb,"isProjectKey");o(Wl,"computeProjectKey")});function ao(e){return`spec.${e}`}function Zt(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 kb(e,t){let n=Array.from(e),r=Array.from(t),s=Math.min(n.length,r.length);for(let i=0;i<s;i++){let a=(n[i].codePointAt(0)??0)-(r[i].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function Bl(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(kb)}function Jn(e){return to(JSON.stringify(Bl(e)))}var ro,so,io,oo,co=b(()=>{"use strict";no();ro={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"]},det_changelog_duplicates:{version:"1.0.0",rules:["changelog.duplicate_heading"]},det_workflow_yaml:{version:"1.0.0",rules:["workflow.unparsable_yaml"]},det_release_claims:{version:"1.0.0",rules:["release.phantom","release.unpublished"]},det_agent_doc_prose:{version:"1.0.0",rules:["agentdoc.added_prose"]}},so="number.collision",io="theme.dead_class",oo="acl.missing_revoke";o(ao,"specDriftRuleId");o(Zt,"gradeEngineStatus");o(kb,"codePointCompare");o(Bl,"normalizeEvidenceForHash");o(Jn,"hashDetectorEvidence")});import{existsSync as Sb,readFileSync as Kl}from"node:fs";import{posix as xb}from"node:path";function Jr(e,t){let n=e[t],r=t+1;for(;r<e.length;){let s=e[r];if(s==="\\"){r+=2;continue}if(s===n)return r+1;r++}return e.length}function Xr(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
|
|
16
|
+
`,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 Xn(e){return e==='"'||e==="'"||e==="`"}function Zr(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function qr(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,s=t;for(;s<e.length;){let i=e[s];if(Xn(i)){s=Jr(e,s);continue}if(Zr(e,s)){s=Xr(e,s);continue}if(i==="["||i==="{")r++;else if((i==="]"||i==="}")&&(r--,r===0))return e.slice(t,s+1);s++}return null}function Eb(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Zr(e,t)){t=Xr(e,t);continue}break}return e.slice(t)}function Qt(e){let t=[],n=0,r=0,s=0;for(;s<e.length;){let i=e[s];if(Xn(i)){s=Jr(e,s);continue}if(Zr(e,s)){s=Xr(e,s);continue}i==="["||i==="{"||i==="("?n++:i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(t.push(e.slice(r,s)),r=s+1),s++}return t.push(e.slice(r)),t.map(i=>Eb(i).trim()).filter(i=>i.length>0)}function Yl(e){let t=Jr(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,s)=>s==="n"?`
|
|
17
|
+
`:s==="r"?"\r":s==="t"?" ":s)}function Ab(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uo(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${Ab(t)}\b`,"m").exec(e);if(!r)return null;let s=r.index+r[0].length,i=!1;for(;s<e.length;){let a=e[s];if(Xn(a)){s=Jr(e,s);continue}if(Zr(e,s)){s=Xr(e,s);continue}if(!i){if(a==="="&&e[s+1]!=="="&&!"=!<>".includes(e[s-1]??" "))i=!0;else if(a===";")return null;s++;continue}if(a==="[")return qr(e,s);if(a===";")return null;s++}return null}function po(e){let t={};if(!e.startsWith("{"))return t;for(let n of Qt(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let s=r[2]??r[3],i=r[4].trim();Xn(i[0]??"")&&(t[s]=Yl(i))}return t}function Tb(e,t){if(!e.startsWith("{"))return null;for(let n of Qt(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 Jl(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Xl(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Zl(e,t){let n=uo(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Xl(),s=[],i=0;for(let a of Qt(n.slice(1,-1))){if(!a.startsWith("{")){i++;continue}let c=po(a),l=c[t.key_field];if(!l){i++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");s.push({key:l,fields:Jl(c,t.fields),orderPath:d,ordinal:r(d)})}return s.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:i}:{records:s,error:null,dropped:i}}function Ql(e,t){let n=uo(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=Xl(),s=[],i=0,a=o((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let m of Qt(c.slice(1,-1))){let h={...d},g=null;if(u.shape==="object"){if(!m.startsWith("{")){i++;continue}let y=po(m);for(let[_,w]of Object.entries(u.fields??{}))h[_]=y[String(w)]??"";if(!p&&typeof u.children=="string"){let _=Tb(m,u.children);g=_&&_.startsWith("[")?qr(_,0):null}}else{if(!m.startsWith("[")){i++;continue}let y=Qt(m.slice(1,-1));for(let[_,w]of Object.entries(u.fields??{})){let k=y[Number(w)];h[_]=k!==void 0&&Xn(k[0]??"")?Yl(k):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?qr(_,0):null}}if(p){let y=h[t.key_field];if(!y){i++;continue}let _=(t.partition_by??[]).map(w=>h[w]??"");s.push({key:y,fields:Jl(h,t.fields),orderPath:_,ordinal:r(_)});continue}g!==null&&a(g,l+1,h)}},"walk");return a(n,0,{}),s.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:i}:{records:s,error:null,dropped:i}}function Vl(e,t){return t.extractor==="object-array"?Zl(e,t):Ql(e,t)}function ed(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(s=>n.has(s.replace("{key}",r).replace(/\/{2,}/g,"/")))}function td(e,t,n){return`spec.drift:${e}#${t}:${n}`}function Rb(e){return e.orderPath.join(" / ")||"(flat)"}function nd(e,t,n,r){let s=[],i=o((d,u,p,m,h,g)=>{s.push({id:td(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:m,detail:h,hint:g})},"push"),a=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=a.get(d.key);if(!u){i("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${Rb(d)}, position ${d.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let m=d.fields[p]??"",h=u.fields[p]??"";m!==h&&i("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${h||"\u2014"}", the specification says "${m||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),p=l.get(u);p?p.push(d):l.set(u,[d])}for(let[d,u]of l){let p=u.filter(y=>a.has(y.key)).map(y=>y.key),m=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),h=new Set(m),g=p.filter(y=>h.has(y));if(m.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";i("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${m.join(" \u2192 ")}
|
|
18
|
+
specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let d of n)c.has(d.key)||i("extra","warn",d.key,`${d.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let d of new Set([...a.keys(),...c.keys()])){if(ed(d,e.grounding,r))continue;let u=a.has(d);i("unrealized",u?"open":"warn",d,u?`${d} is referenced by the implementation but has no artefact`:`${d} is declared by the specification but not built yet`,u?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return s}function Ib(e,t,n){let r=[];for(let s of e.assertions??[]){let i=n.get(s.path);if(!i)continue;let a=i.indexOf(s.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(i.slice(a+s.prefix.length));if(!c)continue;let l=Number(c[1]),d=t[s.counts];l!==d&&r.push({id:`spec.drift:${e.id}#assertion:${s.path}`,contract:e.id,dimension:"assertion",status:"warn",key:s.path,title:`${s.path} states ${l} where the ${s.counts} side has ${d}`,detail:`Counted after "${s.prefix}". ${s.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function zl(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 rd(e,t={}){let n=o(u=>({ok:!1,verdict:"no_opinion",reason:u,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(u=>t.contracts.includes(u.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(u=>`"${u}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let s=o(u=>{let p=[],m=[];for(let h of r){let g=u.get(h.spec.path),y=u.get(h.impl.path);if(g==null||y==null){let x=g==null?h.spec.path:h.impl.path;p.push(zl(h.id,`Declared file could not be read: ${x}`)),m.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=Vl(g,h.spec),w=Vl(y,h.impl);if(_.error||w.error){p.push(zl(h.id,_.error??w.error??"unknown")),m.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let k=_.dropped>0||w.dropped>0;m.push({id:h.id,measured:!0,specRecords:_.records.length,implRecords:w.records.length,partial:k}),k&&p.push({id:`contract.partial:${h.id}`,contract:h.id,dimension:"contract",status:"warn",key:null,title:`Contract "${h.id}" was measured incompletely`,detail:`${_.dropped} specification and ${w.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(...nd(h,_.records,w.records,e.files)),p.push(...Ib(h,{spec:_.records.length,impl:w.records.length},u))}return{findings:p,contracts:m}},"runOnce"),i=s(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let u of s(e.baselineSources).findings)u.id.startsWith("contract.unreadable:")||a.add(u.id);let c=new Map;for(let u of r)for(let p of u.exceptions??[])c.set(td(u.id,p.dimension,p.key),p);let l=i.findings.map(u=>{let p=c.get(u.id);return p?{...u,status:"info",exceptionReason:p.reason}:a.has(u.id)?{...u,status:"info",detail:`${u.detail}
|
|
19
|
+
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>ql[u.status]-ql[p.status]||u.id.localeCompare(p.id));let d=l.some(u=>u.status==="open");return{ok:!d,verdict:d?"drifted":"aligned",reason:null,findings:l,contracts:i.contracts}}function lo(e){let t=e?.trim();return t||null}function Qr(e){let t;try{t=JSON.parse(e)}catch(a){return{manifest:null,error:`manifest is not valid JSON: ${a.message}`}}let n=o(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,"obj"),r=o(a=>typeof a=="string"?a:"","str"),s=n(t);if(!s||!Array.isArray(s.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let i=o(a=>({manifest:null,error:a}),"bad");for(let[a,c]of s.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${a+1}`;if(!l)return i(`${u}: not an object`);if(!d)return i(`${u}: \`id\` is missing`);if(!r(l.reason))return i(`${u}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let p of["spec","impl"]){let m=n(l[p]);if(!m)return i(`${u}: \`${p}\` is missing`);let h=r(m.extractor);if(!h)return i(`${u}: \`${p}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return i(`${u}: unknown \`${p}.extractor\` "${h}"`);if(!r(m.path)||!r(m.symbol)||!r(m.key_field))return i(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(m.levels))return i(`${u}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(l.exceptions)?l.exceptions:[]){let m=n(p);if(!m||!r(m.reason))return i(`${u}: exception for "${r(m?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:s,error:null}}function Cb(e){let t=lo(T(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(T(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Nb(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 sd(e,t={}){let n=o((g,y)=>xb.join(g,y),"join"),r=t.manifestPath??Yr,s=[],i={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:s};if(lo(T(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...i,manifestError:"not a git work tree"};let a=n(e,r);if(!Sb(a))return{...i,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}=Qr(Kl(a,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...i,isRepo:!0,manifestError:l};let d=new Map;for(let g of Nb(c))try{d.set(g,Kl(n(e,g),"utf8"))}catch{d.set(g,null),s.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=T(e,["ls-files","-z"]);if(p===null)s.push("could not list tracked files \u2014 grounding is skipped");else for(let g of p.split("\0"))g&&u.add(g);let m=null,h=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:Cb(e),y=t.baseRef??(g?`origin/${g}`:null);if(!y)s.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(m=lo(T(e,["merge-base",y,"HEAD"])),!m)s.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let _ of d.keys())h.set(_,T(e,["show",`${m}:${_}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:h,baseRef:m,files:u,skipped:s}}async function ct(e,t={}){let n=await sd(e,t);return{...rd(n,t),facts:n}}function fo(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var Yr,ql,Zn=b(()=>{"use strict";ie();Yr=".maind/spec-contracts.json";o(Jr,"endOfString");o(Xr,"skipComment");o(Xn,"isQuote");o(Zr,"isCommentStart");o(qr,"sliceBalanced");o(Eb,"stripLeadingTrivia");o(Qt,"splitTopLevel");o(Yl,"readStringLiteral");o(Ab,"escapeRe");o(uo,"findSymbolArray");o(po,"parseObjectFields");o(Tb,"objectFieldRaw");o(Jl,"pickFields");o(Xl,"makeOrdinals");o(Zl,"extractObjectArray");o(Ql,"extractNestedList");o(Vl,"extractRecords");o(ed,"isGrounded");o(td,"findingId");o(Rb,"partitionOf");o(nd,"compareContract");o(Ib,"checkAssertions");o(zl,"unreadable");ql={open:0,warn:1,info:2,passed:3};o(rd,"computeSpecDrift");o(lo,"trimOrNull");o(Qr,"parseManifest");o(Cb,"resolveDefaultBranch");o(Nb,"declaredPaths");o(sd,"gatherSpecDriftFacts");o(ct,"checkSpecDrift");o(fo,"isSpecDriftGraded")});var M,mo,A,we,Qn=b(()=>{(function(e){e.assertEqual=s=>{};function t(s){}o(t,"assertIs"),e.assertIs=t;function n(s){throw new Error}o(n,"assertNever"),e.assertNever=n,e.arrayToEnum=s=>{let i={};for(let a of s)i[a]=a;return i},e.getValidEnumValues=s=>{let i=e.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(let c of i)a[c]=s[c];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(i){return s[i]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},e.find=(s,i)=>{for(let a of s)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}o(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(M||(M={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(mo||(mo={}));A=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),we=o(e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?A.promise:typeof Map<"u"&&e instanceof Map?A.map:typeof Set<"u"&&e instanceof Set?A.set:typeof Date<"u"&&e instanceof Date?A.date:A.object;default:return A.unknown}},"getParsedType")});var v,Ob,oe,es=b(()=>{Qn();v=M.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ob=o(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),oe=class e extends Error{static{o(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(i){return i.message},r={_errors:[]},s=o(i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}},"processError");return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};oe.create=e=>new oe(e)});var Db,De,ho=b(()=>{es();Qn();Db=o((e,t)=>{let n;switch(e.code){case v.invalid_type:e.received===A.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case v.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:n=`Unrecognized key(s) in object: ${M.joinValues(e.keys,", ")}`;break;case v.invalid_union:n="Invalid input";break;case v.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case v.invalid_enum_value:n=`Invalid enum value. Expected ${M.joinValues(e.options)}, received '${e.received}'`;break;case v.invalid_arguments:n="Invalid function arguments";break;case v.invalid_return_type:n="Invalid function return type";break;case v.invalid_date:n="Invalid date";break;case v.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:M.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case v.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case v.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case v.custom:n="Invalid input";break;case v.invalid_intersection_types:n="Intersection results could not be merged";break;case v.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case v.not_finite:n="Number must be finite";break;default:n=t.defaultError,M.assertNever(e)}return{message:n}},"errorMap"),De=Db});function Pb(e){id=e}function en(){return id}var id,ts=b(()=>{ho();id=De;o(Pb,"setErrorMap");o(en,"getErrorMap")});function E(e,t){let n=en(),r=er({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===De?void 0:De].filter(s=>!!s)});e.common.issues.push(r)}var er,Mb,V,C,lt,Q,ns,rs,Ve,tn,go=b(()=>{ts();ho();er=o(e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:t,defaultError:c}).message;return{...s,path:i,message:c}},"makeIssue"),Mb=[];o(E,"addIssueToContext");V=class e{static{o(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return C;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let i=await s.key,a=await s.value;r.push({key:i,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return C;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}},C=Object.freeze({status:"aborted"}),lt=o(e=>({status:"dirty",value:e}),"DIRTY"),Q=o(e=>({status:"valid",value:e}),"OK"),ns=o(e=>e.status==="aborted","isAborted"),rs=o(e=>e.status==="dirty","isDirty"),Ve=o(e=>e.status==="valid","isValid"),tn=o(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var od=b(()=>{});var R,ad=b(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(R||(R={}))});function O(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:o((a,c)=>{let{message:l}=e;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:s}}function ud(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Zb(e){return new RegExp(`^${ud(e)}$`)}function pd(e){let t=`${dd}T${ud(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Qb(e,t){return!!((t==="v4"||!t)&&Kb.test(e)||(t==="v6"||!t)&&zb.test(e))}function ew(e,t){if(!Hb.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function tw(e,t){return!!((t==="v4"||!t)&&Vb.test(e)||(t==="v6"||!t)&&qb.test(e))}function nw(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(e.toFixed(s).replace(".","")),a=Number.parseInt(t.toFixed(s).replace(".",""));return i%a/10**s}function nn(e){if(e instanceof ae){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=de.create(nn(r))}return new ae({...e._def,shape:o(()=>t,"shape")})}else return e instanceof $e?new $e({...e._def,type:nn(e.element)}):e instanceof de?de.create(nn(e.unwrap())):e instanceof ke?ke.create(nn(e.unwrap())):e instanceof ve?ve.create(e.items.map(t=>nn(t))):e}function _o(e,t){let n=we(e),r=we(t);if(e===t)return{valid:!0,data:e};if(n===A.object&&r===A.object){let s=M.objectKeys(t),i=M.objectKeys(e).filter(c=>s.indexOf(c)!==-1),a={...e,...t};for(let c of i){let l=_o(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===A.array&&r===A.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let i=0;i<e.length;i++){let a=e[i],c=t[i],l=_o(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===A.date&&r===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function fd(e,t){return new wt({values:e,typeName:N.ZodEnum,...O(t)})}function ld(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function md(e,t={},n){return e?qe.create().superRefine((r,s)=>{let i=e(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=ld(t,r),l=c.fatal??n??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=ld(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}}):qe.create()}var ue,cd,D,$b,Lb,Fb,jb,Ub,Hb,Gb,Wb,Bb,yo,Kb,Vb,zb,qb,Yb,Jb,dd,Xb,ze,dt,ut,pt,ft,rn,mt,ht,qe,Me,he,sn,$e,ae,gt,Pe,ss,yt,ve,is,on,an,os,_t,bt,wt,vt,Ye,pe,de,ke,kt,St,cn,rw,tr,nr,xt,sw,N,iw,hd,gd,ow,aw,yd,cw,lw,dw,uw,pw,fw,mw,hw,gw,yw,_w,bw,ww,vw,kw,Sw,xw,Ew,Aw,Tw,Rw,Iw,Cw,Nw,Ow,Dw,Pw,Mw,$w,Lw,Fw,jw,Uw,Hw,_d=b(()=>{es();ts();ad();go();Qn();ue=class{static{o(this,"ParseInputLazyPath")}constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},cd=o((e,t)=>{if(Ve(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new oe(e.common.issues);return this._error=n,this._error}}},"handleResult");o(O,"processCreateParams");D=class{static{o(this,"ZodType")}get description(){return this._def.description}_getType(t){return we(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:we(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new V,ctx:{common:t.parent.common,data:t.data,parsedType:we(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(tn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:we(t)},s=this._parseSync({data:t,path:r.path,parent:r});return cd(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:we(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Ve(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>Ve(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:we(t)},s=this._parse({data:t,path:r.path,parent:r}),i=await(tn(s)?s:Promise.resolve(s));return cd(r,i)}refine(t,n){let r=o(s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n,"getIssueProperties");return this._refinement((s,i)=>{let a=t(s),c=o(()=>i.addIssue({code:v.custom,...r(s)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new pe({schema:this,typeName:N.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:o(n=>this["~validate"](n),"validate")}}optional(){return de.create(this,this._def)}nullable(){return ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $e.create(this)}promise(){return Ye.create(this,this._def)}or(t){return gt.create([this,t],this._def)}and(t){return yt.create(this,t,this._def)}transform(t){return new pe({...O(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new kt({...O(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new tr({typeName:N.ZodBranded,type:this,...O(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new St({...O(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return nr.create(this,t)}readonly(){return xt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},$b=/^c[^\s-]{8,}$/i,Lb=/^[0-9a-z]+$/,Fb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jb=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ub=/^[a-z0-9_-]{21}$/i,Hb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Gb=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Wb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Bb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Kb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Vb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,zb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,qb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Yb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Jb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dd="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Xb=new RegExp(`^${dd}$`);o(ud,"timeRegexSource");o(Zb,"timeRegex");o(pd,"datetimeRegex");o(Qb,"isValidIP");o(ew,"isValidJWT");o(tw,"isValidCidr");ze=class e extends D{static{o(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let i=this._getOrReturnCtx(t);return E(i,{code:v.invalid_type,expected:A.string,received:i.parsedType}),C}let r=new V,s;for(let i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:v.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:v.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=t.data.length>i.value,c=t.data.length<i.value;(a||c)&&(s=this._getOrReturnCtx(t,s),a?E(s,{code:v.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&E(s,{code:v.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Wb.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"email",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")yo||(yo=new RegExp(Bb,"u")),yo.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"emoji",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")jb.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"uuid",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Ub.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"nanoid",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")$b.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cuid",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Lb.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cuid2",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Fb.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"ulid",code:v.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),E(s,{validation:"url",code:v.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"regex",code:v.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?pd(i).test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Xb.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Zb(i).test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Gb.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"duration",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Qb(t.data,i.version)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"ip",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?ew(t.data,i.alg)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"jwt",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?tw(t.data,i.version)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cidr",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Yb.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"base64",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Jb.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"base64url",code:v.invalid_string,message:i.message}),r.dirty()):M.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:v.invalid_string,...R.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...R.errToObj(t)})}url(t){return this._addCheck({kind:"url",...R.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...R.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...R.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...R.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...R.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...R.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...R.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...R.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...R.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...R.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...R.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...R.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...R.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...R.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...R.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...R.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...R.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...R.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...R.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...R.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...R.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...R.errToObj(n)})}nonempty(t){return this.min(1,R.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};ze.create=e=>new ze({checks:[],typeName:N.ZodString,coerce:e?.coerce??!1,...O(e)});o(nw,"floatSafeRemainder");dt=class e extends D{static{o(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==A.number){let i=this._getOrReturnCtx(t);return E(i,{code:v.invalid_type,expected:A.number,received:i.parsedType}),C}let r,s=new V;for(let i of this._def.checks)i.kind==="int"?M.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:v.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?nw(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:v.not_finite,message:i.message}),s.dirty()):M.assertNever(i);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,R.toString(n))}gt(t,n){return this.setLimit("min",t,!1,R.toString(n))}lte(t,n){return this.setLimit("max",t,!0,R.toString(n))}lt(t,n){return this.setLimit("max",t,!1,R.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:R.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:R.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:R.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:R.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&M.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};dt.create=e=>new dt({checks:[],typeName:N.ZodNumber,coerce:e?.coerce||!1,...O(e)});ut=class e extends D{static{o(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==A.bigint)return this._getInvalidInput(t);let r,s=new V;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):M.assertNever(i);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return E(n,{code:v.invalid_type,expected:A.bigint,received:n.parsedType}),C}gte(t,n){return this.setLimit("min",t,!0,R.toString(n))}gt(t,n){return this.setLimit("min",t,!1,R.toString(n))}lte(t,n){return this.setLimit("max",t,!0,R.toString(n))}lt(t,n){return this.setLimit("max",t,!1,R.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:R.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:R.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:R.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};ut.create=e=>new ut({checks:[],typeName:N.ZodBigInt,coerce:e?.coerce??!1,...O(e)});pt=class extends D{static{o(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.boolean,received:r.parsedType}),C}return Q(t.data)}};pt.create=e=>new pt({typeName:N.ZodBoolean,coerce:e?.coerce||!1,...O(e)});ft=class e extends D{static{o(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let i=this._getOrReturnCtx(t);return E(i,{code:v.invalid_type,expected:A.date,received:i.parsedType}),C}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return E(i,{code:v.invalid_date}),C}let r=new V,s;for(let i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:v.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(s=this._getOrReturnCtx(t,s),E(s,{code:v.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):M.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:R.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:R.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};ft.create=e=>new ft({checks:[],coerce:e?.coerce||!1,typeName:N.ZodDate,...O(e)});rn=class extends D{static{o(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==A.symbol){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.symbol,received:r.parsedType}),C}return Q(t.data)}};rn.create=e=>new rn({typeName:N.ZodSymbol,...O(e)});mt=class extends D{static{o(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.undefined,received:r.parsedType}),C}return Q(t.data)}};mt.create=e=>new mt({typeName:N.ZodUndefined,...O(e)});ht=class extends D{static{o(this,"ZodNull")}_parse(t){if(this._getType(t)!==A.null){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.null,received:r.parsedType}),C}return Q(t.data)}};ht.create=e=>new ht({typeName:N.ZodNull,...O(e)});qe=class extends D{static{o(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return Q(t.data)}};qe.create=e=>new qe({typeName:N.ZodAny,...O(e)});Me=class extends D{static{o(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return Q(t.data)}};Me.create=e=>new Me({typeName:N.ZodUnknown,...O(e)});he=class extends D{static{o(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return E(n,{code:v.invalid_type,expected:A.never,received:n.parsedType}),C}};he.create=e=>new he({typeName:N.ZodNever,...O(e)});sn=class extends D{static{o(this,"ZodVoid")}_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.void,received:r.parsedType}),C}return Q(t.data)}};sn.create=e=>new sn({typeName:N.ZodVoid,...O(e)});$e=class e extends D{static{o(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==A.array)return E(n,{code:v.invalid_type,expected:A.array,received:n.parsedType}),C;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&(E(n,{code:a?v.too_big:v.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(E(n,{code:v.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(E(n,{code:v.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>s.type._parseAsync(new ue(n,a,n.path,c)))).then(a=>V.mergeArray(r,a));let i=[...n.data].map((a,c)=>s.type._parseSync(new ue(n,a,n.path,c)));return V.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:R.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:R.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:R.toString(n)}})}nonempty(t){return this.min(1,t)}};$e.create=(e,t)=>new $e({type:e,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...O(t)});o(nn,"deepPartialify");ae=class e extends D{static{o(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=M.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==A.object){let d=this._getOrReturnCtx(t);return E(d,{code:v.invalid_type,expected:A.object,received:d.parsedType}),C}let{status:r,ctx:s}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof he&&this._def.unknownKeys==="strip"))for(let d in s.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let u=i[d],p=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new ue(s,p,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof he){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(d==="strict")c.length>0&&(E(s,{code:v.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=s.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new ue(s,p,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let p=await u.key,m=await u.value;d.push({key:p,value:m,alwaysSet:u.alwaysSet})}return d}).then(d=>V.mergeObjectSync(r,d)):V.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return R.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:o((n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:R.errToObj(t).message??s}:{message:s}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:o(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:o(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:N.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of M.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:o(()=>n,"shape")})}omit(t){let n={};for(let r of M.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:o(()=>n,"shape")})}deepPartial(){return nn(this)}partial(t){let n={};for(let r of M.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:o(()=>n,"shape")})}required(t){let n={};for(let r of M.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof de;)i=i._def.innerType;n[r]=i}return new e({...this._def,shape:o(()=>n,"shape")})}keyof(){return fd(M.objectKeys(this.shape))}};ae.create=(e,t)=>new ae({shape:o(()=>e,"shape"),unknownKeys:"strip",catchall:he.create(),typeName:N.ZodObject,...O(t)});ae.strictCreate=(e,t)=>new ae({shape:o(()=>e,"shape"),unknownKeys:"strict",catchall:he.create(),typeName:N.ZodObject,...O(t)});ae.lazycreate=(e,t)=>new ae({shape:e,unknownKeys:"strip",catchall:he.create(),typeName:N.ZodObject,...O(t)});gt=class extends D{static{o(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new oe(c.ctx.common.issues));return E(n,{code:v.invalid_union,unionErrors:a}),C}if(o(s,"handleResults"),n.common.async)return Promise.all(r.map(async i=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i,a=[];for(let l of r){let d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(l=>new oe(l));return E(n,{code:v.invalid_union,unionErrors:c}),C}}get options(){return this._def.options}};gt.create=(e,t)=>new gt({options:e,typeName:N.ZodUnion,...O(t)});Pe=o(e=>e instanceof _t?Pe(e.schema):e instanceof pe?Pe(e.innerType()):e instanceof bt?[e.value]:e instanceof wt?e.options:e instanceof vt?M.objectValues(e.enum):e instanceof kt?Pe(e._def.innerType):e instanceof mt?[void 0]:e instanceof ht?[null]:e instanceof de?[void 0,...Pe(e.unwrap())]:e instanceof ke?[null,...Pe(e.unwrap())]:e instanceof tr||e instanceof xt?Pe(e.unwrap()):e instanceof St?Pe(e._def.innerType):[],"getDiscriminator"),ss=class e extends D{static{o(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return E(n,{code:v.invalid_type,expected:A.object,received:n.parsedType}),C;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(E(n,{code:v.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),C)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let i of n){let a=Pe(i.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of a){if(s.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);s.set(c,i)}}return new e({typeName:N.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...O(r)})}};o(_o,"mergeValues");yt=class extends D{static{o(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=o((i,a)=>{if(ns(i)||ns(a))return C;let c=_o(i.value,a.value);return c.valid?((rs(i)||rs(a))&&n.dirty(),{status:n.value,value:c.data}):(E(r,{code:v.invalid_intersection_types}),C)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};yt.create=(e,t,n)=>new yt({left:e,right:t,typeName:N.ZodIntersection,...O(n)});ve=class e extends D{static{o(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.array)return E(r,{code:v.invalid_type,expected:A.array,received:r.parsedType}),C;if(r.data.length<this._def.items.length)return E(r,{code:v.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),C;!this._def.rest&&r.data.length>this._def.items.length&&(E(r,{code:v.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new ue(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>V.mergeArray(n,a)):V.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ve.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ve({items:e,typeName:N.ZodTuple,rest:null,...O(t)})};is=class e extends D{static{o(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.object)return E(r,{code:v.invalid_type,expected:A.object,received:r.parsedType}),C;let s=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)s.push({key:i._parse(new ue(r,c,r.path,c)),value:a._parse(new ue(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?V.mergeObjectAsync(n,s):V.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof D?new e({keyType:t,valueType:n,typeName:N.ZodRecord,...O(r)}):new e({keyType:ze.create(),valueType:t,typeName:N.ZodRecord,...O(n)})}},on=class extends D{static{o(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.map)return E(r,{code:v.invalid_type,expected:A.map,received:r.parsedType}),C;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new ue(r,c,r.path,[d,"key"])),value:i._parse(new ue(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return C;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return C;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};on.create=(e,t,n)=>new on({valueType:t,keyType:e,typeName:N.ZodMap,...O(n)});an=class e extends D{static{o(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.set)return E(r,{code:v.invalid_type,expected:A.set,received:r.parsedType}),C;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(E(r,{code:v.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(E(r,{code:v.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function a(l){let d=new Set;for(let u of l){if(u.status==="aborted")return C;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}o(a,"finalizeSet");let c=[...r.data.values()].map((l,d)=>i._parse(new ue(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new e({...this._def,minSize:{value:t,message:R.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:R.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};an.create=(e,t)=>new an({valueType:e,minSize:null,maxSize:null,typeName:N.ZodSet,...O(t)});os=class e extends D{static{o(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.function)return E(n,{code:v.invalid_type,expected:A.function,received:n.parsedType}),C;function r(c,l){return er({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,en(),De].filter(d=>!!d),issueData:{code:v.invalid_arguments,argumentsError:l}})}o(r,"makeArgsIssue");function s(c,l){return er({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,en(),De].filter(d=>!!d),issueData:{code:v.invalid_return_type,returnTypeError:l}})}o(s,"makeReturnsIssue");let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Ye){let c=this;return Q(async function(...l){let d=new oe([]),u=await c._def.args.parseAsync(l,i).catch(h=>{throw d.addIssue(r(l,h)),d}),p=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(p,i).catch(h=>{throw d.addIssue(s(p,h)),d})})}else{let c=this;return Q(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new oe([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,i);if(!p.success)throw new oe([s(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ve.create(t).rest(Me.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||ve.create([]).rest(Me.create()),returns:n||Me.create(),typeName:N.ZodFunction,...O(r)})}},_t=class extends D{static{o(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};_t.create=(e,t)=>new _t({getter:e,typeName:N.ZodLazy,...O(t)});bt=class extends D{static{o(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return E(n,{received:n.data,code:v.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:t.data}}get value(){return this._def.value}};bt.create=(e,t)=>new bt({value:e,typeName:N.ZodLiteral,...O(t)});o(fd,"createZodEnum");wt=class e extends D{static{o(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return E(n,{expected:M.joinValues(r),received:n.parsedType,code:v.invalid_type}),C}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return E(n,{received:n.data,code:v.invalid_enum_value,options:r}),C}return Q(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};wt.create=fd;vt=class extends D{static{o(this,"ZodNativeEnum")}_parse(t){let n=M.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==A.string&&r.parsedType!==A.number){let s=M.objectValues(n);return E(r,{expected:M.joinValues(s),received:r.parsedType,code:v.invalid_type}),C}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=M.objectValues(n);return E(r,{received:r.data,code:v.invalid_enum_value,options:s}),C}return Q(t.data)}get enum(){return this._def.values}};vt.create=(e,t)=>new vt({values:e,typeName:N.ZodNativeEnum,...O(t)});Ye=class extends D{static{o(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.promise&&n.common.async===!1)return E(n,{code:v.invalid_type,expected:A.promise,received:n.parsedType}),C;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return Q(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Ye.create=(e,t)=>new Ye({type:e,typeName:N.ZodPromise,...O(t)});pe=class extends D{static{o(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:o(a=>{E(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return C;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?C:l.status==="dirty"?lt(l.value):n.value==="dirty"?lt(l.value):l});{if(n.value==="aborted")return C;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?C:c.status==="dirty"?lt(c.value):n.value==="dirty"?lt(c.value):c}}if(s.type==="refinement"){let a=o(c=>{let l=s.refinement(c,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?C:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ve(a))return C;let c=s.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Ve(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):C);M.assertNever(s)}};pe.create=(e,t,n)=>new pe({schema:e,typeName:N.ZodEffects,effect:t,...O(n)});pe.createWithPreprocess=(e,t,n)=>new pe({schema:t,effect:{type:"preprocess",transform:e},typeName:N.ZodEffects,...O(n)});de=class extends D{static{o(this,"ZodOptional")}_parse(t){return this._getType(t)===A.undefined?Q(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};de.create=(e,t)=>new de({innerType:e,typeName:N.ZodOptional,...O(t)});ke=class extends D{static{o(this,"ZodNullable")}_parse(t){return this._getType(t)===A.null?Q(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ke.create=(e,t)=>new ke({innerType:e,typeName:N.ZodNullable,...O(t)});kt=class extends D{static{o(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};kt.create=(e,t)=>new kt({innerType:e,typeName:N.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...O(t)});St=class extends D{static{o(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return tn(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new oe(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new oe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};St.create=(e,t)=>new St({innerType:e,typeName:N.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...O(t)});cn=class extends D{static{o(this,"ZodNaN")}_parse(t){if(this._getType(t)!==A.nan){let r=this._getOrReturnCtx(t);return E(r,{code:v.invalid_type,expected:A.nan,received:r.parsedType}),C}return{status:"valid",value:t.data}}};cn.create=e=>new cn({typeName:N.ZodNaN,...O(e)});rw=Symbol("zod_brand"),tr=class extends D{static{o(this,"ZodBranded")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},nr=class e extends D{static{o(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return o(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?C:i.status==="dirty"?(n.dirty(),lt(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})},"handleAsync")();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?C:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:N.ZodPipeline})}},xt=class extends D{static{o(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=o(s=>(Ve(s)&&(s.value=Object.freeze(s.value)),s),"freeze");return tn(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};xt.create=(e,t)=>new xt({innerType:e,typeName:N.ZodReadonly,...O(t)});o(ld,"cleanParams");o(md,"custom");sw={object:ae.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(N||(N={}));iw=o((e,t={message:`Input not instance of ${e.name}`})=>md(n=>n instanceof e,t),"instanceOfType"),hd=ze.create,gd=dt.create,ow=cn.create,aw=ut.create,yd=pt.create,cw=ft.create,lw=rn.create,dw=mt.create,uw=ht.create,pw=qe.create,fw=Me.create,mw=he.create,hw=sn.create,gw=$e.create,yw=ae.create,_w=ae.strictCreate,bw=gt.create,ww=ss.create,vw=yt.create,kw=ve.create,Sw=is.create,xw=on.create,Ew=an.create,Aw=os.create,Tw=_t.create,Rw=bt.create,Iw=wt.create,Cw=vt.create,Nw=Ye.create,Ow=pe.create,Dw=de.create,Pw=ke.create,Mw=pe.createWithPreprocess,$w=nr.create,Lw=o(()=>hd().optional(),"ostring"),Fw=o(()=>gd().optional(),"onumber"),jw=o(()=>yd().optional(),"oboolean"),Uw={string:o(e=>ze.create({...e,coerce:!0}),"string"),number:o(e=>dt.create({...e,coerce:!0}),"number"),boolean:o(e=>pt.create({...e,coerce:!0}),"boolean"),bigint:o(e=>ut.create({...e,coerce:!0}),"bigint"),date:o(e=>ft.create({...e,coerce:!0}),"date")},Hw=C});var f={};se(f,{BRAND:()=>rw,DIRTY:()=>lt,EMPTY_PATH:()=>Mb,INVALID:()=>C,NEVER:()=>Hw,OK:()=>Q,ParseStatus:()=>V,Schema:()=>D,ZodAny:()=>qe,ZodArray:()=>$e,ZodBigInt:()=>ut,ZodBoolean:()=>pt,ZodBranded:()=>tr,ZodCatch:()=>St,ZodDate:()=>ft,ZodDefault:()=>kt,ZodDiscriminatedUnion:()=>ss,ZodEffects:()=>pe,ZodEnum:()=>wt,ZodError:()=>oe,ZodFirstPartyTypeKind:()=>N,ZodFunction:()=>os,ZodIntersection:()=>yt,ZodIssueCode:()=>v,ZodLazy:()=>_t,ZodLiteral:()=>bt,ZodMap:()=>on,ZodNaN:()=>cn,ZodNativeEnum:()=>vt,ZodNever:()=>he,ZodNull:()=>ht,ZodNullable:()=>ke,ZodNumber:()=>dt,ZodObject:()=>ae,ZodOptional:()=>de,ZodParsedType:()=>A,ZodPipeline:()=>nr,ZodPromise:()=>Ye,ZodReadonly:()=>xt,ZodRecord:()=>is,ZodSchema:()=>D,ZodSet:()=>an,ZodString:()=>ze,ZodSymbol:()=>rn,ZodTransformer:()=>pe,ZodTuple:()=>ve,ZodType:()=>D,ZodUndefined:()=>mt,ZodUnion:()=>gt,ZodUnknown:()=>Me,ZodVoid:()=>sn,addIssueToContext:()=>E,any:()=>pw,array:()=>gw,bigint:()=>aw,boolean:()=>yd,coerce:()=>Uw,custom:()=>md,date:()=>cw,datetimeRegex:()=>pd,defaultErrorMap:()=>De,discriminatedUnion:()=>ww,effect:()=>Ow,enum:()=>Iw,function:()=>Aw,getErrorMap:()=>en,getParsedType:()=>we,instanceof:()=>iw,intersection:()=>vw,isAborted:()=>ns,isAsync:()=>tn,isDirty:()=>rs,isValid:()=>Ve,late:()=>sw,lazy:()=>Tw,literal:()=>Rw,makeIssue:()=>er,map:()=>xw,nan:()=>ow,nativeEnum:()=>Cw,never:()=>mw,null:()=>uw,nullable:()=>Pw,number:()=>gd,object:()=>yw,objectUtil:()=>mo,oboolean:()=>jw,onumber:()=>Fw,optional:()=>Dw,ostring:()=>Lw,pipeline:()=>$w,preprocess:()=>Mw,promise:()=>Nw,quotelessJson:()=>Ob,record:()=>Sw,set:()=>Ew,setErrorMap:()=>Pb,strictObject:()=>_w,string:()=>hd,symbol:()=>lw,transformer:()=>Ow,tuple:()=>kw,undefined:()=>dw,union:()=>bw,unknown:()=>fw,util:()=>M,void:()=>hw});var bo=b(()=>{ts();go();od();Qn();_d();es()});var ee=b(()=>{bo();bo()});var wo,vo=b(()=>{"use strict";ee();wo=f.object({id:f.string().min(1),title:f.string().min(1).max(200),type:f.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:f.enum(["community","curated"]),lesson_class:f.enum(["general","architecture"]).default("general"),quality_tier:f.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:f.object({source:f.enum(["memory","vault","claude-md"]),source_id:f.string().min(1),migrated_at:f.string(),migrated_from_workspace:f.string().optional()}).optional(),context:f.object({tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tags:f.array(f.string()).default([])}),summary:f.string().min(1).max(500),problem:f.string().optional(),solution:f.string().optional(),gotchas:f.array(f.string()).default([]),template_body:f.string().min(1).optional(),target_file:f.string().min(1).optional(),submitted_by:f.string().optional(),evidence:f.string().optional(),last_validated_at:f.string().optional(),tool_versions:f.record(f.string(),f.string()).optional(),upvotes:f.number().int().nonnegative().default(0),version:f.number().int().min(1).default(1),changed_at:f.string().optional(),changelog:f.string().max(500).optional(),revision_of:f.string().optional(),org_id:f.string().uuid().optional(),org_name:f.string().optional(),scope:f.literal("private").optional(),body:f.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:f.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:f.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))})});var Gw,bd=b(()=>{"use strict";ee();vo();Gw=wo.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:f.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:f.ZodIssueCode.custom,path:["template_body"],message:"template_body is required and must be non-empty"}),(!e.target_file||e.target_file.length===0)&&t.addIssue({code:f.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:f.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})})});var wd,vd,kd,Sd,ko,xd,Ed,Ad,Ww,Td=b(()=>{"use strict";ee();wd=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],vd=f.enum(wd),kd=["new_to_ai_agents","new_to_this_client","experienced"],Sd=f.enum(kd),ko=[{id:"model-selection",header:"Model selection"},{id:"effort-levels",header:"Effort levels"},{id:"modes",header:"Modes"},{id:"language",header:"Language"},{id:"context-economy",header:"Context economy"},{id:"permissions",header:"Permissions"},{id:"cost",header:"Cost"},{id:"hooks",header:"Hooks"},{id:"learnings",header:"Learnings"},{id:"mcp-snippet",header:"MCP snippet"},{id:"first-week",header:"First week"}],xd=ko.map(e=>e.header),Ed=f.object({experience_level:f.array(Sd).default([]),stack_filters:f.array(f.string()).default([])}).default({experience_level:[],stack_filters:[]}),Ad=f.object({id:f.string().min(1),client:vd,title:f.string().min(1),last_updated:f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:Ed,version:f.number().int().min(1).default(1),changelog:f.string().max(500).optional()}),Ww=Ad.extend({body:f.string().min(1)})});var Id,as,Cd,cs,Bw,Kw,Nd,Od,Dd,Pd,ls,Vw,zw,Rd,qw,Md,Yw,$d=b(()=>{"use strict";ee();Id=["operating_procedure","code_review","communication_style"],as=f.enum(Id),Cd=["info","recommended","required"],cs=f.enum(Cd),Bw=["optional","default_on","mandatory"],Kw=f.enum(Bw),Nd=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Od=f.enum(Nd),Dd=["verify","contribute","mixed"],Pd=f.enum(Dd),ls=f.object({clients:f.array(Od).default([]),stacks:f.array(f.string()).default([]),intents:f.array(Pd).default([])}).default({clients:[],stacks:[],intents:[]}),Vw=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,zw=64,Rd=200,qw=f.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),Md=f.object({id:f.string().min(5).max(zw).regex(Vw,"id must match conv_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),scope:as,version:f.number().int().min(1),changed_at:qw,changelog:f.string().max(500).optional(),applies_to:ls,severity:cs.default("recommended"),disableability:Kw.default("default_on"),summary:f.string().min(1).max(Rd,`summary must be \u2264 ${Rd} chars (rendered as one line in init-push)`),review_gate:f.object({enabled:f.boolean(),min_matched_symbols:f.number().int().min(1).max(8).default(2),hard:f.boolean().default(!1)}).optional(),gateway_gate:f.object({enabled:f.boolean(),deny_tools:f.array(f.string().min(1).max(128)).min(1).max(16),servers:f.array(f.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),Yw=Md.extend({body:f.string().min(1)})});var Je=b(()=>{"use strict";vo();bd();Td();$d()});var So,ds,xo,Ld,Fd,jd,Jw,Ud=b(()=>{"use strict";ee();So=f.object({type:f.literal("text"),md:f.string().min(1).max(2e4)}),ds=f.number().min(0).max(1).optional(),xo=f.object({type:f.literal("media"),kind:f.enum(["image","video"]),url:f.string().url().max(2048),alt:f.string().max(500).optional(),caption:f.string().max(500).optional(),fog:f.object({top:ds,right:ds,bottom:ds,left:ds}).optional()}),Ld=f.object({label:f.string().min(1).max(40),color:f.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),Fd=f.object({type:f.literal("accordion"),title:f.string().min(1).max(200),subtag:Ld.optional(),blocks:f.array(f.discriminatedUnion("type",[So,xo])).max(50)}),jd=f.discriminatedUnion("type",[So,xo,Fd]),Jw=f.array(jd).max(100)});var Hd,Xw,Gd,Wd,Zw,Qw,ev,Bd=b(()=>{"use strict";ee();Hd=["free","solo_pro","team","enterprise"],Xw=f.enum(Hd),Gd=["solo_pro","team","enterprise"],Wd=f.enum(Gd),Zw=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),Qw=f.object({user_id:f.string().uuid(),tier:Wd,reason:f.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:Zw.nullable().optional(),auto_revoke_on_stripe:f.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),ev=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Kd=b(()=>{"use strict"});var tv,nv,rv,Vd=b(()=>{"use strict";ee();tv=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),nv=f.object({org_id:f.string().uuid(),seats:f.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:f.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:tv.nullable().optional(),auto_revoke_on_stripe:f.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),rv=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var zd,sv,qd,Yd,Jd,Xd,iv,Zd=b(()=>{"use strict";ee();zd=f.enum(["info","important","critical"]),sv=f.enum(["pass","warn","fail"]),qd=f.object({type:f.enum(["template","lesson"]),id:f.string().min(1)}),Yd=f.object({languages:f.array(f.string()).optional(),tools:f.array(f.string()).optional()}).optional(),Jd=f.discriminatedUnion("kind",[f.object({kind:f.literal("file-exists"),path:f.string().min(1)}),f.object({kind:f.literal("any-file-exists"),paths:f.array(f.string().min(1)).min(1)}),f.object({kind:f.literal("any-agent-config")}),f.object({kind:f.literal("file-size-budget"),field:f.enum(["claude_md","readme"]),max_chars:f.number().int().positive()}),f.object({kind:f.literal("readme-section-present"),headers:f.array(f.string().min(1)).min(1)}),f.object({kind:f.literal("adr-dir-present")}),f.object({kind:f.literal("git-present")}),f.object({kind:f.literal("quality-gates-configured"),pass_if_at_least:f.number().int().min(1).max(4).optional(),warn_if_at_least:f.number().int().min(0).max(4).optional()}),f.object({kind:f.literal("storage-risk-safe"),allow_unknown:f.boolean().optional()}),f.object({kind:f.literal("doc-path-discoverability")})]),Xd=f.object({id:f.string().min(1),title:f.string().min(1),severity:zd,weight:f.number().int().positive().max(100),applies_when:Yd,check:Jd,fail_message:f.string().min(1),warn_message:f.string().optional(),remediation:qd.optional()}),iv=f.object({version:f.literal(1),checks:f.array(Xd).min(1)})});function av(e){if(!ov.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function us(e){return[e.input_above_200k,e.output_above_200k,e.cache_read_above_200k,e.cache_write_5m_above_200k,e.cache_write_1h_above_200k].filter(t=>t!==void 0).length}function cv(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var ov,ps,Qd,eu,Se,tu,lv,nu=b(()=>{"use strict";ee();ov=/^\d{4}-\d{2}-\d{2}$/;o(av,"isRealDate");ps=f.string().refine(av,{message:"expected a real calendar date as YYYY-MM-DD"}),Qd=["exact","prefix"],eu=f.enum(Qd),Se=f.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),tu=f.object({model_pattern:f.string().min(1).max(100),match_kind:eu,valid_from:ps,valid_to:ps.nullable().optional(),input:Se,output:Se,cache_read:Se,cache_write_5m:Se,cache_write_1h:Se,long_context:f.enum(["same_price","tiered"]).optional(),input_above_200k:Se.optional(),output_above_200k:Se.optional(),cache_read_above_200k:Se.optional(),cache_write_5m_above_200k:Se.optional(),cache_write_1h_above_200k:Se.optional(),context_threshold_tokens:f.number().int().positive().nullable().optional(),source_url:f.string().url().max(500).nullable().optional(),note:f.string().max(500).nullable().optional()}).strict().refine(e=>!e.valid_to||e.valid_to>e.valid_from,{message:"valid_to must be after valid_from",path:["valid_to"]}).refine(e=>us(e)===0||us(e)===5,{message:"above-200k rates must be given for all five classes or none",path:["input_above_200k"]}).refine(e=>e.long_context==="tiered"||us(e)===0,{message:'above-200k rates require long_context: "tiered"',path:["long_context"]}).refine(e=>e.context_threshold_tokens==null||e.long_context==="tiered",{message:'context_threshold_tokens requires long_context: "tiered"',path:["context_threshold_tokens"]}).refine(e=>us(e)===0||e.context_threshold_tokens==null||e.context_threshold_tokens===2e5,{message:"above-rates are only supported at context_threshold_tokens: 200000 \u2014 the analyzer groups against that constant and cannot see another boundary",path:["context_threshold_tokens"]});o(us,"aboveRateCount");o(cv,"rowKey");lv=f.object({changelog:f.string().min(1).max(500),as_of:ps,source_url:f.string().url().max(500),rows:f.array(tu).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((s,i)=>{let a=cv(s),c=n.get(a);c!==void 0?t.addIssue({code:f.ZodIssueCode.custom,path:["rows",i],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,i)});let r=new Map;e.rows.forEach((s,i)=>{let a=`${s.model_pattern}|${s.match_kind}`,c=r.get(a)??[];c.push({i,r:s}),r.set(a,c)});for(let s of r.values())if(!(s.length<2)){s.sort((i,a)=>i.r.valid_from.localeCompare(a.r.valid_from));for(let i=0;i<s.length-1;i++){let a=s[i],c=s[i+1];(!a.r.valid_to||a.r.valid_to>c.r.valid_from)&&t.addIssue({code:f.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var ln=b(()=>{"use strict"});var rr=b(()=>{"use strict"});var ou=b(()=>{"use strict";rr();ln()});var au=b(()=>{"use strict";ln()});var cu=b(()=>{"use strict";Je();rr();ln()});var lu=b(()=>{"use strict";rr();ln()});var du=b(()=>{"use strict";ln();ou();au();cu();lu();rr()});var Rv,Iv,uu,Cv,pu,Eo,fu,mu,hu,gu,Nv,Ao=b(()=>{"use strict";ee();Je();Rv=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,Iv=64,uu=200,Cv=1e3,pu=f.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,f.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),Eo=f.enum(["low","medium","high"]),fu=f.object({owner:f.string().min(1).max(160).optional(),risk_level:Eo.optional(),reviewed_at:pu.optional()}).default({}),mu=f.object({tags:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),limit:f.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),hu=f.object({lesson_query:mu,lesson_pins:f.array(f.string()).default([]),lesson_excludes:f.array(f.string()).default([]),convention_ids:f.array(f.string()).default([]),template_ids:f.array(f.string()).default([]),setup_guide_ids:f.array(f.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),gu=f.object({id:f.string().min(6).max(Iv).regex(Rv,"id must match skill_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),version:f.number().int().min(1),changed_at:pu,tier:f.enum(["community","curated"]).default("curated"),summary:f.string().min(1).max(uu,`summary must be \u2264 ${uu} chars (rendered as one line in skill_index)`),description:f.string().max(Cv).optional(),applies_to:ls,membership:hu,governance:fu}),Nv=gu.extend({body:f.string().default(""),org_id:f.string().uuid().optional(),org_name:f.string().optional()})});var yu,_u,bu,wu,vu,ku,Ov,Su,Dv,Pv,xu=b(()=>{"use strict";ee();Ao();yu=f.enum(["maind","agent-skill"]),_u=f.enum(["ready","needs_attention","blocked"]),bu=f.enum(["info","important","critical"]),wu=f.enum(["pass","warn","fail"]),vu=f.enum(["structure","governance","scope","membership","package","references"]),ku=f.object({id:f.string().min(1),title:f.string().min(1),status:wu,severity:bu,category:vu,field:f.string().nullable().optional(),message:f.string().min(1),hint:f.string().optional()}),Ov=f.object({lesson_ids:f.array(f.string()).optional(),convention_ids:f.array(f.string()).optional(),template_ids:f.array(f.string()).optional(),setup_guide_ids:f.array(f.string()).optional()}).default({}),Su=f.object({name:f.string().min(1).max(64),description:f.string().min(1).max(1024),license:f.string().optional(),compatibility:f.union([f.string(),f.array(f.string())]).optional(),metadata:f.record(f.string()).default({}),"allowed-tools":f.union([f.string(),f.array(f.string())]).optional()}).passthrough(),Dv=f.object({directory_name:f.string().min(1).max(120).optional(),frontmatter:Su,body:f.string().default(""),file_listing:f.array(f.string()).optional()}),Pv=f.object({format:yu,subject:f.string().min(1),status:_u,summary:f.string().min(1),counts:f.object({pass:f.number().int().min(0),warn:f.number().int().min(0),fail:f.number().int().min(0)}),checks:f.array(ku),next_steps:f.array(f.string()),trust_note:f.string().min(1)})});var Eu,Mv,Au,Tu,Ru,dn,$v,Iu,Cu,Nu,Ou,Du,Lv,Fv,Pu,jv,Mu=b(()=>{"use strict";ee();Je();Eu=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],Mv=f.enum(Eu),Au=["verdict","advisory"],Tu=f.enum(Au),Ru=["block","warn","note"],dn=f.enum(Ru),$v=f.object({convention_id:f.string().min(1).max(64),convention_version:f.number().int().min(1),severity:cs,scope:as,grade:Tu,matched_symbols:f.array(f.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:f.array(f.string().min(1).max(512)).max(64).default([]),summary:f.string().max(2e3),hard:f.boolean().optional()}),Iu=["open","warn","info"],Cu=f.enum(Iu),Nu=["introduced","pre_existing"],Ou=f.enum(Nu),Du=["full","partial","none"],Lv=f.enum(Du),Fv=f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:f.string().regex(/^\d+\.\d+\.\d+$/),rule_id:f.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:Cu,baseline:Ou,evidence_hash:f.string().regex(/^[a-f0-9]{64}$/),count:f.number().int().min(1).max(1e5)}),Pu=f.object({version:f.literal(1).default(1),actions:f.object({required:dn.default("block"),recommended:dn.default("warn"),info:dn.default("note")}).default({}),overrides:f.array(f.object({convention_id:f.string().min(1).max(64),action:dn})).max(64).default([]),risk_flag_action:f.enum(["warn","note","ignore"]).default("warn"),detector_overrides:f.array(f.object({detector_id:f.string().regex(/^det_[a-z0-9_]{2,59}$/),action:dn,reason:f.string().min(1).max(200)})).max(32).optional()}),jv=Pu.parse({})});var $u,Lu,Fu,ju,Uu,To,Uv,Hv,Hu,Gu,Wu,Bu,Ku,Gv,Wv,Vu,zu,qu,Bv,Yu=b(()=>{"use strict";ee();$u=14,Lu=14,Fu=14,ju=1,Uu=365,To=f.number().int().min(ju).max(Uu),Uv=["propose","direct"],Hv="propose",Hu=["propose","direct"],Gu="propose",Wu=["propose","direct"],Bu="propose",Ku=["off","propose","direct"],Gv=["member","admin","owner"],Wv="member",Vu="off",zu="en",qu=f.object({version:f.literal(1).default(1),at_risk_days:To.default($u),stagnation_days:To.default(Lu),agent_date_mode:f.enum(Uv).default(Hv),health_manual_ttl_days:To.default(Fu),agent_event_mode:f.enum(Hu).default(Gu),agent_update_mode:f.enum(Wu).default(Bu),agent_pull_mode:f.enum(Ku).default(Vu),org_wide_authoring_min_role:f.enum(Gv).default(Wv),planning_language:f.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(zu)}),Bv=qu.parse({})});var Ju,Kv,Xu=b(()=>{"use strict";ee();Ju=f.object({version:f.literal(1).default(1),org_visibility:f.boolean().default(!1),session_span_visibility:f.boolean().default(!0)}),Kv=Ju.parse({})});var Zu,Qu,Vv,zv,ep=b(()=>{"use strict";ee();Zu=f.object({tools:f.array(f.string()).default([]),languages:f.array(f.string()).default([]),platforms:f.array(f.string()).default([]),tags:f.array(f.string()).default([])}),Qu=f.object({id:f.string().uuid(),user_id:f.string().uuid(),project:f.string().max(200).nullable().optional(),title:f.string().min(1).max(200),body:f.string().min(1).max(2e4),context:Zu.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:f.string(),updated_at:f.string(),last_recalled_at:f.string().nullable().optional(),recall_count:f.number().int().nonnegative().default(0),graduated_draft_id:f.string().uuid().nullable().optional(),deleted_at:f.string().nullable().optional()}),Vv=Qu.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:f.number()}),zv=f.object({id:f.string().uuid(),title:f.string(),summary:f.string(),tags:f.array(f.string()).default([])})});var tp=b(()=>{"use strict"});var np=b(()=>{"use strict"});function fs(e){let t=[],n=null;return e.split(`
|
|
20
|
+
`).forEach((r,s)=>{let i=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(i===""||a>n)return;n=null}if(i===""||i.startsWith("#"))return;let c=Yv.exec(r);if(!c)return;let l=c[3]??"";if(qv.has(l.trim())){n=a;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&t.push({line:s+1,value:d})}),t}var qv,Yv,rp=b(()=>{"use strict";qv=new Set(["|",">","|-",">-","|+",">+"]),Yv=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;o(fs,"plainScalarViolations")});function ir(e,t){let n=o(c=>{let[l,d=""]=c.split("-",2),u=l.split(".").map(p=>{let m=Number(p);return Number.isFinite(m)?m:0});for(;u.length<3;)u.push(0);return[u,d.length>0?d.split("."):[]]},"split"),[r,s]=n(e),[i,a]=n(t);for(let c=0;c<Math.max(r.length,i.length);c+=1){let l=(r[c]??0)-(i[c]??0);if(l!==0)return l<0?-1:1}if(s.length===0&&a.length===0)return 0;if(s.length===0)return 1;if(a.length===0)return-1;for(let c=0;c<Math.max(s.length,a.length);c+=1){let l=s[c],d=a[c];if(l===void 0)return-1;if(d===void 0)return 1;let u=/^\d+$/.test(l),p=/^\d+$/.test(d);if(u&&p){let m=Number(l)-Number(d);if(m!==0)return m<0?-1:1}else{if(u!==p)return u?-1:1;if(l!==d)return l<d?-1:1}}return 0}var sp=b(()=>{"use strict";o(ir,"compareSemver")});var Ro=b(()=>{"use strict";Je();Ud();Je();Je();Bd();Kd();Vd();Zd();nu();du();Je();Ao();xu();Mu();Yu();Xu();ep();tp();np();rp();sp()});import{execFileSync as Jv}from"node:child_process";import{existsSync as Xv,readFileSync as Zv}from"node:fs";import{join as Qv}from"node:path";function or(e){let t=[],n=e.split(`
|
|
21
|
+
`);for(let r=0;r<n.length;r+=1){let s=n[r]??"";if(!/^##(?!#)\s/.test(s))continue;let i=/(\d+\.\d+\.\d+)/.exec(s);i&&t.push({version:i[1],line:r+1,raw:s.trim(),shape:/^##\s+Unreleased\b/i.test(s)?"unreleased-labelled":ek.test(s)?"never-published":"released"})}return t}function op(e){let t=new Map;for(let n of or(e)){let r=t.get(n.version);r?r.push(n):t.set(n.version,[n])}return[...t.entries()].filter(([,n])=>n.length>1).map(([n,r])=>({version:n,count:r.length,lines:r.map(s=>s.line),shapes:r.map(s=>s.shape)})).sort((n,r)=>(n.lines[0]??0)-(r.lines[0]??0))}function ap(e,t){let n=op(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of or(t))r.set(a.version,(r.get(a.version)??0)+1);let s=[],i=[];for(let a of n){let c=r.get(a.version)??0;(a.count>c?s:i).push({...a,countBefore:c})}return{introduced:s,preExisting:i,baseResolved:!0}}function cp(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no CHANGELOG.md tracked",findings:[],facts:e};let t=[];for(let r of e.files){if(r.head===null)continue;let s=ap(r.head,e.baseRef===null?null:r.base);for(let i of s.introduced)t.push({path:r.path,version:i.version,level:"open",count:i.count,countBefore:i.countBefore,lines:i.lines,title:`${r.path}: version ${i.version} has ${i.count} headings (was ${i.countBefore})`});for(let i of s.preExisting)t.push({path:r.path,version:i.version,level:"info",count:i.count,countBefore:i.countBefore,lines:i.lines,title:`${r.path}: version ${i.version} already had ${i.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function ip(e,t){try{return Jv("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function tk(e,t={}){let n=ip(["ls-files","-z","--","*CHANGELOG.md","CHANGELOG.md"],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),s=t.baseRef??null,i=r.map(a=>{let c=Qv(e,a);return{path:a,head:Xv(c)?Zv(c,"utf8"):null,base:s===null?null:ip(["show",`${s}:${a}`],e)}});return{isRepo:!0,baseRef:s,files:i}}function Io(e,t={}){return cp(tk(e,t))}var ek,ms=b(()=>{"use strict";ek=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;o(or,"parseVersionHeadings");o(op,"findDuplicateHeadings");o(ap,"classifyIntroduced");o(cp,"computeChangelogDuplicates");o(ip,"git");o(tk,"gatherChangelogFacts");o(Io,"checkChangelogDuplicates")});import{execFileSync as nk}from"node:child_process";import{existsSync as rk,readFileSync as lp}from"node:fs";import{dirname as dp,join as up}from"node:path";function fp(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.packages.length===0)return{ok:!1,verdict:"no_opinion",reason:"no publishable package.json tracked",findings:[],facts:e};if(!e.registryReachable)return{ok:!1,verdict:"no_opinion",reason:e.registryError??"registry unreachable",findings:[],facts:e};let t=[];for(let n of e.packages){let r=new Set(e.published[n.name]??[]),s=new Set(n.documentedBase??n.documented),i=[...n.documented].sort(ir);for(let a of i){if(r.has(a)||ir(a,n.version)>=0)continue;let c=!s.has(a);t.push({package:n.name,version:a,level:c?"open":"info",rule:"release.phantom",title:c?`${n.name}@${a} is newly documented as released but the registry never served it`:`${n.name}@${a} is documented as released but the registry never served it`})}for(let a of[...n.neverPublished??[]].sort(ir))r.has(a)&&t.push({package:n.name,version:a,level:"info",rule:"release.mislabelled",title:`${n.name}@${a} is marked never published but the registry serves it`});r.has(n.version)||t.push({package:n.name,version:n.version,level:"info",rule:"release.unpublished",title:`${n.name}@${n.version} is not published yet`})}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"mismatch",reason:null,findings:t,facts:e}}function pp(e){let t=or(e),n=[...new Set(t.filter(i=>i.shape!=="never-published").map(i=>i.version))],r=new Set(n),s=[...new Set(t.filter(i=>i.shape==="never-published"&&!r.has(i.version)).map(i=>i.version))];return{documented:n,neverPublished:s}}function Co(e,t){try{return nk("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function mp(e,t=null){let n=Co(["ls-files","-z","--","package.json","*/package.json"],e);if(n===null)return[];let r=[];for(let s of[...new Set(n.split("\0").filter(Boolean))].sort()){let i;try{i=JSON.parse(lp(up(e,s),"utf8"))}catch{continue}if(i.private===!0||typeof i.name!="string"||typeof i.version!="string")continue;let a=dp(s)==="."?"":dp(s),c=up(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=rk(c)?pp(lp(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,p=t===null?null:Co(["show",`${t}:${u}`],e),m=t===null?null:p===null?[]:pp(p).documented;r.push({dir:a,name:i.name,version:i.version,documented:l,documentedBase:m,neverPublished:d})}return r}async function sk(e){let t=`https://registry.npmjs.org/${e.replace("/","%2F")}`,n=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(n.status===404)return[];if(!n.ok)throw new Error(`HTTP ${n.status}`);let r=await n.json();return Object.keys(r.versions??{})}async function hp(e,t={}){if(Co(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=mp(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??sk,s={};for(let i of n)try{s[i.name]=await r(i.name)}catch(a){return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:`${i.name}: ${a.message}`}}return{isRepo:!0,packages:n,published:s,registryReachable:!0,registryError:null}}async function No(e,t={}){return fp(await hp(e,t))}var Oo=b(()=>{"use strict";Ro();ms();o(fp,"computeReleaseClaims");o(pp,"claimsOf");o(Co,"git");o(mp,"discoverPackages");o(sk,"packument");o(hp,"gatherReleaseClaimsFacts");o(No,"checkReleaseClaims")});import{execFileSync as ik}from"node:child_process";import{existsSync as ok,readFileSync as ak}from"node:fs";import{join as ck}from"node:path";function gp(e){return e.split(`
|
|
22
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function _p(e,t){let n=new Map;for(let i of gp(t??""))n.set(i,(n.get(i)??0)+1);let r=[];for(let i of gp(e)){let a=n.get(i)??0;a>0?n.set(i,a-1):r.push(i)}let s=0;for(let i of n.values())s+=i;return{added:r,removed:s,net:Math.max(0,r.length-s)}}function bp(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.baseRef===null)return{ok:!1,verdict:"no_opinion",reason:"no base to measure growth against",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no agent instruction file tracked",findings:[],facts:e};let t=[];for(let n of e.files){if(n.head===null)continue;let r=_p(n.head,n.base);r.net!==0&&t.push({path:n.path,level:"open",netLines:r.net,addedLines:r.added.length,removedLines:r.removed,sample:r.added.slice(0,5),newFile:n.base===null,title:n.base===null?`${n.path}: new agent instruction file with ${r.net} line(s) \u2014 every line loads into every session`:`${n.path}: +${r.net} line(s) of agent instructions \u2014 every line loads into every session; durable knowledge belongs in docs, a convention or a code comment`})}return{ok:t.length===0,verdict:t.length===0?"clean":"grown",reason:null,findings:t,facts:e}}function Do(e,t){try{return ik("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function wp(e,t={}){let n=Do(["ls-files","-z","--",...yp],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&Do(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,i=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=ck(e,a);return{path:a,head:ok(c)?ak(c,"utf8"):null,base:r===null?null:Do(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:i}}function Po(e,t={}){return bp(wp(e,t))}var yp,Mo=b(()=>{"use strict";yp=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"];o(gp,"contentLines");o(_p,"proseDelta");o(bp,"computeAgentDocProse");o(Do,"git");o(wp,"gatherAgentDocProseFacts");o(Po,"checkAgentDocProse")});import{execFileSync as lk}from"node:child_process";import{existsSync as dk,readFileSync as uk}from"node:fs";import{join as pk}from"node:path";function kp(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no workflow files under .github/workflows",findings:[],facts:e};let t=[];for(let n of e.files){if(n.content===null)continue;let r=new Set(n.base===null?[]:fs(n.base).map(s=>s.value));for(let s of fs(n.content)){let i=s.value.length>60?`${s.value.slice(0,57)}\u2026`:s.value,a=e.baseRef!==null&&!r.has(s.value);t.push({path:n.path,level:a?"open":"info",line:s.line,value:s.value,title:`${n.path}:${s.line}: unquoted plain scalar containing ": " \u2014 ${i}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function vp(e,t){try{return lk("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function Sp(e,t={}){let n=vp(["ls-files","-z","--",".github/workflows/*.yml",".github/workflows/*.yaml"],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),s=t.baseRef??null;return{isRepo:!0,baseRef:s,files:r.map(i=>{let a=pk(e,i);return{path:i,content:dk(a)?uk(a,"utf8"):null,base:s===null?null:vp(["show",`${s}:${i}`],e)}})}}function $o(e,t={}){return kp(Sp(e,t))}var Lo=b(()=>{"use strict";Ro();o(kp,"computeWorkflowYaml");o(vp,"git");o(Sp,"gatherWorkflowYamlFacts");o($o,"checkWorkflowYaml")});import{readFileSync as fk}from"node:fs";import{join as mk,posix as hk}from"node:path";function xp(e){let t="",n=0,r=e.length;for(;n<r;){let s=e[n],i=e[n+1];if(s==="-"&&i==="-"){for(;n<r&&e[n]!==`
|
|
23
|
+
`;)n++;continue}if(s==="/"&&i==="*"){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(s==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let a=(s==="E"||s==="e")&&i==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(s==="'"||a){let c=s!=="'";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+=s,n++}return t}function ge(e){let t=[],n="",r=!1,s=!1,i=o(()=>{t.push(s?n:n.toLowerCase()),n="",s=!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,s=!0;continue}if(l==="."&&!r){i();continue}n+=l}i();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 Le(e){let t=[],n=0,r="";for(let s of e){if(s==="("&&n++,s===")"&&(n=Math.max(0,n-1)),s===","&&n===0){t.push(r.trim()),r="";continue}r+=s}return r.trim()&&t.push(r.trim()),t}function gk(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,s,i]=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&&!Le(a[1]).map(m=>ge(m)?.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||!Le(c[1]).map(p=>ge(p)?.name??"").filter(Boolean).includes("public"))return null;let d=Le(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>ge(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of Le(s)){let m=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!m)continue;let h=m[1].toUpperCase();if(h==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...ar]};m[2]!=="("&&ar.includes(h)&&u.push(h)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function Ep(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,s,i]=t;if(n)return null;let a=s.trim();if(yk.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!Le(l[1]).map(m=>ge(m)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),m=Le(p).map(h=>ge(h)).filter(h=>h!==null).filter(h=>h.schema==="public").map(h=>h.name);if(m.length===0)return null;c=m}let d=Le(i).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>ge(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of Le(r)){let m=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!m)continue;let h=m[1].toUpperCase(),g=m[2]==="(";if(h==="ALL")return{tables:c,roles:d,writePrivs:[...ar]};!g&&ar.includes(h)&&u.push(h)}return{tables:c,roles:d,writePrivs:u}}function jo(e){let t=new Map,n=[...e].sort((s,i)=>Ne(s.version,i.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let s of n){let i=xp(s.content);for(let a of i.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=gk(c);if(!p)continue;let m=p.roles.includes("anon"),h=p.roles.includes("authenticated");if(p.action==="revoke"){if(m&&(r.anonAddressed=!0),h)for(let g of p.writePrivs)r.authWritesRevoked.add(g)}else if(m&&(r.anonAddressed=!1),h)for(let g of p.writePrivs)r.authWritesRevoked.delete(g);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=ge(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:s.version,anonAddressed:r.anonAddressed,authWritesRevoked:new Set(r.authWritesRevoked)});continue}let d=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(c);if(d){let p=d[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let m of Le(p)){let h=ge(m);h&&h.schema==="public"&&t.delete(h.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(u){let p=ge(u[1]),m=ge(u[2]);if(p&&m&&p.schema==="public"){let h=t.get(p.name);h&&(t.delete(p.name),t.set(m.name,h))}continue}if(/^REVOKE\b/i.test(c)){let p=Ep(c);if(!p)continue;let m=p.tables==="all_in_public"?[...t.keys()]:p.tables,h=p.roles.includes("anon"),g=p.roles.includes("authenticated");if(!h&&!g)continue;for(let y of m){let _=t.get(y);if(_&&(h&&(_.anonAddressed=!0),g))for(let w of p.writePrivs)_.authWritesRevoked.add(w)}continue}}}return t}function Fo(e){let t=[];for(let[n,r]of jo(e)){let s=[];r.anonAddressed||s.push("anon"),ar.every(i=>r.authWritesRevoked.has(i))||s.push("authenticated_writes"),s.length>0&&t.push({table:n,createdIn:r.createdIn,missing:s})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function Ap(e){let t=Fo(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Fo(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let s=e.baseFiles===null?null:n.get(r.table),a=s!=null&&r.missing.every(l=>s.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 Tp(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function Ho(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(hs)||t.endsWith(Uo))}function bk(e,t){try{let n=fk(e,"utf8");return n.length>t?null:n}catch{return null}}function wk(e,t,n,r,s){let i=T(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(i===null)return s.push(`could not diff ${t} against ${r} ${hs}`),null;let a=new Set,c=[];for(let u of i.split(`
|
|
24
|
+
`).filter(Boolean)){let[p,...m]=u.split(" ");p.startsWith("A")?a.add(m[0]):p.startsWith("R")?(c.push(m[0]),a.add(m[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(m[0])}let l=[],d=new Set(c);for(let{ref:u,content:p}of n)!a.has(u.path)&&!d.has(u.path)&&l.push({name:u.name,version:u.version,content:p});for(let u of c){let p=hk.basename(u),m=Yt(p);if(m===null)continue;let h=T(e,["show",`${r}:${u}`]);if(h===null)return s.push(`could not read ${u} at ${r} ${Uo}`),null;l.push({name:p,version:m,content:h})}return l}function Et(e,t={}){let n=t.maxFileBytes??_k,r=[],s=it(e,t.dirs);if(s.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let i=t.includeBaseline!==!1,a=null;if(i)if(t.baseRef)a=t.baseRef;else{let m=El(e);a=m?`origin/${m}`:null,a===null&&r.push(`no default branch resolvable ${hs}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let m of s){let h=[];for(let _ of m.files){let w=bk(mk(e,_.path),n);if(w===null){r.push(`could not read ${_.path} \u2014 excluded from the fold`);continue}h.push({ref:_,content:w})}let g=h.map(({ref:_,content:w})=>({name:_.name,version:_.version,content:w})),y=a===null?null:wk(e,m.dir,h,a,r);c.push(...Ap({dir:m.dir,files:g,baseFiles:y})),l.push({dir:m.dir,migrationCount:g.length,tableCount:jo(g).size})}let d=l.reduce((m,h)=>m+h.migrationCount,0),u=Tp(d,c.length),p={open:0,info:1};return c.sort((m,h)=>p[m.status]-p[h.status]||m.id.localeCompare(h.id)),{ok:u!=="no_opinion"&&!c.some(m=>m.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var ar,yk,_k,hs,Uo,gs=b(()=>{"use strict";ie();Vn();o(xp,"stripSql");o(ge,"normalizeQualifiedIdent");o(Le,"splitTopLevel");ar=["INSERT","UPDATE","DELETE"];o(gk,"parseDefaultAclTables");yk=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;o(Ep,"parseTableRevoke");o(jo,"foldTableAcl");o(Fo,"evaluateTableAcl");o(Ap,"computeTableAclFindings");o(Tp,"deriveTableAclVerdict");_k=5e6,hs="\u2014 findings reported ungraded (open)",Uo="\u2014 baseline degraded";o(Ho,"isTableAclGraded");o(bk,"safeRead");o(wk,"baseFilesFor");o(Et,"checkTableAclLint")});import{readFileSync as vk}from"node:fs";import{join as Go}from"node:path";function Bo(e){return e.verdict!=="no_opinion"&&e.graded}function Ko(e){let t=new Set;for(let n of e.matchAll(kk))t.add(n[1]);return t}function Vo(e){return new Set([...e].map(t=>t.split("-")[0]))}function Dp(e){return e.split(`
|
|
33
25
|
`).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
|
|
34
|
-
`)}function
|
|
35
|
-
`).filter(Boolean)}function At(e,t={}){let n=t.maxFileBytes??
|
|
36
|
-
`).filter(Boolean)),l=o(p=>c.has(p)?
|
|
37
|
-
`).filter(s=>s.length>0&&n.some(i=>AS(s,i)))}function AS(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),s=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(s!==""&&!e.startsWith(s+"/"))return!1;let i=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?i.endsWith(r.slice(1)):i===r}function IS(e){let t=R(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(s=>R(e,["rev-parse","--verify","--quiet",`origin/${s}`])!==null);return r?`origin/${r}`:null}function qo(e,t){try{let n=kS(e,"utf8");return n.length>t?null:n}catch{return null}}var df,SS,xS,af,TS,Ns=b(()=>{"use strict";re();o(Yo,"isThemeClassDriftGraded");df=["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"],SS=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,xS=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+df.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");o(Jo,"extractTokens");o(Xo,"deriveNamespaces");o(uf,"stripCommentLines");o(Zo,"evaluateThemeClasses");o(of,"findingKey");o(ES,"gradeAgainstBaseline");o(pf,"deriveThemeClassVerdict");af=["*.ts","*.tsx","*.js","*.jsx"],TS=15e5;o(Qo,"isScannableSource");o(cf,"listTracked");o(At,"checkThemeClassDrift");o(RS,"baselineFindings");o(lf,"listTrackedAt");o(AS,"matchesSourcePattern");o(IS,"resolveBaseRef");o(qo,"safeRead")});function ea(e){return po[e].version}function Qe(e,t,n,r){return{detector_id:e,detector_version:ea(e),state:t,finding_count:n,...r?{reason:r}:{}}}function j(e,t,n){return{summary:Qe(e,t,0,n),findings:[]}}function yf(e){return e==="open"||e==="warn"||e==="info"}function NS(e){let t="det_number_collisions";if(!e.ok)return j(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return j(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return j(t,"not_applicable","no numbered namespaces");if(!oo(n))return j(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let s=[];for(let i of r){if(!yf(i.status))continue;let{level:a,baseline:c}=tn(i.status);s.push({detector_id:t,rule_id:fo,level:a,baseline:c,evidence:[...i.ownPath?[i.ownPath]:[],...i.sightings.map(l=>l.path)],title:i.title})}return{summary:Qe(t,"ran",s.length),findings:s}}function OS(e){let t="det_spec_drift";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return j(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return j(t,"not_applicable",n.reason??"no opinion");if(!vo(n))return j(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let s of n.findings){if(!yf(s.status))continue;let{level:i,baseline:a}=tn(s.status,{excepted:s.exceptionReason!==void 0});r.push({detector_id:t,rule_id:go(s.dimension),level:i,baseline:a,evidence:[s.id],title:s.title})}return{summary:Qe(t,"ran",r.length),findings:r}}function DS(e){let t="det_theme_class_drift";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return j(t,"not_applicable","no theme tokens");if(!Yo(n))return j(t,"ungraded","no merge-base to grade against");let r=[];for(let s of n.findings){let{level:i,baseline:a}=tn(s.status);r.push({detector_id:t,rule_id:mo,level:i,baseline:a,evidence:[s.file,s.klass,s.token],title:`${s.klass} in ${s.file} \u2014 token ${s.token} does not exist`})}return{summary:Qe(t,"ran",r.length),findings:r}}function PS(e){let t="det_table_acl_lint";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return j(t,"not_applicable","no supabase migrations");if(!Vo(n))return j(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let s of n.findings){let{level:i,baseline:a}=tn(s.status);r.push({detector_id:t,rule_id:ho,level:i,baseline:a,evidence:[s.project,s.table,...s.missing],title:s.title})}return{summary:Qe(t,"ran",r.length),findings:r}}function MS(e){let t="det_changelog_duplicates";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return j(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return j(t,"ungraded","no base ref to grade against");let r=n.findings.map(s=>({detector_id:t,rule_id:"changelog.duplicate_heading",level:s.level,baseline:s.level==="open"?"introduced":"pre_existing",evidence:[s.path,s.version],title:s.title}));return{summary:Qe(t,"ran",r.length),findings:r}}function LS(e){let t="det_workflow_yaml";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return j(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return j(t,"ungraded","no base ref to grade against");let r=n.findings.map(s=>({detector_id:t,rule_id:"workflow.unparsable_yaml",level:s.level,baseline:s.level==="open"?"introduced":"pre_existing",evidence:[s.path,String(s.line)],title:s.title}));return{summary:Qe(t,"ran",r.length),findings:r}}function $S(e){let t="det_release_claims";if(!e.ok)return j(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.packages.length>0&&!n.facts.registryReachable?j(t,"ungraded",n.reason??"registry unreachable"):j(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(s=>({detector_id:t,rule_id:s.rule,level:s.level,baseline:"introduced",evidence:[s.package,s.version],title:s.title}));return{summary:Qe(t,"ran",r.length),findings:r}}function ta(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||Os[e.level]-Os[t.level]||mf[e.baseline]-mf[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function hf(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function FS(e){let t=new Map,n=new Map;for(let s of e)if(s.baseline==="introduced"){let i=Xn(s.evidence),a=`${s.detector_id}|${s.rule_id}|${s.level}|${i}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:s.detector_id,detector_version:ea(s.detector_id),rule_id:s.rule_id,level:s.level,baseline:"introduced",evidence_hash:i,count:1})}else{let i=`${s.detector_id}|${s.rule_id}`,a=n.get(i);a?(a.evidence.push(...s.evidence),a.count+=1,Os[s.level]<Os[a.level]&&(a.level=s.level)):n.set(i,{detector_id:s.detector_id,rule_id:s.rule_id,level:s.level,evidence:[...s.evidence],count:1})}let r=[...t.values()];for(let s of n.values())r.push({detector_id:s.detector_id,detector_version:ea(s.detector_id),rule_id:s.rule_id,level:s.level,baseline:"pre_existing",evidence_hash:Xn(s.evidence),count:s.count});return r.sort(ta)}function jS(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 mn(e){let t={det_number_collisions:NS(e.number),det_spec_drift:OS(e.spec),det_theme_class_drift:DS(e.theme),det_table_acl_lint:PS(e.acl),det_changelog_duplicates:MS(e.changelog),det_workflow_yaml:LS(e.workflow),det_release_claims:$S(e.release)},n=ff.map(l=>t[l].summary),r=ff.flatMap(l=>t[l].findings),s=FS(r),i=[...s].sort((l,d)=>hf(l)-hf(d)||ta(l,d)).slice(0,gf).sort(ta),a=s.length-i.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Xn(l.evidence),title:l.title}));return{findings:i,coverage:jS(n,a),engines:n,local:c,truncated:a}}function lr(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e},changelog:{ok:!1,error:e},workflow:{ok:!1,error:e},release:{ok:!1,error:e}}}function _f(e){return e instanceof Error?e.message:String(e)}async function It(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:_f(t)}}}async function na(e,t={}){let n={...CS,...t.engines};try{if(R(e,["rev-parse","--is-inside-work-tree"])?.trim()!=="true")return mn(lr("not a git work tree"));let s=t.baseRef,i={number:await It(()=>n.number(e,{...s?{baseRef:s}:{},...t.includeWorktrees===void 0?{}:{includeWorktrees:t.includeWorktrees}})),spec:await It(()=>n.spec(e,s?{baseRef:s}:{})),theme:await It(()=>n.theme(e,s?{baseRef:s}:{})),acl:await It(()=>n.acl(e,s?{baseRef:s}:{})),changelog:await It(()=>n.changelog(e,s?{baseRef:s}:{})),workflow:await It(()=>n.workflow(e,s?{baseRef:s}:{})),release:await It(()=>n.release(e,s?{baseRef:s}:{}))};return mn(i)}catch(r){return mn(lr(`detector adapter failed: ${_f(r)}`))}}var gf,CS,ff,Os,mf,ra=b(()=>{"use strict";re();yo();Jn();Qn();Uo();Go();As();Cs();Ns();gf=64,CS={number:o((e,t)=>ct(e,t),"number"),spec:o((e,t)=>dt(e,t),"spec"),theme:o((e,t)=>At(e,t),"theme"),acl:o((e,t)=>Rt(e,t),"acl"),changelog:o((e,t)=>$o(e,t),"changelog"),workflow:o((e,t)=>Ho(e,t),"workflow"),release:o((e,t)=>jo(e,t),"release")},ff=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint","det_changelog_duplicates","det_workflow_yaml","det_release_claims"];o(ea,"versionOf");o(Qe,"summary");o(j,"noFindings");o(yf,"isFindingStatus");o(NS,"adaptNumber");o(OS,"adaptSpec");o(DS,"adaptTheme");o(PS,"adaptAcl");o(MS,"adaptChangelog");o(LS,"adaptWorkflow");o($S,"adaptRelease");Os={open:0,warn:1,info:2},mf={introduced:0,pre_existing:1};o(ta,"compareWire");o(hf,"capPriority");o(FS,"buildWire");o(jS,"deriveCoverage");o(mn,"adaptDetectorReports");o(lr,"unavailableDetectorReports");o(_f,"errorText");o(It,"attempt");o(na,"runRepoHealthDetectors")});var bf,sa=b(()=>{"use strict";bf=[{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 wf(e){let t=new Set;for(let[n,r]of e.paths)for(let s of bf){if(t.has(s.flag)||!s.path.test(n)||s.onlyWhenAdded&&r!=="added")continue;if(!s.content){t.add(s.flag);continue}let i=US(n,e);i!==null&&s.content.test(i)&&t.add(s.flag)}return[...t].sort()}function US(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
38
|
-
`):t.readUntracked(e)}var
|
|
26
|
+
`)}function zo(e){let t=Vo(e.tokens),n=[];for(let{path:r,content:s}of e.sources){let i=Dp(s),a=new Set;for(let c of i.matchAll(Sk)){let l=c[2],d=l.split("-")[0];if(!t.has(d)||e.tokens.has(l))continue;let u=`${c[1]}-${l}`;a.has(u)||(a.add(u),n.push({file:r,klass:u,token:l,namespace:d}))}}return n}function Rp(e){return`${e.file} ${e.klass}`}function xk(e,t){let n=t===null?null:new Set(t.map(Rp));return e.map(r=>({...r,status:n!==null&&n.has(Rp(r))?"info":"open"}))}function Pp(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function qo(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Cp(e,t){let n=T(e,["ls-files","--",...t]);return n===null?[]:n.split(`
|
|
27
|
+
`).filter(Boolean)}function At(e,t={}){let n=t.maxFileBytes??Ek,r=new Set;for(let u of Cp(e,["*.css"])){let p=Wo(Go(e,u),n);if(p!==null)for(let m of Ko(p))r.add(m)}if(r.size===0)return{ok:!1,verdict:"no_opinion",tokenCount:0,namespaceCount:0,findings:[],scannedFiles:0,graded:!1,baseRef:null};let s=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(u=>Ip.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):Ip,i=[];for(let u of Cp(e,s)){if(!qo(u))continue;let p=Wo(Go(e,u),n);p!==null&&i.push({path:u,content:p})}let a=zo({tokens:r,sources:i}),c=t.includeBaseline===!1?null:Ak(e,s,n,t.baseRef),l=xk(a,c?.findings??null),d=Pp(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:Vo(r).size,findings:l,scannedFiles:i.length,graded:c!==null,baseRef:c?.mergeBase??null}}function Ak(e,t,n,r){let s=r??Rk(e);if(s===null)return null;let i=T(e,["merge-base",s,"HEAD"])?.trim();if(!i)return null;let a=T(e,["diff","--name-only","--no-renames",i]);if(a===null)return null;let c=new Set(a.split(`
|
|
28
|
+
`).filter(Boolean)),l=o(p=>c.has(p)?T(e,["show",`${i}:${p}`]):Wo(Go(e,p),n),"atBase"),d=new Set;for(let p of Np(e,i,["*.css"])){let m=l(p);if(m!==null)for(let h of Ko(m))d.add(h)}if(d.size===0)return{findings:[],mergeBase:i};let u=[];for(let p of Np(e,i,t)){if(!qo(p))continue;let m=l(p);m===null||m.length>n||u.push({path:p,content:m})}return{findings:zo({tokens:d,sources:u}),mergeBase:i}}function Np(e,t,n){let r=T(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
|
|
29
|
+
`).filter(s=>s.length>0&&n.some(i=>Tk(s,i)))}function Tk(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),s=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(s!==""&&!e.startsWith(s+"/"))return!1;let i=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?i.endsWith(r.slice(1)):i===r}function Rk(e){let t=T(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(s=>T(e,["rev-parse","--verify","--quiet",`origin/${s}`])!==null);return r?`origin/${r}`:null}function Wo(e,t){try{let n=vk(e,"utf8");return n.length>t?null:n}catch{return null}}var Op,kk,Sk,Ip,Ek,ys=b(()=>{"use strict";ie();o(Bo,"isThemeClassDriftGraded");Op=["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"],kk=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,Sk=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Op.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");o(Ko,"extractTokens");o(Vo,"deriveNamespaces");o(Dp,"stripCommentLines");o(zo,"evaluateThemeClasses");o(Rp,"findingKey");o(xk,"gradeAgainstBaseline");o(Pp,"deriveThemeClassVerdict");Ip=["*.ts","*.tsx","*.js","*.jsx"],Ek=15e5;o(qo,"isScannableSource");o(Cp,"listTracked");o(At,"checkThemeClassDrift");o(Ak,"baselineFindings");o(Np,"listTrackedAt");o(Tk,"matchesSourcePattern");o(Rk,"resolveBaseRef");o(Wo,"safeRead")});function Yo(e){return ro[e].version}function Fe(e,t,n,r){return{detector_id:e,detector_version:Yo(e),state:t,finding_count:n,...r?{reason:r}:{}}}function F(e,t,n){return{summary:Fe(e,t,0,n),findings:[]}}function jp(e){return e==="open"||e==="warn"||e==="info"}function Ck(e){let t="det_number_collisions";if(!e.ok)return F(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return F(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return F(t,"not_applicable","no numbered namespaces");if(!Ji(n))return F(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let s=[];for(let i of r){if(!jp(i.status))continue;let{level:a,baseline:c}=Zt(i.status);s.push({detector_id:t,rule_id:so,level:a,baseline:c,evidence:[...i.ownPath?[i.ownPath]:[],...i.sightings.map(l=>l.path)],title:i.title})}return{summary:Fe(t,"ran",s.length),findings:s}}function Nk(e){let t="det_spec_drift";if(!e.ok)return F(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return F(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return F(t,"not_applicable",n.reason??"no opinion");if(!fo(n))return F(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let s of n.findings){if(!jp(s.status))continue;let{level:i,baseline:a}=Zt(s.status,{excepted:s.exceptionReason!==void 0});r.push({detector_id:t,rule_id:ao(s.dimension),level:i,baseline:a,evidence:[s.id],title:s.title})}return{summary:Fe(t,"ran",r.length),findings:r}}function Ok(e){let t="det_theme_class_drift";if(!e.ok)return F(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return F(t,"not_applicable","no theme tokens");if(!Bo(n))return F(t,"ungraded","no merge-base to grade against");let r=[];for(let s of n.findings){let{level:i,baseline:a}=Zt(s.status);r.push({detector_id:t,rule_id:io,level:i,baseline:a,evidence:[s.file,s.klass,s.token],title:`${s.klass} in ${s.file} \u2014 token ${s.token} does not exist`})}return{summary:Fe(t,"ran",r.length),findings:r}}function Dk(e){let t="det_table_acl_lint";if(!e.ok)return F(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return F(t,"not_applicable","no supabase migrations");if(!Ho(n))return F(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let s of n.findings){let{level:i,baseline:a}=Zt(s.status);r.push({detector_id:t,rule_id:oo,level:i,baseline:a,evidence:[s.project,s.table,...s.missing],title:s.title})}return{summary:Fe(t,"ran",r.length),findings:r}}function Pk(e){let t="det_changelog_duplicates";if(!e.ok)return F(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return F(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return F(t,"ungraded","no base ref to grade against");let r=n.findings.map(s=>({detector_id:t,rule_id:"changelog.duplicate_heading",level:s.level,baseline:s.level==="open"?"introduced":"pre_existing",evidence:[s.path,s.version],title:s.title}));return{summary:Fe(t,"ran",r.length),findings:r}}function Mk(e){let t="det_workflow_yaml";if(!e.ok)return F(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return F(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return F(t,"ungraded","no base ref to grade against");let r=n.findings.map(s=>({detector_id:t,rule_id:"workflow.unparsable_yaml",level:s.level,baseline:s.level==="open"?"introduced":"pre_existing",evidence:[s.path,String(s.line)],title:s.title}));return{summary:Fe(t,"ran",r.length),findings:r}}function $k(e){let t="det_release_claims";if(!e.ok)return F(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.packages.length>0&&!n.facts.registryReachable?F(t,"ungraded",n.reason??"registry unreachable"):F(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(s=>({detector_id:t,rule_id:s.rule,level:s.level,baseline:"introduced",evidence:[s.package,s.version],title:s.title}));return{summary:Fe(t,"ran",r.length),findings:r}}function Lk(e){let t="det_agent_doc_prose";if(!e.ok)return F(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.files.length>0&&n.facts.baseRef===null?F(t,"ungraded",n.reason??"no base ref to grade against"):F(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(s=>({detector_id:t,rule_id:"agentdoc.added_prose",level:s.level,baseline:"introduced",evidence:[s.path,...s.sample,String(s.netLines)],title:s.title}));return{summary:Fe(t,"ran",r.length),findings:r}}function Jo(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||_s[e.level]-_s[t.level]||$p[e.baseline]-$p[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Lp(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function Fk(e){let t=new Map,n=new Map;for(let s of e)if(s.baseline==="introduced"){let i=Jn(s.evidence),a=`${s.detector_id}|${s.rule_id}|${s.level}|${i}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:s.detector_id,detector_version:Yo(s.detector_id),rule_id:s.rule_id,level:s.level,baseline:"introduced",evidence_hash:i,count:1})}else{let i=`${s.detector_id}|${s.rule_id}`,a=n.get(i);a?(a.evidence.push(...s.evidence),a.count+=1,_s[s.level]<_s[a.level]&&(a.level=s.level)):n.set(i,{detector_id:s.detector_id,rule_id:s.rule_id,level:s.level,evidence:[...s.evidence],count:1})}let r=[...t.values()];for(let s of n.values())r.push({detector_id:s.detector_id,detector_version:Yo(s.detector_id),rule_id:s.rule_id,level:s.level,baseline:"pre_existing",evidence_hash:Jn(s.evidence),count:s.count});return r.sort(Jo)}function jk(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 un(e){let t={det_number_collisions:Ck(e.number),det_spec_drift:Nk(e.spec),det_theme_class_drift:Ok(e.theme),det_table_acl_lint:Dk(e.acl),det_changelog_duplicates:Pk(e.changelog),det_workflow_yaml:Mk(e.workflow),det_release_claims:$k(e.release),det_agent_doc_prose:Lk(e.agentDoc)},n=Mp.map(l=>t[l].summary),r=Mp.flatMap(l=>t[l].findings),s=Fk(r),i=[...s].sort((l,d)=>Lp(l)-Lp(d)||Jo(l,d)).slice(0,Fp).sort(Jo),a=s.length-i.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Jn(l.evidence),title:l.title}));return{findings:i,coverage:jk(n,a),engines:n,local:c,truncated:a}}function cr(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e},changelog:{ok:!1,error:e},workflow:{ok:!1,error:e},release:{ok:!1,error:e},agentDoc:{ok:!1,error:e}}}function Up(e){return e instanceof Error?e.message:String(e)}async function Xe(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:Up(t)}}}async function Xo(e,t={}){let n={...Ik,...t.engines};try{if(T(e,["rev-parse","--is-inside-work-tree"])?.trim()!=="true")return un(cr("not a git work tree"));let s=t.baseRef,i={number:await Xe(()=>n.number(e,{...s?{baseRef:s}:{},...t.includeWorktrees===void 0?{}:{includeWorktrees:t.includeWorktrees}})),spec:await Xe(()=>n.spec(e,s?{baseRef:s}:{})),theme:await Xe(()=>n.theme(e,s?{baseRef:s}:{})),acl:await Xe(()=>n.acl(e,s?{baseRef:s}:{})),changelog:await Xe(()=>n.changelog(e,s?{baseRef:s}:{})),workflow:await Xe(()=>n.workflow(e,s?{baseRef:s}:{})),release:await Xe(()=>n.release(e,s?{baseRef:s}:{})),agentDoc:await Xe(()=>n.agentDoc(e,s?{baseRef:s}:{}))};return un(i)}catch(r){return un(cr(`detector adapter failed: ${Up(r)}`))}}var Fp,Ik,Mp,_s,$p,Zo=b(()=>{"use strict";ie();co();Yn();Zn();Oo();Mo();Lo();ms();gs();ys();Fp=64,Ik={number:o((e,t)=>ot(e,t),"number"),spec:o((e,t)=>ct(e,t),"spec"),theme:o((e,t)=>At(e,t),"theme"),acl:o((e,t)=>Et(e,t),"acl"),changelog:o((e,t)=>Io(e,t),"changelog"),workflow:o((e,t)=>$o(e,t),"workflow"),release:o((e,t)=>No(e,t),"release"),agentDoc:o((e,t)=>Po(e,t),"agentDoc")},Mp=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint","det_changelog_duplicates","det_workflow_yaml","det_release_claims","det_agent_doc_prose"];o(Yo,"versionOf");o(Fe,"summary");o(F,"noFindings");o(jp,"isFindingStatus");o(Ck,"adaptNumber");o(Nk,"adaptSpec");o(Ok,"adaptTheme");o(Dk,"adaptAcl");o(Pk,"adaptChangelog");o(Mk,"adaptWorkflow");o($k,"adaptRelease");o(Lk,"adaptAgentDoc");_s={open:0,warn:1,info:2},$p={introduced:0,pre_existing:1};o(Jo,"compareWire");o(Lp,"capPriority");o(Fk,"buildWire");o(jk,"deriveCoverage");o(un,"adaptDetectorReports");o(cr,"unavailableDetectorReports");o(Up,"errorText");o(Xe,"attempt");o(Xo,"runRepoHealthDetectors")});var Hp,Qo=b(()=>{"use strict";Hp=[{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 Gp(e){let t=new Set;for(let[n,r]of e.paths)for(let s of Hp){if(t.has(s.flag)||!s.path.test(n)||s.onlyWhenAdded&&r!=="added")continue;if(!s.content){t.add(s.flag);continue}let i=Uk(n,e);i!==null&&s.content.test(i)&&t.add(s.flag)}return[...t].sort()}function Uk(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
30
|
+
`):t.readUntracked(e)}var Wp=b(()=>{"use strict";Qo();o(Gp,"scanRiskFlags");o(Uk,"contentForPath")});var pn,Bp,fn,mn,ea,bs,ws,vs,ta,Kp,lr=b(()=>{"use strict";pn="1",Bp=`
|
|
39
31
|
CREATE TABLE IF NOT EXISTS meta (
|
|
40
32
|
key TEXT PRIMARY KEY,
|
|
41
33
|
value TEXT NOT NULL
|
|
@@ -94,7 +86,23 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
94
86
|
vec BLOB NOT NULL,
|
|
95
87
|
content_hash TEXT NOT NULL
|
|
96
88
|
);
|
|
97
|
-
`,gn="schema_version",yn="last_index_commit",ia="last_indexed_at",Ds="embed_recipe_version",Ps="embed_model",Ms="embed_dim",oa="last_synced_at",Sf="last_synced_commit"});function aa(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 xf(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let s of aa(e.name))t.add(s);for(let s of aa(e.qualifiedName))t.add(s);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function Ef(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 s of aa(r))t.add(s)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var ca=b(()=>{"use strict";o(aa,"splitIdentifier");o(xf,"buildSearchText");o(Ef,"toFtsMatchQuery")});import{readFileSync as Tf}from"node:fs";import{posix as Rf}from"node:path";function Af(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 Ct(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function If(e){return e==="added"?0:e==="modified"?1:2}function HS(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 s=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(s+=l-c+1)}let i=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return s>0||i?{...e,change:"modified",changedLineCount:s,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var ur,la=b(()=>{"use strict";$l();Wi();jl();Gl();re();td();zi();ro();Jn();ra();Qn();vf();dr();ca();ur=class{static{o(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(gn),s=await this.store.countFiles()>0;(t.full||s&&r!==hn)&&await this.wipe();let i=ql(this.repoRoot),a=new Set(i.map(g=>g.path)),c=await this.store.getAllFiles(),l=new Map(c.map(g=>[g.path,g])),d=c.length>0&&!t.full,u={filesScanned:i.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:d};for(let g of c)a.has(g.path)||(await this.store.deleteFile(g.path),u.filesDeleted++);let p=[],m=0;for(let g of i){m++;let y=Xl(this.repoRoot,g.path);if(!y){u.filesSkipped++;continue}let _=l.get(g.path);if(_&&_.mtimeMs===y.mtimeMs&&_.size===y.size){u.filesSkipped++;continue}let w=this.readRepoFile(g.path);if(w===null){u.filesSkipped++;continue}let k=rs(w);if(_&&_.contentHash===k){await this.store.upsertFile({..._,mtimeMs:y.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let x=await this.parser.parse(g.path,w,g.language),S=new Map;for(let L of x.nodes)S.set(L.nodeKey,xf(L));let I={path:g.path,language:g.language,contentHash:k,mtimeMs:y.mtimeMs,size:y.size,indexedAt:n};await this.store.replaceFileNodes(I,x.nodes,S),p.push(x),u.filesParsed++,t.onProgress?.({path:g.path,done:m,total:i.length})}if(p.length>0){let g=await this.store.getNameIndex(),y=Ul(g);for(let _ of p){let w=Hl(_,y);await this.store.replaceOutgoingEdges(w.srcKeys,w.edges)}}if(this.embedder&&t.embed){let g=await this.store.getNodesByKinds([...Gi]),y=await this.store.getEmbeddingContentHashes(),_=[];for(let k of g){let x=Ll(k),S=rs(`${this.embedder.recipeVersion}\0${x}`);y.get(k.nodeKey)!==S&&_.push({nodeKey:k.nodeKey,text:x,hash:S})}let w=64;for(let k=0;k<_.length;k+=w){let x=_.slice(k,k+w),S=await this.embedder.embedDocuments(x.map(L=>L.text));await this.store.upsertEmbeddings(x.map((L,U)=>({nodeKey:L.nodeKey,dim:this.embedder.dim,vec:S[U],contentHash:L.hash})));let I=Math.min(k+w,_.length);t.onProgress?.({path:"embedding symbols",done:I,total:_.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Ds,this.embedder.recipeVersion),await this.store.setMeta(Ps,this.embedder.model),await this.store.setMeta(Ms,String(this.embedder.dim))}await this.store.setMeta(gn,hn),await this.store.setMeta(ia,String(n));let h=Vn(this.repoRoot);return h&&await this.store.setMeta(yn,h),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(t.now??Date.now())-n,u}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let i of n)r[i.language]=i.count;let s=await this.store.getMeta(ia);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:s?Number(s):null,lastIndexCommit:await this.store.getMeta(yn),schemaVersion:await this.store.getMeta(gn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Ct(n.limit,20,100),s=await this.store.searchFts(t,n.kind??null,r),i=[];for(let a of s){let c=await this.store.getNode(a.nodeKey);c&&i.push({...Af(c),score:a.score})}return i}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Ct(n.limit,20,100),s=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:Fl(s,l.vec)})).sort((l,d)=>d.score-l.score).slice(0,r),c=[];for(let l of a){let d=await this.store.getNode(l.nodeKey);d&&c.push({...Af(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",s=Ct(n.maxDepth,3,5),i=Ct(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<s&&u.length>0;p++){let m=[];for(let h of u){let g=await this.store.neighbors(h,r,a,i);for(let y of g){let _=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(_))continue;if(l.add(_),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=i)return c;let w=r==="out"?y.dstKey:y.srcKey;d.has(w)||(d.add(w),m.push(w))}}u=m}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=Tf(Rf.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(),s={};for(let a of n)s[a.kind]=a.count;let i={};for(let a of r)i[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:s,languageDistribution:i,topModules:await this.store.topModulesByFanIn(Ct(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=Jl(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Ct(t.limit,64,200),s=[],i=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&i++,s.push(...c)}return s.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:i,symbols:s.slice(0,r),truncated:s.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=ns(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(Vn(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return od(this.repoRoot,n,t)}async checkDivergence(t={}){return qn(this.repoRoot,t)}async checkNumberCollisions(t={}){return ct(this.repoRoot,t)}async checkNumberForPath(t,n={}){return lt(this.repoRoot,t,n)}async checkSpecDrift(t={}){return dt(this.repoRoot,t)}async reviewDetectors(t={}){return na(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=ns(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=ed(this.repoRoot,t),s=r?.files??new Map,i=r?.coverage??"none",a=wf({paths:n,hunks:s,readUntracked:o(m=>this.readRepoFileHead(m,Ql),"readUntracked")}),c=zl(n.keys()),l=Ct(t.limit,64,200),d=[],u=0,p=0;for(let m of c){let h=await this.store.getNodesByFile(m.path);if(h.length===0)continue;u++;let g=await this.store.getFile(m.path),y=this.readRepoFile(m.path),_=g!==null&&y!==null&&rs(y)!==g.contentHash;_&&(p++,i==="full"&&(i="partial"));let w=n.get(m.path)??"modified",k=s.get(m.path);for(let x of h)d.push(HS(x,w,k,_))}return d.sort((m,h)=>If(m.change)-If(h.change)||m.filePath.localeCompare(h.filePath)||m.startLine-h.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:i,baseKind:t.since?"ref":"uncommitted",headSha:Vn(this.repoRoot),dirty:Zl(this.repoRoot),baseSha:t.since?ss(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 Tf(Rf.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};o(Af,"toHit");o(Ct,"clampLimit");o(If,"changeRank");o(HS,"classifyReviewSymbol")});import{createRequire as GS}from"node:module";function Nf(){return Cf("node:sqlite")}function _n(){if(pr)return pr;try{let{DatabaseSync:e}=Nf(),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(),pr={ok:!0}}finally{t.close()}}catch(e){pr={ok:!1,reason:e instanceof Error?e.message:String(e)}}return pr}function WS(e){let{DatabaseSync:t}=Nf(),n=new t(e);return{prepare:o(r=>n.prepare(r),"prepare"),exec:o(r=>n.exec(r),"exec"),close:o(()=>n.close(),"close"),transaction:o(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(s){try{n.exec("ROLLBACK")}catch{}throw s}},"transaction")}}function BS(e){let t=Cf("better-sqlite3"),n=new t(e);return{prepare:o(r=>n.prepare(r),"prepare"),exec:o(r=>{n.exec(r)},"exec"),close:o(()=>{n.close()},"close"),transaction:o(r=>n.transaction(r),"transaction")}}function KS(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Ls(e){let t=KS(),n=o(s=>{let i=s==="node:sqlite"?WS(e):BS(e);return i.exec("PRAGMA journal_mode = WAL"),i.exec("PRAGMA foreign_keys = ON"),{db:i,backend:s}},"openAs");if(t==="builtin"){let s=_n();if(!s.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${s.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=_n();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${i})`)}}var Cf,pr,da=b(()=>{"use strict";Cf=GS(import.meta.url);o(Nf,"loadBuiltin");pr=null;o(_n,"probeBuiltinSqlite");o(WS,"openBuiltin");o(BS,"openBetter");o(KS,"backendOverride");o(Ls,"openSqliteDatabase")});function $s(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 Of,fr,Df=b(()=>{"use strict";da();dr();ca();o($s,"toNodeRow");Of=400,fr=class{static{o(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Ls(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(kf)}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 i=this.insertNodeStmt(),a=this.insertFtsStmt();for(let c of n)i.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 s=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)s.run(a);let i=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)i.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?$s(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map($s)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map($s)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map($s)}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 s of t){let i=Buffer.from(s.vec.buffer,s.vec.byteOffset,s.vec.byteLength);n.run(s.nodeKey,s.dim,i,s.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 s=Ef(t);if(!s)return[];let i=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
89
|
+
`,fn="schema_version",mn="last_index_commit",ea="last_indexed_at",bs="embed_recipe_version",ws="embed_model",vs="embed_dim",ta="last_synced_at",Kp="last_synced_commit"});function na(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 Vp(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let s of na(e.name))t.add(s);for(let s of na(e.qualifiedName))t.add(s);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function zp(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 s of na(r))t.add(s)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var ra=b(()=>{"use strict";o(na,"splitIdentifier");o(Vp,"buildSearchText");o(zp,"toFtsMatchQuery")});import{readFileSync as qp}from"node:fs";import{posix as Yp}from"node:path";function Jp(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 Tt(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function Xp(e){return e==="added"?0:e==="modified"?1:2}function Hk(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 s=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(s+=l-c+1)}let i=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return s>0||i?{...e,change:"modified",changedLineCount:s,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var dr,sa=b(()=>{"use strict";Qc();Oi();tl();sl();ie();yl();Li();zi();Yn();Zo();Zn();Wp();lr();ra();dr=class{static{o(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(fn),s=await this.store.countFiles()>0;(t.full||s&&r!==pn)&&await this.wipe();let i=dl(this.repoRoot),a=new Set(i.map(g=>g.path)),c=await this.store.getAllFiles(),l=new Map(c.map(g=>[g.path,g])),d=c.length>0&&!t.full,u={filesScanned:i.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:d};for(let g of c)a.has(g.path)||(await this.store.deleteFile(g.path),u.filesDeleted++);let p=[],m=0;for(let g of i){m++;let y=fl(this.repoRoot,g.path);if(!y){u.filesSkipped++;continue}let _=l.get(g.path);if(_&&_.mtimeMs===y.mtimeMs&&_.size===y.size){u.filesSkipped++;continue}let w=this.readRepoFile(g.path);if(w===null){u.filesSkipped++;continue}let k=Wr(w);if(_&&_.contentHash===k){await this.store.upsertFile({..._,mtimeMs:y.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let x=await this.parser.parse(g.path,w,g.language),S=new Map;for(let $ of x.nodes)S.set($.nodeKey,Vp($));let I={path:g.path,language:g.language,contentHash:k,mtimeMs:y.mtimeMs,size:y.size,indexedAt:n};await this.store.replaceFileNodes(I,x.nodes,S),p.push(x),u.filesParsed++,t.onProgress?.({path:g.path,done:m,total:i.length})}if(p.length>0){let g=await this.store.getNameIndex(),y=nl(g);for(let _ of p){let w=rl(_,y);await this.store.replaceOutgoingEdges(w.srcKeys,w.edges)}}if(this.embedder&&t.embed){let g=await this.store.getNodesByKinds([...Ni]),y=await this.store.getEmbeddingContentHashes(),_=[];for(let k of g){let x=Zc(k),S=Wr(`${this.embedder.recipeVersion}\0${x}`);y.get(k.nodeKey)!==S&&_.push({nodeKey:k.nodeKey,text:x,hash:S})}let w=64;for(let k=0;k<_.length;k+=w){let x=_.slice(k,k+w),S=await this.embedder.embedDocuments(x.map($=>$.text));await this.store.upsertEmbeddings(x.map(($,U)=>({nodeKey:$.nodeKey,dim:this.embedder.dim,vec:S[U],contentHash:$.hash})));let I=Math.min(k+w,_.length);t.onProgress?.({path:"embedding symbols",done:I,total:_.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(bs,this.embedder.recipeVersion),await this.store.setMeta(ws,this.embedder.model),await this.store.setMeta(vs,String(this.embedder.dim))}await this.store.setMeta(fn,pn),await this.store.setMeta(ea,String(n));let h=Kn(this.repoRoot);return h&&await this.store.setMeta(mn,h),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(t.now??Date.now())-n,u}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let i of n)r[i.language]=i.count;let s=await this.store.getMeta(ea);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:s?Number(s):null,lastIndexCommit:await this.store.getMeta(mn),schemaVersion:await this.store.getMeta(fn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Tt(n.limit,20,100),s=await this.store.searchFts(t,n.kind??null,r),i=[];for(let a of s){let c=await this.store.getNode(a.nodeKey);c&&i.push({...Jp(c),score:a.score})}return i}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Tt(n.limit,20,100),s=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:el(s,l.vec)})).sort((l,d)=>d.score-l.score).slice(0,r),c=[];for(let l of a){let d=await this.store.getNode(l.nodeKey);d&&c.push({...Jp(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",s=Tt(n.maxDepth,3,5),i=Tt(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<s&&u.length>0;p++){let m=[];for(let h of u){let g=await this.store.neighbors(h,r,a,i);for(let y of g){let _=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(_))continue;if(l.add(_),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=i)return c;let w=r==="out"?y.dstKey:y.srcKey;d.has(w)||(d.add(w),m.push(w))}}u=m}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=qp(Yp.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(),s={};for(let a of n)s[a.kind]=a.count;let i={};for(let a of r)i[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:s,languageDistribution:i,topModules:await this.store.topModulesByFanIn(Tt(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=pl(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=Tt(t.limit,64,200),s=[],i=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&i++,s.push(...c)}return s.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:i,symbols:s.slice(0,r),truncated:s.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Gr(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(Kn(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return kl(this.repoRoot,n,t)}async checkDivergence(t={}){return zn(this.repoRoot,t)}async checkNumberCollisions(t={}){return ot(this.repoRoot,t)}async checkNumberForPath(t,n={}){return at(this.repoRoot,t,n)}async checkSpecDrift(t={}){return ct(this.repoRoot,t)}async reviewDetectors(t={}){return Xo(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Gr(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=gl(this.repoRoot,t),s=r?.files??new Map,i=r?.coverage??"none",a=Gp({paths:n,hunks:s,readUntracked:o(m=>this.readRepoFileHead(m,hl),"readUntracked")}),c=ll(n.keys()),l=Tt(t.limit,64,200),d=[],u=0,p=0;for(let m of c){let h=await this.store.getNodesByFile(m.path);if(h.length===0)continue;u++;let g=await this.store.getFile(m.path),y=this.readRepoFile(m.path),_=g!==null&&y!==null&&Wr(y)!==g.contentHash;_&&(p++,i==="full"&&(i="partial"));let w=n.get(m.path)??"modified",k=s.get(m.path);for(let x of h)d.push(Hk(x,w,k,_))}return d.sort((m,h)=>Xp(m.change)-Xp(h.change)||m.filePath.localeCompare(h.filePath)||m.startLine-h.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:i,baseKind:t.since?"ref":"uncommitted",headSha:Kn(this.repoRoot),dirty:ml(this.repoRoot),baseSha:t.since?Br(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 qp(Yp.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};o(Jp,"toHit");o(Tt,"clampLimit");o(Xp,"changeRank");o(Hk,"classifyReviewSymbol")});var Zp=b(()=>{"use strict";ie()});var Gk,tM,Qp=b(()=>{"use strict";ie();Gk=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],tM=new RegExp(Gk.join("|"),"g")});import{existsSync as ia,readdirSync as Wk,readFileSync as Bk}from"node:fs";import{spawnSync as Kk}from"node:child_process";import{dirname as Vk,join as ks,posix as oa}from"node:path";function tf(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 ${aa} 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 ${aa} 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,m=r!==null&&r.ok===!1?r.detail:void 0,g={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${m?`: ${m}`:"."}`,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:g.title,detail:g.detailText,hint:g.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let s=new Set(r.versions),i=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!s.has(p)).sort(Ne);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:(e.projectRoot?`cd ${e.projectRoot} && npx supabase migration up`:"`npx supabase migration up` im Projektverzeichnis")+" (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen. Meldet der Lauf nichts Angewendetes, war es das falsche Verzeichnis ODER die Migration lief bereits \u2014 diese Pruefung sagt, was davon.",versions:a});let c=r.versions.filter(p=>!i.has(p)).sort(Ne),l=new Map,d=[];for(let p of c){let m=e.siblingVersions.get(p);if(m){let h=l.get(m)??[];h.push(p),l.set(m,h)}else d.push(p)}for(let[p,m]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${m.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${m.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:m});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${d.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:d}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),m=e.fileVersions.filter(g=>!p.has(g)).sort(Ne),h=e.remote.versions.filter(g=>!i.has(g)).sort(Ne);m.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${m.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${m.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:m}),h.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${h.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${h.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:h})}let u=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function nf(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function sf(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(`
|
|
90
|
+
`).filter(Boolean).slice(-1)[0]}}function ef(e,t,n){let r=e(t,zk,n);return r.ok===!1?sf(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
|
|
91
|
+
`).map(s=>s.trim()).filter(Boolean)}}function of(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 qk(e){let t=T(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=Vk(t);return n===e?null:n}function Yk(e,t,n){let r=oa.dirname(t),i=[{path:ks(e,r,"config.toml"),source:"worktree"}],a=qk(e);a&&i.push({path:ks(a,r,"config.toml"),source:"main_worktree"});for(let c of i)if(ia(c.path))try{let l=of(Bk(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 Jk(e,t){let n=new Map,r=T(e,["worktree","list","--porcelain"]);if(r===null)return n;let s=T(e,["rev-parse","--show-toplevel"])?.trim();for(let i of r.split(`
|
|
92
|
+
`)){if(!i.startsWith("worktree "))continue;let a=i.slice(9).trim();if(!a||a===s||!ia(a))continue;let c=ks(a,t);if(ia(c))try{for(let l of Wk(c)){let d=Yt(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function ca(e,t={}){let n=t.runPsql??rf,r=t.timeoutMs??15e3,s=[],i=it(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:s}};let a=[],c=[],l=[];for(let p of i){let m=Yk(e,p.dir,s),h=m.source==="missing"?null:ef(n,`postgresql://postgres:postgres@127.0.0.1:${m.port}/postgres`,r),g=t.remoteDbUrl!==void 0?ef(n,t.remoteDbUrl,r):null,y=tf({dir:p.dir,projectRoot:ks(e,oa.dirname(oa.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:m,ledger:h,siblingVersions:Jk(e,p.dir),remote:g});a.push(...y.findings),l.push(y.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:y.verdict,db:y.db})}let d=nf(l),u={open:0,warn:1,info:2};return a.sort((p,m)=>u[p.status]-u[m.status]||p.id.localeCompare(m.id)),{ok:d==="in_sync",verdict:d,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:s}}}var aa,rf,zk,af=b(()=>{"use strict";ie();Vn();aa=54322;o(tf,"evaluateLedgerProject");o(nf,"deriveLedgerVerdict");rf=o((e,t,n)=>{let r=Kk("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"),zk="select version from supabase_migrations.schema_migrations order by version";o(sf,"classifyLedgerError");o(ef,"readLedger");o(of,"parseDbPort");o(qk,"mainWorktreeRoot");o(Yk,"resolveConfig");o(Jk,"gatherSiblingVersions");o(ca,"checkMigrationLedgerDrift")});import{appendFileSync as Xk,existsSync as cf,mkdirSync as Zk,readFileSync as Qk}from"node:fs";import{join as eS}from"node:path";function ur(e,t={}){try{if(!cf(e)){if(!t.create)return"skipped";Zk(e,{recursive:!0})}let n=eS(e,".gitignore"),r=cf(n)?Qk(n,"utf8"):null,s=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),i=lf.filter(l=>!s.has(l));if(i.length===0)return"unchanged";let a=r===null?[...tS,...i]:i,c=r&&!r.endsWith(`
|
|
93
|
+
`)?`
|
|
94
|
+
`:"";return Xk(n,c+a.join(`
|
|
95
|
+
`)+`
|
|
96
|
+
`),r===null?"created":"appended"}catch{return"skipped"}}var lf,tS,la=b(()=>{"use strict";lf=["code-index.sqlite","code-index.sqlite-wal","code-index.sqlite-shm","index-refresh.lock","conventions-cache.json","conventions-cache.json.*.tmp","context.md","manifest.json","git-context.md","review.md","review.json","review-comment.md","run-review.md","pr-body.md","HANDOFF-*.md"],tS=["# Written by the maind tools: machine-local files that must not be committed.","# Missing lines are appended, nothing is removed \u2014 your own lines stay.",'# Never "*": this directory also holds files that ARE committed (feature.json, gates.json \u2026).'];o(ur,"ensureMaindLocalIgnore")});var df,hn=b(()=>{"use strict";Xc();sa();Li();Qo();ms();Lo();Oo();Mo();zi();Zp();Qp();Hi();Yn();ys();Zn();Vn();gs();af();co();Zo();Yn();Zn();ys();gs();Ur();Oi();lr();la();df="0.1.0"});import{execFileSync as nS}from"node:child_process";import{createHash as rS}from"node:crypto";import{mkdirSync as sS,readFileSync as iS,renameSync as oS,writeFileSync as aS}from"node:fs";import{dirname as uf,join as pf}from"node:path";function je(e=process.cwd()){try{let t=nS("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 Ss(e){return rS("sha256").update(e).digest("hex").slice(0,16)}function xs(e){return pf(e,cS)}function ff(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function mf(e,t,n,r=new Date().toISOString()){try{if(!ff(n))return;let s={version:da,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},i=xs(e);sS(uf(i),{recursive:!0}),ur(uf(i));let a=`${i}.${process.pid}.tmp`;aS(a,JSON.stringify(s,null,2),"utf8"),oS(a,i)}catch{}}function hf(e,t){try{let n=iS(xs(e),"utf8"),r=JSON.parse(n);return r.version!==da||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!ff(r.result)?null:{version:da,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function gf(e,t,n=new Date){let r=lS(t.cached_at,n),s=t.result.instructions??"",i={...t.result,instructions:`${r}
|
|
97
|
+
|
|
98
|
+
${s}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:i})}function lS(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${dS(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function dS(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,s=Math.floor(r/6e4);if(s<1)return"just now";if(s<60)return`${s} minute${s===1?"":"s"} ago`;let i=Math.floor(s/60);if(i<24)return`${i} hour${i===1?"":"s"} ago`;let a=Math.floor(i/24);return`${a} day${a===1?"":"s"} ago`}var da,cS,gn=b(()=>{"use strict";hn();da=1,cS=pf(".maind","conventions-cache.json");o(je,"resolveRepoRoot");o(Ss,"keyFingerprint");o(xs,"cachePath");o(ff,"hasInstructions");o(mf,"writeConventionsCache");o(hf,"readConventionsCache");o(gf,"buildCachedInitializeResponse");o(lS,"fallbackMarker");o(dS,"relativeAge")});import{existsSync as Is,mkdirSync as kS,readFileSync as yf,writeFileSync as fa,chmodSync as _f}from"node:fs";import{homedir as SS,hostname as xS,platform as pa,release as ES}from"node:os";import{randomUUID as AS}from"node:crypto";import{join as Rt}from"node:path";function It(){let e=SS(),t=process.env;if(pa()==="darwin")return Rt(e,"Library","Application Support","maind");if(pa()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:Rt(e,"AppData","Roaming");return Rt(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:Rt(e,".config");return Rt(n,"maind")}function bf(e){Is(e)||kS(e,{recursive:!0,mode:448})}function te(){let e=It();bf(e);let t=Rt(e,TS);if(Is(t)){let r=yf(t,"utf8").trim();if(CS(r))return r}let n=AS();fa(t,n+`
|
|
99
|
+
`,{encoding:"utf8",mode:384});try{_f(t,384)}catch{}return n}function CS(e){return IS.test(e)}function ma(){return Rt(It(),RS)}function Ct(e){let t=It();bf(t);let n=ma();fa(n,e+`
|
|
100
|
+
`,{encoding:"utf8",mode:384});try{_f(n,384)}catch{}}function B(){let e=ma();if(!Is(e))return null;let t=yf(e,"utf8").trim();return t.length>0?t:null}function fr(){let e=ma();Is(e)&&fa(e,"",{encoding:"utf8",mode:384})}function wf(){try{return`mcp-bridge-${xS()}`}catch{return"mcp-bridge"}}function Cs(e){return{os:`${pa()} ${ES()}`,ide:"mcp-bridge",ext_version:e,device_id:te()}}var TS,RS,IS,ce=b(()=>{"use strict";o(It,"configDir");o(bf,"ensureDir");TS="device-id",RS="api-key";o(te,"ensureDeviceId");IS=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;o(CS,"isUuid");o(ma,"apiKeyPath");o(Ct,"writeApiKey");o(B,"readApiKey");o(fr,"clearApiKey");o(wf,"bridgeLabel");o(Cs,"clientMeta")});function mr(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:NS}function yn(e){return`${mr()}/${e.replace(/^\/+/,"")}`}var NS,_n=b(()=>{"use strict";NS="https://fn.maind.dev/functions/v1";o(mr,"functionsOrigin");o(yn,"functionsUrl")});var H,Ze=b(()=>{"use strict";H="0.73.0"});import{execFileSync as FS}from"node:child_process";import{createHash as jS}from"node:crypto";function US(e){return jS("sha256").update(e).digest("hex")}function HS(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 ha(e){let t=HS(e);return t?US(t):null}function z(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&GS.test(e))return e;let t;try{t=FS("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?ha(t):null}var GS,Qe=b(()=>{"use strict";o(US,"sha256Hex");o(HS,"normalizeRemoteUrl");o(ha,"projectKeyFromRemote");GS=/^[a-f0-9]{64}$/;o(z,"computeProjectKey")});import BS from"node:path";import{fileURLToPath as KS}from"node:url";function VS(e,t=BS.sep){return e.split(t).includes("_npx")}function Ee(e){let t=e.extraArgs??[],n=o(r=>({command:"npx",args:["-y",Nf,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):VS(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 Ae(){try{let e=KS(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function wn(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Cf(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Cf(n)).join(" ")}function Os(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Nf)}function Ds(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Cf(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Nf,vn=b(()=>{"use strict";Nf="@maind-dev/mcp-bridge";o(VS,"isEphemeralEntry");o(Ee,"resolveBridgeLaunch");o(Ae,"currentBridgeEntry");o(wn,"launchToShellCommand");o(Os,"isNpxForm");o(Ds,"isLegacyHookForm");o(Cf,"shellQuote")});import*as ye from"node:path";function Df(e){let t=e.launch??Ee({entryPath:Ae(),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}}}function zS(e){switch(e.platform){case"darwin":return ye.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??ye.join(e.homeDir,"AppData","Roaming");return ye.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??ye.join(e.homeDir,".config");return ye.join(t,"Claude","claude_desktop_config.json")}}}function Ps(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:ye.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:ye.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:zS(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:ye.join(e.homeDir,".cursor","mcp.json"),kind:"json"},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:ye.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json"},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:ye.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}function Pf(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function Ms(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Of(e.env.XDG_CONFIG_HOME),appData:Of(e.env.APPDATA)}}function Of(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}var ga=b(()=>{"use strict";vn();o(Df,"buildMaindServerEntry");o(zS,"claudeDesktopConfigPath");o(Ps,"getClientTargets");o(Pf,"filterTargetsByFamily");o(Ms,"makeDefaultContext");o(Of,"nonEmpty")});import*as q from"node:fs/promises";import*as $s from"node:path";async function ne(e){try{return await q.readFile(e,"utf8")}catch(t){if(qS(t))return null;throw t}}async function ya(e){await q.mkdir(e,{recursive:!0})}async function Y(e,t,n){let r=$s.dirname(e);await ya(r);let s=$s.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await q.writeFile(s,t,{encoding:"utf8",mode:n});try{await q.rename(s,e)}catch(i){if(YS(i))try{await q.copyFile(s,e),await q.unlink(s).catch(()=>{}),n!==void 0&&await q.chmod(e,n).catch(()=>{});return}catch(a){throw await q.unlink(s).catch(()=>{}),a}throw await q.unlink(s).catch(()=>{}),i}}async function Mf(e,t){let n=await ne(e);return n===null?!1:n.split(/\r?\n/).some(s=>s.startsWith(t))}function qS(e){return $f(e)&&e.code==="ENOENT"}function YS(e){return!$f(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function $f(e){return typeof e=="object"&&e!==null&&"code"in e}var Ue=b(()=>{"use strict";o(ne,"readFileSafe");o(ya,"ensureDir");o(Y,"atomicWriteFile");o(Mf,"hasLinePrefix");o(qS,"isNoEnt");o(YS,"isWindowsRenameFailure");o($f,"isNodeError")});import{existsSync as px}from"node:fs";import*as Gf from"node:path";function Ot(e,t={},n=va){let r=t.fileExists??px,s=t.expectedCommand??fx,i={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);wa(a)&&(i=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=mx(i,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 d=` Replace its command with: ${s(a.subcommand)}`;if(Ds(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.`+d};if(Os(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.`+d};let u=hx(l);return u!==null&&!r(u)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${u}, which does not exist \u2014 the hook fails silently on every run.`+d}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function ka(e){return e.some(t=>t.status!=="ok")}function js(e){return e.some(t=>t.remedy==="run-install")}function fx(e){return wn(Ee({entryPath:Ae(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function mx(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let s of r){if(!wa(s))continue;let i=s.hooks;if(Array.isArray(i))for(let a of i){if(!wa(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function hx(e){for(let t of gx(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Gf.isAbsolute(t)?t:null;return null}function gx(e){let t=[],n="",r=!1;for(let s of e){if(s==="'"){r=!r;continue}if(!r&&/\s/.test(s)){n.length>0&&t.push(n),n="";continue}n+=s}return n.length>0&&t.push(n),t}function wa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var va,Fs,kn=b(()=>{"use strict";vn();va=[{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."}],Fs=[{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."}];o(Ot,"inspectHookWiring");o(ka,"hasWiringDrift");o(js,"needsInstallRun");o(fx,"defaultExpectedCommand");o(mx,"findCommand");o(hx,"extractScriptPath");o(gx,"tokenize");o(wa,"isObject")});import*as Ea from"node:path";import*as Bf from"node:readline";async function Kf(e,t){let n=Ea.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let s;try{s=await ne(n)}catch(m){return{target:r,action:"merge",status:"failed",detail:`read: ${Sa(m)}`}}let i,a="create";if(s===null||s.trim().length===0)i={};else{a="merge";try{let m=JSON.parse(s);if(!xa(m))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};i=m}catch(m){return{target:r,action:"merge",status:"failed",detail:`parse: ${Sa(m)}`}}}let c=_x(i,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 bx(e.out,`
|
|
101
|
+
Merge a ${t.event} hook into ${n}?
|
|
102
|
+
${t.consentDescription}
|
|
103
|
+
[Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:"user declined"}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},d=i.hooks?.[t.event]??[],u={...i,hooks:{...i.hooks??{},[t.event]:[...d,l]}},p=JSON.stringify(u,null,2)+`
|
|
104
|
+
`;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:n};try{await Y(n,p,384)}catch(m){return{target:r,action:"merge",status:"failed",detail:`write: ${Sa(m)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function Vf(e){let t=Ea.join(e.homeDir,Wf);return Kf(e,{event:"SessionStart",command:`cat ${t}`,timeout:5,matchPattern:/maind-session-start-reminder\.md/,targetKey:"hook:~/.claude/settings.json",skipDetail:o(()=>"SessionStart hook already references the reminder file","skipDetail"),consentDescription:`It 'cat's ${Wf} into every new Claude Code session.`})}function yx(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function Aa(e,t){let n=e.launch??Ee({entryPath:Ae(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=wn(n);return Kf(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:yx(t),skipDetail:o(s=>{let i=`${t.label} already runs maind ${t.subcommand}`;return Ds(s)?`${i}, 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}`:Os(s)?`${i}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:i},"skipDetail"),consentDescription:t.consentDescription})}async function zf(e){let t=[];for(let n of va)t.push(await Aa(e,n));return t}function _x(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let s of r){if(!xa(s))continue;let i=s.hooks;if(Array.isArray(i))for(let a of i){if(!xa(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function bx(e,t){e.write(t);let n=Bf.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(s=>{n.question("",i=>s(i.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function xa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sa(e){return e instanceof Error?e.message:String(e)}var Wf,Ta=b(()=>{"use strict";Ue();vn();kn();Wf=".claude/maind-session-start-reminder.md";o(Kf,"mergeClaudeHook");o(Vf,"mergeSessionStartHook");o(yx,"targetKeyFor");o(Aa,"mergeSubcommandHook");o(zf,"mergeAllSubcommandHooks");o(_x,"findExistingHookCommand");o(bx,"promptYesNo");o(xa,"isObject");o(Sa,"errMessage")});import{existsSync as wx,readFileSync as vx}from"node:fs";import{join as kx}from"node:path";function Ge(){return kx(It(),"config.json")}function Te(){try{let e=Ge();if(!wx(e))return null;let t=JSON.parse(vx(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 Sn=b(()=>{"use strict";ce();o(Ge,"bridgeConfigPath");o(Te,"readBridgeConfig")});function Us(){return{nodes:[],edges:[],refs:[],imports:[]}}function nt(e){return e+1}function Hs(e){return(e.text.split(`
|
|
105
|
+
`,1)[0]??"").trim().slice(0,200)}function Cx(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 Nx(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let s=Cx(r.childForFieldName("function"));s&&n.add(s)}return[...n]}function xn(e,t,n,r){for(let s of Nx(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:s})}var Gs=b(()=>{"use strict";o(Us,"newResult");o(nt,"line1");o(Hs,"signatureOf");o(Cx,"calleeName");o(Nx,"collectCallTargets");o(xn,"addCallRefs")});function nm(e,t){let n=Us();for(let r of e.namedChildren)Ox(r,t,n);return n}function rm(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function Ox(e,t,n){let r=rm(e);switch(r.type){case"import_statement":case"import_from_statement":{let i=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??Px(r);i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:i});return}case"function_definition":{let s=r.childForFieldName("name")?.text;if(!s)return;let i=Ws(r,t,s,s,"function");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&xn(n,i.nodeKey,a,tm);return}case"class_definition":Dx(r,t,n);return;case"expression_statement":{let i=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(i&&i.type==="identifier"){let a=Ws(r,t,i.text,i.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function Dx(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let s=Ws(e,t,r,r,"class");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let i=e.childForFieldName("superclasses");if(i){for(let c of i.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:s.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:s.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=rm(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=Ws(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:s.nodeKey,dstKey:p.nodeKey,kind:"contains"});let m=l.childForFieldName("body");m&&xn(n,p.nodeKey,m,tm)}}function Ws(e,t,n,r,s){return{nodeKey:Lr(t.filePath,r,s),kind:s,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:nt(e.startPosition.row),endLine:nt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Hs(e),doc:null}}function Px(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var tm,sm=b(()=>{"use strict";Bn();Gs();tm="call";o(nm,"extractPython");o(rm,"unwrapDecorated");o(Ox,"handleTopLevel");o(Dx,"addClass");o(Ws,"makeNode");o(Px,"firstDottedName")});function am(e,t){let n=Us();for(let r of e.namedChildren)$x(r,t,n);return n}function Mx(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function $x(e,t,n){let r=Mx(e);switch(r.type){case"import_statement":{let s=r.childForFieldName("source")?.text;s&&n.imports.push({fromModuleKey:t.moduleKey,specifier:Fx(s)});return}case"function_declaration":case"generator_function_declaration":{im(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{Lx(r,t,n);return}case"interface_declaration":Ra(r,t,n,"interface");return;case"type_alias_declaration":Ra(r,t,n,"type_alias");return;case"enum_declaration":Ra(r,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let s of r.namedChildren){if(s.type!=="variable_declarator")continue;let i=s.childForFieldName("name");if(!i||i.type!=="identifier")continue;let a=s.childForFieldName("value"),c=a?.type==="arrow_function"||a?.type==="function_expression"||a?.type==="function";im(s,t,n,c?"function":"variable",i,a)}return}default:return}}function im(e,t,n,r,s,i){let c=(s??e.childForFieldName("name"))?.text;if(!c)return;let l=Bs(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let d=i??e.childForFieldName("body")??e;r==="function"&&d&&xn(n,l.nodeKey,d,om)}function Ra(e,t,n,r){let s=e.childForFieldName("name")?.text;if(!s)return;let i=Bs(e,t,s,s,r);n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"})}function Lx(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let s=Bs(e,t,r,r,"class");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.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 d of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:s.nodeKey,kind:l,targetName:d.text});for(let d of c.descendantsOfType("identifier"))n.refs.push({fromKey:s.nodeKey,kind:l,targetName:d.text})}let i=e.childForFieldName("body");if(i)for(let a of i.namedChildren){if(a.type!=="method_definition")continue;let c=a.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,d=Bs(a,t,c,l,"method");n.nodes.push(d),n.edges.push({srcKey:s.nodeKey,dstKey:d.nodeKey,kind:"contains"});let u=a.childForFieldName("body");u&&xn(n,d.nodeKey,u,om)}}function Bs(e,t,n,r,s){return{nodeKey:Lr(t.filePath,r,s),kind:s,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:nt(e.startPosition.row),endLine:nt(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Hs(e),doc:null}}function Fx(e){return e.replace(/^["'`]|["'`]$/g,"")}var om,cm=b(()=>{"use strict";Bn();Gs();om="call_expression";o(am,"extractTypescript");o(Mx,"unwrapExport");o($x,"handleTopLevel");o(im,"addFunctionLike");o(Ra,"addSimpleNamed");o(Lx,"addClass");o(Bs,"makeNode");o(Fx,"stripQuotes")});import{createRequire as jx}from"node:module";import{join as Ux}from"node:path";function um(e,t){return t?Ux(t,lm[e]):jx(import.meta.url).resolve(`tree-sitter-wasms/out/${lm[e]}`)}var lm,dm,pm=b(()=>{"use strict";lm={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},dm="tree-sitter.wasm";o(um,"grammarPath")});import{join as Hx}from"node:path";import Ia from"web-tree-sitter";var Gx,Ks,fm=b(()=>{"use strict";Bn();Ur();sm();cm();Gs();pm();Gx=["typescript","tsx","javascript","python"],Ks=class{static{o(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await Ia.init(this.assetDir?{locateFile:o(t=>Hx(this.assetDir,t||dm),"locateFile")}:void 0),this.parser=new Ia,this.initialized=!0)}supports(t){return Gx.includes(t)}async parse(t,n,r){await this.init();let s=this.parser;s.setLanguage(await this.grammar(r));let i=s.parse(n);if(!i)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[]};let a=i.rootNode,c=$r(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:nt(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?nm(a,d):am(a,d);return i.delete(),{filePath:t,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await Ia.Language.load(um(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as Wx}from"node:module";function hm(){return mm("node:sqlite")}function En(){if(_r)return _r;try{let{DatabaseSync:e}=hm(),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(),_r={ok:!0}}finally{t.close()}}catch(e){_r={ok:!1,reason:e instanceof Error?e.message:String(e)}}return _r}function Bx(e){let{DatabaseSync:t}=hm(),n=new t(e);return{prepare:o(r=>n.prepare(r),"prepare"),exec:o(r=>n.exec(r),"exec"),close:o(()=>n.close(),"close"),transaction:o(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(s){try{n.exec("ROLLBACK")}catch{}throw s}},"transaction")}}function Kx(e){let t=mm("better-sqlite3"),n=new t(e);return{prepare:o(r=>n.prepare(r),"prepare"),exec:o(r=>{n.exec(r)},"exec"),close:o(()=>{n.close()},"close"),transaction:o(r=>n.transaction(r),"transaction")}}function Vx(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Vs(e){let t=Vx(),n=o(s=>{let i=s==="node:sqlite"?Bx(e):Kx(e);return i.exec("PRAGMA journal_mode = WAL"),i.exec("PRAGMA foreign_keys = ON"),{db:i,backend:s}},"openAs");if(t==="builtin"){let s=En();if(!s.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${s.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=En();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${i})`)}}var mm,_r,Ca=b(()=>{"use strict";mm=Wx(import.meta.url);o(hm,"loadBuiltin");_r=null;o(En,"probeBuiltinSqlite");o(Bx,"openBuiltin");o(Kx,"openBetter");o(Vx,"backendOverride");o(Vs,"openSqliteDatabase")});function zs(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 gm,br,ym=b(()=>{"use strict";Ca();lr();ra();o(zs,"toNodeRow");gm=400,br=class{static{o(this,"NodeSqliteStore")}db;backend;constructor(t){let n=Vs(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Bp)}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 i=this.insertNodeStmt(),a=this.insertFtsStmt();for(let c of n)i.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 s=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)s.run(a);let i=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)i.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?zs(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(zs)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(zs)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(zs)}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 s of t){let i=Buffer.from(s.vec.buffer,s.vec.byteOffset,s.vec.byteLength);n.run(s.nodeKey,s.dim,i,s.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 s=zp(t);if(!s)return[];let i=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
98
106
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
99
107
|
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
100
108
|
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
@@ -107,7 +115,7 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
107
115
|
FROM nodes n
|
|
108
116
|
WHERE n.kind = 'module'
|
|
109
117
|
ORDER BY imports_in DESC, symbol_count DESC
|
|
110
|
-
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(i=>i.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),s=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let i=0;i<n.length;i+=
|
|
118
|
+
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(i=>i.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),s=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let i=0;i<n.length;i+=gm)for(let a of n.slice(i,i+gm))r.run(a),s.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(
|
|
111
119
|
node_key, kind, name, qualified_name, file_path, language,
|
|
112
120
|
start_line, end_line, start_byte, end_byte, signature, doc
|
|
113
121
|
) 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)
|
|
@@ -117,22 +125,22 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
117
125
|
content_hash = excluded.content_hash,
|
|
118
126
|
mtime_ms = excluded.mtime_ms,
|
|
119
127
|
size = excluded.size,
|
|
120
|
-
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as VS}from"node:crypto";function bn(e){return VS("sha256").update(e,"utf8").digest("hex")}function Pf(e){return{node_key_hash:bn(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:bn(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?bn(e.signature):null}}function Mf(e){return{src_key_hash:bn(e.srcKey),dst_key_hash:bn(e.dstKey),kind:e.kind}}function Lf(e,t,n){return{node_key_hash:bn(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var $f=b(()=>{"use strict";o(bn,"sha256");o(Pf,"toCloudNode");o(Mf,"toCloudEdge");o(Lf,"toCloudEmbedding")});function ua(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Ff(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function qS(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var wn,vn,zS,pa=b(()=>{"use strict";dr();$f();wn=class extends Error{static{o(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},vn=class{static{o(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(yn),lastSyncedAt:Ff(await this.store.getMeta(oa))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Pf),n=(await this.store.getAllEdges()).map(Mf),r=await this.store.getMeta(gn)??hn,s=await this.store.getMeta(yn),i=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(y=>[y.language,y.count])),c={project_key:this.cfg.projectKey,head_commit:s,schema_version:r,file_count:i,lang_dist:a},l=0,d=ua(t,this.chunk),u=ua(n,this.chunk*2),p=Math.max(1,d.length+u.length);for(let y of d)await this.post("/api/codebase/push",{...c,nodes:y,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:p});for(let y of u)await this.post("/api/codebase/push",{...c,nodes:[],edges:y}),this.cfg.onProgress?.({phase:"edges",done:++l,total:p});d.length===0&&u.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let m=t.map(y=>y.node_key_hash),h=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:m});this.cfg.onProgress?.({phase:"prune",done:p,total:p});let g=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(oa,String(Date.now())),s&&await this.store.setMeta(Sf,s),{nodes:t.length,edges:n.length,pruned:qS(h.nodes_deleted),embeddings:g,headCommit:s}}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}),i=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(d=>Lf(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&i[d.node_key_hash]!==d.content_hash);if(a.length===0)return 0;let c=ua(a,zS),l=0;for(let d of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:d}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(Ds),n=await this.store.getMeta(Ps),r=Ff(await this.store.getMeta(Ms));if(!t||!n||!r)throw new wn("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(()=>""),s=null;try{s=r?JSON.parse(r):null}catch{s=null}if(!t.ok||!s||s.ok!==!0){let i=s?.error;throw new wn(`${n} failed (HTTP ${t.status})${i?`: ${i}`:""}`,t.status,i)}return s}},zS=250;o(ua,"chunkArray");o(Ff,"numOrNull");o(qS,"numOr0")});var jf={};oe(jf,{CodeIndexSync:()=>vn,DEFAULT_DB_RELPATH:()=>ma,SyncError:()=>wn,createCodeIndexSync:()=>JS,createNodeCodeIndex:()=>ha,openSqliteDatabase:()=>Ls,probeBuiltinSqlite:()=>_n});import{mkdirSync as YS}from"node:fs";import{posix as fa}from"node:path";function ha(e){let t=e.dbPath??fa.join(e.repoRoot,ma);YS(fa.dirname(t),{recursive:!0});let n=new fr(t),r=new Qr;return new ur({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function JS(e){let t=e.dbPath??fa.join(e.repoRoot,ma),n=e.projectKey??kl(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 fr(t);return new vn(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var ma,ga=b(()=>{"use strict";Fi();Ml();la();Df();pa();pa();da();ma=".maind/code-index.sqlite";o(ha,"createNodeCodeIndex");o(JS,"createCodeIndexSync")});import{execFileSync as Uf}from"node:child_process";import{existsSync as Hf,realpathSync as Gf}from"node:fs";import{createRequire as XS}from"node:module";import{basename as ZS,dirname as QS,isAbsolute as Wf,join as ex,relative as Bf,resolve as Fs,sep as Kf}from"node:path";function Vf(){let e=_n();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return XS(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 zf(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 pe(e=process.cwd()){try{let t=Uf("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 Yf(e,t=pe(),n=process.cwd()){let r=Wf(e)?[e]:[Fs(t,e),Fs(n,e)];for(let s of r){let i=QS(s);if(!Hf(i))continue;let a;try{a=Gf(i)}catch{continue}let c=Jf(a);if(c===null)continue;let l=Bf(c,ex(a,ZS(s)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Kf).join("/")}}return null}function js(e,t=pe(),n=process.cwd()){let r=Wf(e)?[e]:[Fs(t,e),Fs(n,e)];for(let s of r){if(!Hf(s))continue;let i;try{i=Gf(s)}catch{continue}let a=Jf(i);if(a===null)continue;let c=Bf(a,i);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Kf).join("/")}}return null}function Jf(e){try{let t=Uf("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 Xf(){return ha({repoRoot:pe()})}var qf,mr=b(()=>{"use strict";ga();o(Vf,"probeNativeStore");o(zf,"isNativeStoreUnavailable");qf="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.";o(pe,"resolveRepoRoot");o(Yf,"resolveRepoRootForPath");o(js,"resolveRepoRootForDir");o(Jf,"gitToplevelOf");o(Xf,"defaultEngineFactory")});var sm=b(()=>{"use strict"});var im=b(()=>{"use strict";re()});var sx,XL,om=b(()=>{"use strict";re();sx=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],XL=new RegExp(sx.join("|"),"g")});import{existsSync as ya,readdirSync as ix,readFileSync as ox}from"node:fs";import{spawnSync as ax}from"node:child_process";import{dirname as cx,join as Gs,posix as _a}from"node:path";function cm(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 ${ba} 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 ${ba} 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,m=r!==null&&r.ok===!1?r.detail:void 0,g={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${m?`: ${m}`:"."}`,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:g.title,detail:g.detailText,hint:g.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let s=new Set(r.versions),i=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!s.has(p)).sort(Pe);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:(e.projectRoot?`cd ${e.projectRoot} && npx supabase migration up`:"`npx supabase migration up` im Projektverzeichnis")+" (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen. Meldet der Lauf nichts Angewendetes, war es das falsche Verzeichnis ODER die Migration lief bereits \u2014 diese Pruefung sagt, was davon.",versions:a});let c=r.versions.filter(p=>!i.has(p)).sort(Pe),l=new Map,d=[];for(let p of c){let m=e.siblingVersions.get(p);if(m){let h=l.get(m)??[];h.push(p),l.set(m,h)}else d.push(p)}for(let[p,m]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${m.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${m.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:m});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${d.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:d}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),m=e.fileVersions.filter(g=>!p.has(g)).sort(Pe),h=e.remote.versions.filter(g=>!i.has(g)).sort(Pe);m.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${m.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${m.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:m}),h.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${h.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${h.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:h})}let u=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function lm(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function um(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(`
|
|
121
|
-
`).
|
|
122
|
-
|
|
123
|
-
`)){if(!i.startsWith("worktree "))continue;let a=i.slice(9).trim();if(!a||a===s||!ya(a))continue;let c=Gs(a,t);if(ya(c))try{for(let l of ix(c)){let d=Zt(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function wa(e,t={}){let n=t.runPsql??dm,r=t.timeoutMs??15e3,s=[],i=at(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:s}};let a=[],c=[],l=[];for(let p of i){let m=ux(e,p.dir,s),h=m.source==="missing"?null:am(n,`postgresql://postgres:postgres@127.0.0.1:${m.port}/postgres`,r),g=t.remoteDbUrl!==void 0?am(n,t.remoteDbUrl,r):null,y=cm({dir:p.dir,projectRoot:Gs(e,_a.dirname(_a.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:m,ledger:h,siblingVersions:px(e,p.dir),remote:g});a.push(...y.findings),l.push(y.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:y.verdict,db:y.db})}let d=lm(l),u={open:0,warn:1,info:2};return a.sort((p,m)=>u[p.status]-u[m.status]||p.id.localeCompare(m.id)),{ok:d==="in_sync",verdict:d,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:s}}}var ba,dm,lx,fm=b(()=>{"use strict";re();zn();ba=54322;o(cm,"evaluateLedgerProject");o(lm,"deriveLedgerVerdict");dm=o((e,t,n)=>{let r=ax("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"),lx="select version from supabase_migrations.schema_migrations order by version";o(um,"classifyLedgerError");o(am,"readLedger");o(pm,"parseDbPort");o(dx,"mainWorktreeRoot");o(ux,"resolveConfig");o(px,"gatherSiblingVersions");o(wa,"checkMigrationLedgerDrift")});var mm,hr=b(()=>{"use strict";sm();la();zi();sa();As();Go();Uo();ro();im();om();Xi();Jn();Ns();Qn();zn();Cs();fm();yo();ra();Jn();Qn();Ns();Cs();zr();Wi();dr();mm="0.1.0"});import{execFile as vm}from"node:child_process";import{randomUUID as wx}from"node:crypto";function Tx(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return ka.test(t)?t:wx()}function Sa(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function Rx(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 Ax(e){return await new Promise(t=>{vm("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(Ix(r))})})}function Ix(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 Cx(){return await new Promise(e=>{vm("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 Nx(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function Ox(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),s=ka.test(r)&&r===t?"env":"random";return{current:o(()=>({id:n,source:s,aliases:[]}),"current"),tryUpgrade:o(()=>!1,"tryUpgrade"),adopt:o(i=>{ka.test(i)&&(n=i.trim().toLowerCase())},"adopt"),activityAtMs:o(()=>null,"activityAtMs")}}var wm,km,vx,kx,Sx,xx,Ex,ka,Ks,xa=b(()=>{"use strict";Yt();wm=45e3,km=3e4,vx=5,kx=120,Sx=3e4,xx=15*6e4,Ex=1500,ka=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(Tx,"resolveClientSessionId");o(Sa,"autoAnnounceDisabled");o(Rx,"autoWorkingPathsEnabled");Ks=class{static{o(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??ve)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??Cx,this.gitBranchObject=t.gitBranchObject??Ax,this.log=t.log??(s=>process.stderr.write(s+`
|
|
124
|
-
`)
|
|
125
|
-
|
|
126
|
-
`)}function RE(e,t){let n=o(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(d=>d.length>2)),"toks"),r=n(e),s=n(t);if(r.size<3||s.size<3)return!1;let[i,a]=r.size<=s.size?[r,s]:[s,r],c=0;for(let l of i)a.has(l)&&c++;return c/i.size>=.8}function AE(e,t,n){return bE.test(e)?{polarity:-1,magnitude:Tn.rework,kind:"rework"}:n&&wE.test(e)?{polarity:-1,magnitude:Tn.correction,kind:"correction"}:vE.test(e)?{polarity:1,magnitude:Tn.acceptance,kind:"acceptance"}:t!==null&&RE(t,e)?{polarity:-1,magnitude:Tn.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function IE(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:zm,behaviour_measured:!0}}async function CE(e,t){for(let n of Js(e))await new Promise(r=>{let s=Vm({input:Km(n,{encoding:"utf-8"})});s.on("line",i=>{let a=i.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of Zs(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(Qs))continue;let d=l.name.slice(Qs.length);d&&(t.maind_tool_calls??={},t.maind_tool_calls[d]=(t.maind_tool_calls[d]??0)+1)}}),s.on("error",()=>r()),s.on("close",()=>r())})}async function Ca(e,t={}){let n=IE("");if(!e||!_E(e))return n;let r=t.turns??(await _r(e)).turns;for(let h of r)n.input_tokens+=h.input_tokens,n.output_tokens+=h.output_tokens,n.cache_read_tokens+=h.cache_read_tokens,n.cache_creation_tokens+=h.cache_creation_tokens,h.sidechain||n.assistant_turns++;let s=[],i=new Map,a=null,c=!1,l=null;await new Promise(h=>{let g=Km(e,{encoding:"utf-8"}),y=Vm({input:g}),_=o(w=>{let k=w.trim();if(!k)return;let x;try{x=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let G=x.sessionId??x.session_id;typeof G=="string"&&G&&(n.session_id=G)}x.type==="ai-title"&&typeof x.aiTitle=="string"&&x.aiTitle&&(n.ai_title=x.aiTitle),typeof x.slug=="string"&&x.slug&&(n.session_slug=x.slug);let S=x.message?.role,I=x.isSidechain===!0;if(S==="assistant")for(let G of Zs(x.message?.content)){if(G.type!=="tool_use"||typeof G.name!="string"||!G.name.startsWith(Qs))continue;let Ut=G.name.slice(Qs.length);Ut&&(n.maind_tool_calls??={},n.maind_tool_calls[Ut]=(n.maind_tool_calls[Ut]??0)+1)}if(I)return;if(S==="assistant"){let G=Zs(x.message?.content),Ut=!1;for(let kc of G)kc.type==="tool_use"&&(n.tool_calls++,Ut=!0,kc.name==="AskUserQuestion"&&n.agent_questions++);c=Ut;return}if(S!=="user")return;let L=Zs(x.message?.content),U=TE(L);if(U.includes(kE)){n.interrupts++,s.push({polarity:-1,magnitude:Tn.interrupt,kind:"interrupt"});return}if(L.some(G=>G.type==="tool_result"&&G.is_error===!0&&typeof G.content=="string"&&G.content.includes(SE))){n.tool_denials++,s.push({polarity:-1,magnitude:Tn.denial,kind:"denial"});return}if(L.some(G=>G.type==="tool_result")||!U.trim())return;n.user_turns++,n.user_chars+=U.length;let B=yr(U);B&&(a=B);let $=AE(U,l,c);l=U,$.kind==="correction"?n.corrections++:$.kind==="rework"?n.reworks++:$.kind==="repeat"?n.repeated_instructions++:$.kind==="acceptance"&&n.acceptances++,$.polarity!==0&&s.push($),c=!1},"processLine");y.on("line",w=>{try{_(w)}catch{}}),y.on("close",()=>h()),y.on("error",()=>h()),g.on("error",()=>h())}),await CE(e,n),n.effort_at_end=a;for(let h of r)h.synthetic||h.model==="<unknown>"||EE(i,h.model,h.sidechain,h.output_tokens,h.ts);n.model_mix=[...i.values()].sort((h,g)=>h.first_ts-g.first_ts||h.model.localeCompare(g.model)),n.user_token_estimate=Math.round(n.user_chars/4);let d=n.user_token_estimate+n.output_tokens;n.human_share=d>0?Number((n.user_token_estimate/d).toFixed(4)):0;let u=0,p=0,m=[];return s.forEach((h,g)=>{h.polarity>0?n.reactions_pos++:h.polarity<0&&n.reactions_neg++,u=u*xE+h.polarity*h.magnitude;let y=Number(u.toFixed(3));m.push({t:g,value:y,...h.kind!=="neutral"?{kind:h.kind}:{}}),p+=y,g>0&&s[g-1].polarity<0&&h.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=m,n.momentum_final=m.length?m[m.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 Qs,zm,bE,wE,vE,kE,SE,xE,Tn,qm=b(()=>{"use strict";Ys();Xs();Qs="mcp__maind__",zm="2026-09-09",bE=/(\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,wE=/(\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,vE=/(\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,kE="[Request interrupted by user",SE="The user doesn't want to proceed with this tool use",xE=.7,Tn={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};o(EE,"bumpModel");o(Zs,"asBlocks");o(TE,"textOf");o(RE,"isRepeat");o(AE,"classifyGenuine");o(IE,"emptyAnalysis");o(CE,"tallySubagentMaindCalls");o(Ca,"analyzeSession")});function Na(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 Oa(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 Da(e,t,n,r="unknown",s){let i={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...s?{cost_slices:s.slices,cost_context_ok:s.context_ok}:{}}};return t&&t.started_at&&(i.session_span=n?{...t,...n}:t),i}var Ym=b(()=>{"use strict";o(Na,"parseIngestResponse");o(Oa,"describeSliceVerdict");o(Da,"ingestBody")});import{homedir as NE}from"node:os";import{join as OE}from"node:path";var DE,Pa=b(()=>{"use strict";DE=OE(NE(),".codex","sessions")});var Jm=b(()=>{"use strict";Pa()});import{isAbsolute as $a,relative as ME,resolve as Xm,sep as Fa}from"node:path";function Zm(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function ei(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function ja(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=o(a=>{if(!Array.isArray(a))return[];let c=[];for(let l of a){if(!l||typeof l!="object")continue;let d=l,u=ei(d.from);typeof d.object_id!="string"||!Ma.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:ei(d.to)})}return c},"windows"),s=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=ei(c.from);typeof c.path_prefix!="string"||l===null||s.push({path_prefix:c.path_prefix,from:l,to:ei(c.to)})}let i=[];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"||!Ma.test(c.object_id)||typeof c.path_prefix=="string"&&i.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Ma.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:s,anchors:i}}function eh(e,t){if(!$a(e))return null;let n=ME(Xm(t),Xm(e));return!n||n==="."||n.startsWith("..")||$a(n)?null:Fa==="/"?n:n.split(Fa).join("/")}function LE(e,t){return t===""||e===t||e.startsWith(t+"/")}function Ua(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function th(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function Ha(e,t){for(let n of th(t))if(LE(e,n.path_prefix))return n.object_id;return null}function $E(e,t){for(let n of th(t))if(Ua(e,n.path_prefix))return n.object_id;return null}function La(e,t){return e>=t.from&&(t.to===null||e<t.to)}function nh(e,t,n,r){let s=e.ts,i=r?.anchors??[],a=t.map(c=>Ha(c,i)).filter(c=>c!==null);if(r&&s>0){let c=r.leases.filter(u=>La(s,u));if(c.length)return c.sort((u,p)=>p.from-u.from||u.object_id.localeCompare(p.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(u=>La(s,u));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,m)=>p.object_id.localeCompare(m.object_id))[0]).object_id,source:"binding"};let d=r.claims.filter(u=>La(s,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(m=>Ua(m.path_prefix,u))).sort((m,h)=>h.path_prefix.length-m.path_prefix.length);for(let m of p){let h=$E(m.path_prefix,i);if(h)return{object_id:h,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 Ga(e,t,n){let r=t?.anchors??[],s=o(g=>{if(!n.repoRoot)return[];let y=[];for(let _ of g.edited_paths){let w=eh(_,n.repoRoot);w!==null&&!y.includes(w)&&y.push(w)}return y},"relOf"),i=o(g=>{for(let y of g){let _=Ha(y,r);if(_)return{object_id:_,rel:y}}return null},"firstAnchoredEdit"),a=new Map;for(let g of e){let y=a.get(g.stream)??[];y.push(g),a.set(g.stream,y)}let c=[...a.entries()].sort(([g],[y])=>g===Ot?-1:y===Ot?1:0),l=[],d=o(g=>{let y=null;for(let _ of l){if(_.ts>g&&g>0)break;y=_.seg}return y},"mainSegmentAt"),u=new Map;for(let[g,y]of c){let _=y.map((k,x)=>({t:k,i:x,rels:s(k)})).sort((k,x)=>k.t.ts-x.t.ts||k.i-x.i),w=null;for(let k of _){let x=i(k.rels);if(x){w=x;break}}!w&&g!==Ot&&_.length&&(w=d(_[0].t.ts));for(let k of _){let x=i(k.rels);x&&(w=x),g===Ot&&l.push({ts:k.t.ts,seg:w});let S=k.t;if(S.input_tokens+S.output_tokens+S.cache_read_tokens+S.cache_creation_tokens===0)continue;let L=nh(S,k.rels,w,t),U=S.input_tokens+S.cache_read_tokens+S.cache_creation_tokens>Qm?"above_200k":"standard",F=Zm(S.model),B=`${L.object_id??""}|${L.source}|${F}|${U}`,$=u.get(B);$||($={object_id:L.object_id,attribution_source:L.source,model:F,context_tier:U,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},u.set(B,$)),$.input_tokens+=S.input_tokens,$.output_tokens+=S.output_tokens,$.cache_read_tokens+=S.cache_read_tokens,$.cache_creation_tokens+=S.cache_creation_tokens,$.cache_creation_1h_tokens+=S.cache_creation_1h_tokens,$.turns+=1,S.ts>0&&(($.firstMs===0||S.ts<$.firstMs)&&($.firstMs=S.ts),S.ts>$.lastMs&&($.lastMs=S.ts))}}let p=n.nowMs??Date.now(),m=[];for(let g of u.values()){let{firstMs:y,lastMs:_,...w}=g;w.first_ts=new Date(y>0?y:p).toISOString(),w.last_ts=new Date(_>0?_:p).toISOString(),m.push(w)}let h={lease:0,binding:1,claim:2,path:3,none:4};return m.sort((g,y)=>h[g.attribution_source]-h[y.attribution_source]||(g.object_id??"").localeCompare(y.object_id??"")||g.model.localeCompare(y.model)||g.context_tier.localeCompare(y.context_tier)),m}function Wa(e,t){let n=new Map;for(let i of e){let a=new Set;for(let c of i.edited_paths){if(!$a(c))continue;let l=t(FE(c));l&&a.add(l)}for(let c of a)n.set(c,(n.get(c)??0)+1)}let r=null,s=0;for(let[i,a]of n)(a>s||a===s&&r!==null&&i.length>r.length)&&(r=i,s=a);return r}function FE(e){let t=e.split(Fa).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var Qm,Ma,rh=b(()=>{"use strict";Xs();o(Zm,"normalizeModelId");Qm=2e5,Ma=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(ei,"msOf");o(ja,"parseCostContext");o(eh,"toRepoRelative");o(LE,"underPrefix");o(Ua,"prefixesOverlap");o(th,"sortedAnchors");o(Ha,"anchorFor");o($E,"bestAnchorOverlapping");o(La,"inWindow");o(nh,"assignTurn");o(Ga,"sliceSession");o(Wa,"dominantCheckoutRoot");o(FE,"dirOf")});import{createReadStream as jE,existsSync as UE}from"node:fs";import{createInterface as HE}from"node:readline";function sh(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function BE(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
127
|
-
`
|
|
128
|
-
`)
|
|
128
|
+
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as zx}from"node:crypto";function An(e){return zx("sha256").update(e,"utf8").digest("hex")}function _m(e){return{node_key_hash:An(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:An(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?An(e.signature):null}}function bm(e){return{src_key_hash:An(e.srcKey),dst_key_hash:An(e.dstKey),kind:e.kind}}function wm(e,t,n){return{node_key_hash:An(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var vm=b(()=>{"use strict";o(An,"sha256");o(_m,"toCloudNode");o(bm,"toCloudEdge");o(wm,"toCloudEmbedding")});function Na(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function km(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Yx(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var Tn,Rn,qx,Oa=b(()=>{"use strict";lr();vm();Tn=class extends Error{static{o(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},Rn=class{static{o(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(mn),lastSyncedAt:km(await this.store.getMeta(ta))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(_m),n=(await this.store.getAllEdges()).map(bm),r=await this.store.getMeta(fn)??pn,s=await this.store.getMeta(mn),i=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(y=>[y.language,y.count])),c={project_key:this.cfg.projectKey,head_commit:s,schema_version:r,file_count:i,lang_dist:a},l=0,d=Na(t,this.chunk),u=Na(n,this.chunk*2),p=Math.max(1,d.length+u.length);for(let y of d)await this.post("/api/codebase/push",{...c,nodes:y,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++l,total:p});for(let y of u)await this.post("/api/codebase/push",{...c,nodes:[],edges:y}),this.cfg.onProgress?.({phase:"edges",done:++l,total:p});d.length===0&&u.length===0&&await this.post("/api/codebase/push",{...c,nodes:[],edges:[]});let m=t.map(y=>y.node_key_hash),h=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:m});this.cfg.onProgress?.({phase:"prune",done:p,total:p});let g=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(ta,String(Date.now())),s&&await this.store.setMeta(Kp,s),{nodes:t.length,edges:n.length,pruned:Yx(h.nodes_deleted),embeddings:g,headCommit:s}}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}),i=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(d=>wm(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&i[d.node_key_hash]!==d.content_hash);if(a.length===0)return 0;let c=Na(a,qx),l=0;for(let d of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:d}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(bs),n=await this.store.getMeta(ws),r=km(await this.store.getMeta(vs));if(!t||!n||!r)throw new Tn("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(()=>""),s=null;try{s=r?JSON.parse(r):null}catch{s=null}if(!t.ok||!s||s.ok!==!0){let i=s?.error;throw new Tn(`${n} failed (HTTP ${t.status})${i?`: ${i}`:""}`,t.status,i)}return s}},qx=250;o(Na,"chunkArray");o(km,"numOrNull");o(Yx,"numOr0")});var Sm={};se(Sm,{CodeIndexSync:()=>Rn,DEFAULT_DB_RELPATH:()=>Da,SyncError:()=>Tn,createCodeIndexSync:()=>Xx,createNodeCodeIndex:()=>Pa,openSqliteDatabase:()=>Vs,probeBuiltinSqlite:()=>En});import{mkdirSync as Jx}from"node:fs";import{posix as qs}from"node:path";function Pa(e){let t=e.dbPath??qs.join(e.repoRoot,Da);Jx(qs.dirname(t),{recursive:!0}),e.dbPath===void 0&&ur(qs.dirname(t));let n=new br(t),r=new Ks;return new dr({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function Xx(e){let t=e.dbPath??qs.join(e.repoRoot,Da),n=e.projectKey??Wl(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 br(t);return new Rn(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var Da,Ma=b(()=>{"use strict";no();fm();sa();ym();Oa();la();Oa();Ca();Da=".maind/code-index.sqlite";o(Pa,"createNodeCodeIndex");o(Xx,"createCodeIndexSync")});import{execFileSync as xm}from"node:child_process";import{existsSync as Em,realpathSync as Am}from"node:fs";import{createRequire as Zx}from"node:module";import{basename as Qx,dirname as eE,isAbsolute as Tm,join as tE,relative as Rm,resolve as Ys,sep as Im}from"node:path";function Cm(){let e=En();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return Zx(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 Nm(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 fe(e=process.cwd()){try{let t=xm("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 Dm(e,t=fe(),n=process.cwd()){let r=Tm(e)?[e]:[Ys(t,e),Ys(n,e)];for(let s of r){let i=eE(s);if(!Em(i))continue;let a;try{a=Am(i)}catch{continue}let c=Pm(a);if(c===null)continue;let l=Rm(c,tE(a,Qx(s)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Im).join("/")}}return null}function Js(e,t=fe(),n=process.cwd()){let r=Tm(e)?[e]:[Ys(t,e),Ys(n,e)];for(let s of r){if(!Em(s))continue;let i;try{i=Am(s)}catch{continue}let a=Pm(i);if(a===null)continue;let c=Rm(a,i);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Im).join("/")}}return null}function Pm(e){try{let t=xm("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 Mm(){return Pa({repoRoot:fe()})}var Om,wr=b(()=>{"use strict";Ma();o(Cm,"probeNativeStore");o(Nm,"isNativeStoreUnavailable");Om="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.";o(fe,"resolveRepoRoot");o(Dm,"resolveRepoRootForPath");o(Js,"resolveRepoRootForDir");o(Pm,"gitToplevelOf");o(Mm,"defaultEngineFactory")});import{execFile as qm}from"node:child_process";import{randomUUID as pE}from"node:crypto";function _E(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return La.test(t)?t:pE()}function Fa(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function bE(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 wE(e){return await new Promise(t=>{qm("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(vE(r))})})}function vE(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 kE(){return await new Promise(e=>{qm("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 SE(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function xE(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),s=La.test(r)&&r===t?"env":"random";return{current:o(()=>({id:n,source:s,aliases:[]}),"current"),tryUpgrade:o(()=>!1,"tryUpgrade"),adopt:o(i=>{La.test(i)&&(n=i.trim().toLowerCase())},"adopt"),activityAtMs:o(()=>null,"activityAtMs")}}var zm,Ym,fE,mE,hE,gE,yE,La,ti,ja=b(()=>{"use strict";Sn();zm=45e3,Ym=3e4,fE=5,mE=120,hE=3e4,gE=15*6e4,yE=1500,La=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(_E,"resolveClientSessionId");o(Fa,"autoAnnounceDisabled");o(bE,"autoWorkingPathsEnabled");ti=class{static{o(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??Te)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??kE,this.gitBranchObject=t.gitBranchObject??wE,this.log=t.log??(s=>process.stderr.write(s+`
|
|
129
|
+
`)),this.machineLabel=SE(r?.machine_label),this.enabled=this.projectKey!==null&&!Fa(n,r),this.workingPathsEnabled=bE(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??xE(n,_E(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<zm||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<zm||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<fE||(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,yE).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(hE*2**(this.consecutiveFailures-1),gE);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{if(t==="active"){let i=this.identity.current().id;(this.identity.resync?this.identity.resync():this.identity.tryUpgrade()?"upgraded":"unchanged")==="switched"&&this.log(`[maind-mcp-bridge] presence: this agent process now hosts a different conversation (${i} \u2192 ${this.identity.current().id}) \u2014 announcing it as its own session.`)}}catch{}let n=this.identity.current(),r={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:mE,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let i=await this.gitBranch();if(i&&(r.branch=i),this.lastBranch=i,i)try{let a=await this.gitBranchObject(i);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 s=await this.postToolCall("announce_session",r);if(t==="active"&&s!==null&&typeof s=="object"){let i=s;if(i.ok===!0&&typeof i.session_id=="string")try{this.identity.adopt(i.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(s!=null){let i={sessionId:this.sessionId,branch:this.lastBranch},a=typeof s=="object"?s:null;if(a!==null&&a.ok===!0)this.snapshot.write(s,i);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,i)}}}catch{}}};o(wE,"defaultGitBranchObject");o(vE,"normalizeObjectId");o(kE,"defaultGitBranch");o(SE,"normalizeMachineLabel");o(xE,"staticIdentity")});import{mkdirSync as Jm,readdirSync as eh,readFileSync as EE,renameSync as Xm,statSync as AE,unlinkSync as Ua,writeFileSync as Zm}from"node:fs";import{homedir as TE}from"node:os";import{join as In}from"node:path";function th(){return In(TE(),".maind","presence")}function nh(e,t){return In(e,t)}function rh(e){let t=e.baseDir??th(),n=nh(t,e.projectKey),r=e.pid??process.pid,s=e.ppid??process.ppid,i=e.cwd??process.cwd(),a=e.now??Date.now,c=null,l=o(d=>{if(c!==null&&c!==d)try{Ua(c)}catch{}c=d},"replaceOwn");return{write(d,u){try{if(typeof d!="object"||d===null)return;let p=d;if(p.ok!==!0)return;let m={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:s,cwd:i,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[]};Jm(n,{recursive:!0,mode:448});let h=In(n,`${u.sessionId}.json`),g=`${h}.tmp-${r}`;Zm(g,JSON.stringify(m),{mode:384}),Xm(g,h),l(h),Qm(n,a(),h)}catch{}},endSession(){try{c&&Ua(c)}catch{}},markFailed(d,u){try{let p={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:s,cwd:i,branch:u.branch,peers:[],conflicts:[],announce_error:d};Jm(n,{recursive:!0,mode:448});let m=In(n,`${u.sessionId}.json`),h=`${m}.tmp-${r}`;Zm(h,JSON.stringify(p),{mode:384}),Xm(h,m),l(m),Qm(n,a(),m)}catch{}}}}function Qm(e,t,n){try{for(let r of eh(e)){if(!r.endsWith(".json"))continue;let s=In(e,r);if(s!==n)try{t-AE(s).mtimeMs>RE&&Ua(s)}catch{}}}catch{}}function Cn(e,t=th()){try{let n=nh(t,e),r=[];for(let s of eh(n))if(s.endsWith(".json"))try{let i=JSON.parse(EE(In(n,s),"utf8")),a=IE(i);a&&r.push(a)}catch{}return r.sort((s,i)=>i.written_at.localeCompare(s.written_at)),r}catch{return[]}}function IE(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 RE,ni=b(()=>{"use strict";RE=120*6e4;o(th,"presenceSnapshotBaseDir");o(nh,"projectDir");o(rh,"createSnapshotStore");o(Qm,"pruneStale");o(Cn,"readSnapshots");o(IE,"parseSnapshot")});import{execFileSync as CE}from"node:child_process";import{createHash as NE,randomUUID as OE}from"node:crypto";import{existsSync as DE,mkdirSync as PE,readdirSync as ME,readFileSync as ih,renameSync as $E,statSync as Ha,unlinkSync as oh,writeFileSync as LE}from"node:fs";import{homedir as FE}from"node:os";import{basename as jE,join as rt}from"node:path";function Nn(e){return rt(e??rt(FE(),".maind","presence"),"identity")}function kr(e,t){if(e){let n=jE(e).replace(/\.jsonl$/i,"");if(vr.test(n))return n.toLowerCase()}return t&&vr.test(t)?t.toLowerCase():null}function ah(e){let t=e.nowMs??Date.now();PE(e.dir,{recursive:!0,mode:448});let n=rt(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,s={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(ih(n,"utf8"));l.session_id===e.sessionId&&(s={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let i=e.transcriptPath??s.transcript_path,a=e.model??s.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(),...i?{transcript_path:i}:{},...a?{model:a}:{}};LE(r,JSON.stringify(c,null,2)+`
|
|
130
|
+
`,{mode:384}),$E(r,n),BE(e.dir,t)}function ch(e,t,n,r=Date.now()){try{let s=Ha(rt(e,`${t}.json`));return r-s.mtimeMs>n}catch{return!0}}function lh(e,t){try{oh(rt(e,`${t}.json`))}catch{}}function BE(e,t){try{for(let n of ME(e))if(n.endsWith(".json"))try{let r=Ha(rt(e,n));t-r.mtimeMs>HE&&oh(rt(e,n))}catch{}}catch{}}function KE(e){return dh(e)?.file??null}function dh(e){let t=rt(e.dir,`${e.agentPid}.json`);try{if(!DE(t))return null;let n=Ha(t);if(n.mtimeMs<e.bridgeStartMs-GE)return null;let r=JSON.parse(ih(t,"utf8"));if(typeof r!="object"||r===null)return null;let s=r;return s.v!==1||typeof s.transcript_stem!="string"||!vr.test(s.transcript_stem)||typeof s.session_id!="string"||typeof s.cwd!="string"||s.agent_pid!==e.agentPid||!VE(s.cwd,e.cwd)?null:{file:s,mtimeMs:n.mtimeMs}}catch{return null}}function sh(e){return e.replace(/\/+$/,"")}function VE(e,t){let n=sh(e),r=sh(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function zE(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=NE("sha1").update(n).update(e,"utf8").digest(),s=Buffer.from(r.subarray(0,16));s[6]=s[6]&15|80,s[8]=s[8]&63|128;let i=s.toString("hex");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function qE(e){if(process.platform==="win32")return null;try{let t=CE("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function YE(){try{return te()}catch{return null}}var vr,UE,HE,GE,WE,ri,si=b(()=>{"use strict";ce();vr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,UE=8,HE=48*60*6e4,GE=6e4,WE="9f3c72da-2f10-4b8f-9c31-ad291c0de291";o(Nn,"identityDirPath");o(kr,"transcriptStemOf");o(ah,"writeAgentIdentityFile");o(ch,"identityFileStale");o(lh,"deleteAgentIdentityFile");o(BE,"pruneIdentityDir");o(KE,"readAgentIdentityFile");o(dh,"readAgentIdentityEntry");o(sh,"normDir");o(VE,"sameSessionTree");o(zE,"uuidV5");o(qE,"processStartTime");ri=class{static{o(this,"SessionIdentityManager")}env;agentPid;cwd;dir;bridgeStartMs;nowMs;envId;id;source;aliases=[];stem=null;constructor(t){this.env=t.env??process.env,this.agentPid=t.agentPid??process.ppid,this.cwd=t.cwd??process.cwd(),this.dir=t.identityDir??Nn(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=vr.test(n)?n:null;let r=this.readStem();if(r!==null){this.id=r,this.stem=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 s=(t.deviceId??YE)(),i=(t.ppidStart??qE)(this.agentPid);if(s!==null&&i!==null&&t.projectKey!==null){this.id=zE(`${s}|${this.agentPid}|${i}|${t.projectKey}`,WE),this.source="derived";return}this.id=OE(),this.source="random"}current(){return{id:this.id,source:this.source,aliases:[...this.aliases]}}tryUpgrade(){return this.resync()!=="unchanged"}resync(){let t=this.readStem();if(t===null)return"unchanged";if(this.source==="client_native")return t===this.stem?"unchanged":(this.id=t,this.stem=t,this.aliases=this.envId!==null&&this.envId!==t?[this.envId]:[],"switched");if(t===this.id)return"unchanged";let n=this.id;return this.id=t,this.stem=t,this.source="client_native",this.pushAlias(n),this.envId!==null&&this.pushAlias(this.envId),"upgraded"}adopt(t){let n=t.trim().toLowerCase();if(!vr.test(n)||n===this.id)return;let r=this.id;this.id=n,!(this.source==="client_native"&&r===this.stem)&&this.pushAlias(r)}pushAlias(t){t===this.id||this.aliases.includes(t)||(this.aliases.push(t),this.aliases.length>UE&&this.aliases.shift())}activityAtMs(){return dh({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 KE({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};o(YE,"defaultDeviceId")});function Ga(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Wa=b(()=>{"use strict";o(Ga,"newModeState")});import{createReadStream as JE,existsSync as XE}from"node:fs";import{stat as ZE}from"node:fs/promises";import{createInterface as QE}from"node:readline";async function Ba(e){if(!e||!XE(e))return null;let t;try{t=await ZE(e)}catch{return null}let n=new Set,r=0,s=0,i=0;return await new Promise(a=>{let c=JE(e,{encoding:"utf-8"}),l=QE({input:c});l.on("line",d=>{let u=d.trim();if(u){i++;try{let p=JSON.parse(u),m=p.message?.usage;if(!m)return;let h=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=h??g;if(y!==null){if(n.has(y))return;n.add(y)}typeof m.input_tokens=="number"&&(r+=m.input_tokens),typeof m.output_tokens=="number"&&(s+=m.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:s,total_tokens:r+s,lines_seen:i,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var uh=b(()=>{"use strict";o(Ba,"summariseTranscript")});var ph=b(()=>{"use strict"});function Sr(e){if(!e)return null;let t=null;for(let n of e.matchAll(t0)){let r=n[1].toLowerCase();e0.has(r)&&(t=r)}return t}var e0,t0,ii=b(()=>{"use strict";e0=new Set(["low","medium","high","xhigh","max"]),t0=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;o(Sr,"detectEffortLevel")});import{createReadStream as n0,existsSync as r0,readdirSync as s0}from"node:fs";import{basename as hh,dirname as i0,join as fh}from"node:path";import{createInterface as o0}from"node:readline";function On(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function l0(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 s=c0[r.name];if(!s||!r.input||typeof r.input!="object")continue;let i=r.input[s];typeof i=="string"&&i.length>0&&t.push(i)}return t}function oi(e){let t=hh(e).replace(/\.jsonl$/,""),n=fh(i0(e),t,"subagents"),r;try{r=s0(n)}catch{return[]}return r.filter(s=>s.endsWith(".jsonl")).sort().map(s=>fh(n,s))}async function mh(e,t,n,r,s){r0(e)&&await new Promise(i=>{let a=n0(e,{encoding:"utf-8"}),c=o0({input:a}),l=0;c.on("line",d=>{l++;let u=d.trim();if(!u)return;let p;try{p=JSON.parse(u)}catch{return}if(p.message?.role!=="assistant")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??`${e}#${l}`,y=l0(p.message.content),_=r.get(g);if(_){for(let I of y)_.edited_paths.includes(I)||_.edited_paths.push(I);return}if(n.has(g))return;n.add(g);let w=p.message.usage??{},k=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,x=typeof p.message.model=="string"&&p.message.model?p.message.model:"",S={ts:Number.isFinite(k)?k:0,model:x||"<unknown>",synthetic:x===a0,input_tokens:On(w.input_tokens),output_tokens:On(w.output_tokens),cache_read_tokens:On(w.cache_read_input_tokens),cache_creation_tokens:On(w.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(On(w.cache_creation?.ephemeral_1h_input_tokens),On(w.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:t,edited_paths:y,cwd:typeof p.cwd=="string"&&p.cwd?p.cwd:null};r.set(g,S),s.push(S)}),c.on("close",()=>i()),c.on("error",()=>i()),a.on("error",()=>i())})}function Ka(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 s=e[r];s.ts>0?n=s.ts:n>0&&(s.ts=n)}}async function xr(e){let t=new Set,n=new Map,r=[],s=e?oi(e):[];if(!e)return{turns:r,subagent_files:s};let i=[];await mh(e,Mt,t,n,i),Ka(i),r.push(...i);for(let a of s){let c=[],l=hh(a).replace(/\.jsonl$/,"");await mh(a,l,t,n,c),Ka(c);for(let d of c)d.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:s}}var Mt,a0,c0,ai=b(()=>{"use strict";Mt="main",a0="<synthetic>",c0={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};o(On,"num");o(l0,"editedPathsOf");o(oi,"subagentFilesOf");o(mh,"readStream");o(Ka,"fillTimestamps");o(xr,"collectTurns")});import{createReadStream as gh,existsSync as d0}from"node:fs";import{createInterface as yh}from"node:readline";function y0(e,t,n,r,s){let i=`${n?"s":"m"}:${t}`,a=e.get(i);if(!a){e.set(i,{model:t,turns:1,output_tokens:r,first_ts:s,last_ts:s,sidechain:n});return}a.turns++,a.output_tokens+=r,s>0&&((a.first_ts===0||s<a.first_ts)&&(a.first_ts=s),s>a.last_ts&&(a.last_ts=s))}function ci(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function _0(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
131
|
+
`)}function b0(e,t){let n=o(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(d=>d.length>2)),"toks"),r=n(e),s=n(t);if(r.size<3||s.size<3)return!1;let[i,a]=r.size<=s.size?[r,s]:[s,r],c=0;for(let l of i)a.has(l)&&c++;return c/i.size>=.8}function w0(e,t,n){return u0.test(e)?{polarity:-1,magnitude:Dn.rework,kind:"rework"}:n&&p0.test(e)?{polarity:-1,magnitude:Dn.correction,kind:"correction"}:f0.test(e)?{polarity:1,magnitude:Dn.acceptance,kind:"acceptance"}:t!==null&&b0(t,e)?{polarity:-1,magnitude:Dn.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function v0(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:_h,behaviour_measured:!0}}async function k0(e,t){for(let n of oi(e))await new Promise(r=>{let s=yh({input:gh(n,{encoding:"utf-8"})});s.on("line",i=>{let a=i.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of ci(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(li))continue;let d=l.name.slice(li.length);d&&(t.maind_tool_calls??={},t.maind_tool_calls[d]=(t.maind_tool_calls[d]??0)+1)}}),s.on("error",()=>r()),s.on("close",()=>r())})}async function Va(e,t={}){let n=v0("");if(!e||!d0(e))return n;let r=t.turns??(await xr(e)).turns;for(let h of r)n.input_tokens+=h.input_tokens,n.output_tokens+=h.output_tokens,n.cache_read_tokens+=h.cache_read_tokens,n.cache_creation_tokens+=h.cache_creation_tokens,h.sidechain||n.assistant_turns++;let s=[],i=new Map,a=null,c=!1,l=null;await new Promise(h=>{let g=gh(e,{encoding:"utf-8"}),y=yh({input:g}),_=o(w=>{let k=w.trim();if(!k)return;let x;try{x=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let W=x.sessionId??x.session_id;typeof W=="string"&&W&&(n.session_id=W)}x.type==="ai-title"&&typeof x.aiTitle=="string"&&x.aiTitle&&(n.ai_title=x.aiTitle),typeof x.slug=="string"&&x.slug&&(n.session_slug=x.slug);let S=x.message?.role,I=x.isSidechain===!0;if(S==="assistant")for(let W of ci(x.message?.content)){if(W.type!=="tool_use"||typeof W.name!="string"||!W.name.startsWith(li))continue;let Kt=W.name.slice(li.length);Kt&&(n.maind_tool_calls??={},n.maind_tool_calls[Kt]=(n.maind_tool_calls[Kt]??0)+1)}if(I)return;if(S==="assistant"){let W=ci(x.message?.content),Kt=!1;for(let Gc of W)Gc.type==="tool_use"&&(n.tool_calls++,Kt=!0,Gc.name==="AskUserQuestion"&&n.agent_questions++);c=Kt;return}if(S!=="user")return;let $=ci(x.message?.content),U=_0($);if(U.includes(m0)){n.interrupts++,s.push({polarity:-1,magnitude:Dn.interrupt,kind:"interrupt"});return}if($.some(W=>W.type==="tool_result"&&W.is_error===!0&&typeof W.content=="string"&&W.content.includes(h0))){n.tool_denials++,s.push({polarity:-1,magnitude:Dn.denial,kind:"denial"});return}if($.some(W=>W.type==="tool_result")||!U.trim())return;n.user_turns++,n.user_chars+=U.length;let K=Sr(U);K&&(a=K);let L=w0(U,l,c);l=U,L.kind==="correction"?n.corrections++:L.kind==="rework"?n.reworks++:L.kind==="repeat"?n.repeated_instructions++:L.kind==="acceptance"&&n.acceptances++,L.polarity!==0&&s.push(L),c=!1},"processLine");y.on("line",w=>{try{_(w)}catch{}}),y.on("close",()=>h()),y.on("error",()=>h()),g.on("error",()=>h())}),await k0(e,n),n.effort_at_end=a;for(let h of r)h.synthetic||h.model==="<unknown>"||y0(i,h.model,h.sidechain,h.output_tokens,h.ts);n.model_mix=[...i.values()].sort((h,g)=>h.first_ts-g.first_ts||h.model.localeCompare(g.model)),n.user_token_estimate=Math.round(n.user_chars/4);let d=n.user_token_estimate+n.output_tokens;n.human_share=d>0?Number((n.user_token_estimate/d).toFixed(4)):0;let u=0,p=0,m=[];return s.forEach((h,g)=>{h.polarity>0?n.reactions_pos++:h.polarity<0&&n.reactions_neg++,u=u*g0+h.polarity*h.magnitude;let y=Number(u.toFixed(3));m.push({t:g,value:y,...h.kind!=="neutral"?{kind:h.kind}:{}}),p+=y,g>0&&s[g-1].polarity<0&&h.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=m,n.momentum_final=m.length?m[m.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 li,_h,u0,p0,f0,m0,h0,g0,Dn,bh=b(()=>{"use strict";ii();ai();li="mcp__maind__",_h="2026-09-09",u0=/(\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,p0=/(\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,f0=/(\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,m0="[Request interrupted by user",h0="The user doesn't want to proceed with this tool use",g0=.7,Dn={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};o(y0,"bumpModel");o(ci,"asBlocks");o(_0,"textOf");o(b0,"isRepeat");o(w0,"classifyGenuine");o(v0,"emptyAnalysis");o(k0,"tallySubagentMaindCalls");o(Va,"analyzeSession")});function za(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 qa(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 Ya(e,t,n,r="unknown",s){let i={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...s?{cost_slices:s.slices,cost_context_ok:s.context_ok}:{}}};return t&&t.started_at&&(i.session_span=n?{...t,...n}:t),i}var wh=b(()=>{"use strict";o(za,"parseIngestResponse");o(qa,"describeSliceVerdict");o(Ya,"ingestBody")});import{homedir as S0}from"node:os";import{join as x0}from"node:path";var E0,Ja=b(()=>{"use strict";E0=x0(S0(),".codex","sessions")});var vh=b(()=>{"use strict";Ja()});import{isAbsolute as Qa,relative as T0,resolve as kh,sep as ec}from"node:path";function Sh(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function di(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function tc(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=o(a=>{if(!Array.isArray(a))return[];let c=[];for(let l of a){if(!l||typeof l!="object")continue;let d=l,u=di(d.from);typeof d.object_id!="string"||!Xa.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:di(d.to)})}return c},"windows"),s=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=di(c.from);typeof c.path_prefix!="string"||l===null||s.push({path_prefix:c.path_prefix,from:l,to:di(c.to)})}let i=[];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"||!Xa.test(c.object_id)||typeof c.path_prefix=="string"&&i.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Xa.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:s,anchors:i}}function Eh(e,t){if(!Qa(e))return null;let n=T0(kh(t),kh(e));return!n||n==="."||n.startsWith("..")||Qa(n)?null:ec==="/"?n:n.split(ec).join("/")}function R0(e,t){return t===""||e===t||e.startsWith(t+"/")}function nc(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Ah(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function rc(e,t){for(let n of Ah(t))if(R0(e,n.path_prefix))return n.object_id;return null}function I0(e,t){for(let n of Ah(t))if(nc(e,n.path_prefix))return n.object_id;return null}function Za(e,t){return e>=t.from&&(t.to===null||e<t.to)}function Th(e,t,n,r){let s=e.ts,i=r?.anchors??[],a=t.map(c=>rc(c,i)).filter(c=>c!==null);if(r&&s>0){let c=r.leases.filter(u=>Za(s,u));if(c.length)return c.sort((u,p)=>p.from-u.from||u.object_id.localeCompare(p.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(u=>Za(s,u));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,m)=>p.object_id.localeCompare(m.object_id))[0]).object_id,source:"binding"};let d=r.claims.filter(u=>Za(s,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(m=>nc(m.path_prefix,u))).sort((m,h)=>h.path_prefix.length-m.path_prefix.length);for(let m of p){let h=I0(m.path_prefix,i);if(h)return{object_id:h,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 sc(e,t,n){let r=t?.anchors??[],s=o(g=>{if(!n.repoRoot)return[];let y=[];for(let _ of g.edited_paths){let w=Eh(_,n.repoRoot);w!==null&&!y.includes(w)&&y.push(w)}return y},"relOf"),i=o(g=>{for(let y of g){let _=rc(y,r);if(_)return{object_id:_,rel:y}}return null},"firstAnchoredEdit"),a=new Map;for(let g of e){let y=a.get(g.stream)??[];y.push(g),a.set(g.stream,y)}let c=[...a.entries()].sort(([g],[y])=>g===Mt?-1:y===Mt?1:0),l=[],d=o(g=>{let y=null;for(let _ of l){if(_.ts>g&&g>0)break;y=_.seg}return y},"mainSegmentAt"),u=new Map;for(let[g,y]of c){let _=y.map((k,x)=>({t:k,i:x,rels:s(k)})).sort((k,x)=>k.t.ts-x.t.ts||k.i-x.i),w=null;for(let k of _){let x=i(k.rels);if(x){w=x;break}}!w&&g!==Mt&&_.length&&(w=d(_[0].t.ts));for(let k of _){let x=i(k.rels);x&&(w=x),g===Mt&&l.push({ts:k.t.ts,seg:w});let S=k.t;if(S.input_tokens+S.output_tokens+S.cache_read_tokens+S.cache_creation_tokens===0)continue;let $=Th(S,k.rels,w,t),U=S.input_tokens+S.cache_read_tokens+S.cache_creation_tokens>xh?"above_200k":"standard",j=Sh(S.model),K=`${$.object_id??""}|${$.source}|${j}|${U}`,L=u.get(K);L||(L={object_id:$.object_id,attribution_source:$.source,model:j,context_tier:U,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},u.set(K,L)),L.input_tokens+=S.input_tokens,L.output_tokens+=S.output_tokens,L.cache_read_tokens+=S.cache_read_tokens,L.cache_creation_tokens+=S.cache_creation_tokens,L.cache_creation_1h_tokens+=S.cache_creation_1h_tokens,L.turns+=1,S.ts>0&&((L.firstMs===0||S.ts<L.firstMs)&&(L.firstMs=S.ts),S.ts>L.lastMs&&(L.lastMs=S.ts))}}let p=n.nowMs??Date.now(),m=[];for(let g of u.values()){let{firstMs:y,lastMs:_,...w}=g;w.first_ts=new Date(y>0?y:p).toISOString(),w.last_ts=new Date(_>0?_:p).toISOString(),m.push(w)}let h={lease:0,binding:1,claim:2,path:3,none:4};return m.sort((g,y)=>h[g.attribution_source]-h[y.attribution_source]||(g.object_id??"").localeCompare(y.object_id??"")||g.model.localeCompare(y.model)||g.context_tier.localeCompare(y.context_tier)),m}function ic(e,t){let n=new Map;for(let i of e){let a=new Set;for(let c of i.edited_paths){if(!Qa(c))continue;let l=t(C0(c));l&&a.add(l)}for(let c of a)n.set(c,(n.get(c)??0)+1)}let r=null,s=0;for(let[i,a]of n)(a>s||a===s&&r!==null&&i.length>r.length)&&(r=i,s=a);return r}function C0(e){let t=e.split(ec).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var xh,Xa,Rh=b(()=>{"use strict";ai();o(Sh,"normalizeModelId");xh=2e5,Xa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(di,"msOf");o(tc,"parseCostContext");o(Eh,"toRepoRelative");o(R0,"underPrefix");o(nc,"prefixesOverlap");o(Ah,"sortedAnchors");o(rc,"anchorFor");o(I0,"bestAnchorOverlapping");o(Za,"inWindow");o(Th,"assignTurn");o(sc,"sliceSession");o(ic,"dominantCheckoutRoot");o(C0,"dirOf")});import{createReadStream as N0,existsSync as O0}from"node:fs";import{createInterface as D0}from"node:readline";function Ih(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function $0(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
132
|
+
`)}function Oh(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 L0(e){let t=e.message?.role;if(t==="assistant")return{holder:Ih(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=Ih(e.message?.content),r=$0(n);return r.includes(P0)?{holder:"human",genuine:!1}:n.some(i=>i.type==="tool_result"&&i.is_error===!0&&typeof i.content=="string"&&i.content.includes(M0))?{holder:"agent",genuine:!1}:n.some(i=>i.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function oc(e){let t=Oh("");if(!e||!O0(e))return t;let n=null,r=0,s=0,i=null,a="human",c=[];return await new Promise(l=>{let d=N0(e,{encoding:"utf-8"}),u=D0({input:d}),p=o(m=>{let h=m.trim();if(!h)return;let g;try{g=JSON.parse(h)}catch{return}if(!t.session_id){let w=g.sessionId??g.session_id;typeof w=="string"&&w&&(t.session_id=w)}if(g.isSidechain===!0)return;let y=typeof g.timestamp=="string"?Date.parse(g.timestamp):NaN;if(!Number.isFinite(y)||i!==null&&y<i)return;let _=L0(g);if(_!==null){if(t.event_count++,_.genuine&&t.turn_count++,n===null&&(n=y),r=y,i!==null){let w=y-i;a==="agent"?s+=w:w>=Ch*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(w/1e3),c.length<Nh&&c.push({offset_seconds:Math.round((i-n)/1e3),duration_seconds:Math.round(w/1e3)}))}i=y,a=_.holder}},"processLine");u.on("line",m=>{try{p(m)}catch{}}),u.on("close",()=>l()),u.on("error",()=>l()),d.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(s/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var P0,M0,Ch,Nh,Dh=b(()=>{"use strict";P0="[Request interrupted by user",M0="The user doesn't want to proceed with this tool use",Ch=60,Nh=200;o(Ih,"asBlocks");o($0,"textOf");o(Oh,"emptySpan");o(L0,"classify");o(oc,"analyzeSpan")});import{createReadStream as F0,existsSync as j0}from"node:fs";import{createInterface as U0}from"node:readline";function G0(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function ui(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function W0(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(`
|
|
133
|
+
`)}return""}async function ac(e,t={}){if(!e||!j0(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Ga(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),s=t.initialEffort??null,i=t.initialModes?{...t.initialModes}:Ga(),a=t.start??0;return await new Promise(c=>{let l=F0(e,{encoding:"utf-8",start:t.start??0}),d=U0({input:l});d.on("line",p=>{a+=Buffer.byteLength(p,"utf-8")+1;let m=p.trim();if(!m)return;let h;try{h=JSON.parse(m)}catch{return}let g=h.sessionId??h.session_id??"",y=h.timestamp?Date.parse(h.timestamp):Date.now(),_=h.message?.role;if(h.type==="ai-title"&&typeof h.aiTitle=="string"){n.push({kind:"title",session_id:g,ts:y,title:h.aiTitle});return}if(h.type==="attachment"&&h.attachment?.type){let w=H0[h.attachment.type];w&&(i[G0(w.mode)]=w.active,n.push({kind:"mode",session_id:g,ts:y,mode:w.mode,active:w.active}));return}if(_==="user"){let w=W0(h.message?.content),k=Sr(w);k&&(s=k);let x={session_id:g,ts:y,text:w,effort_directive:k};n.push({kind:"user",...x});return}if(_==="assistant"){let w=h.message?.usage,k=typeof h.message?.id=="string"&&h.message.id?h.message.id:null,x=typeof h.requestId=="string"&&h.requestId?h.requestId:null,S=k??x,I=S!==null&&r.has(S);S!==null&&!I&&r.add(S);let $={session_id:g,ts:y,model:h.message?.model??null,input_tokens:I?0:ui(w?.input_tokens),output_tokens:I?0:ui(w?.output_tokens),cache_read_input_tokens:I?0:ui(w?.cache_read_input_tokens),cache_creation_input_tokens:I?0:ui(w?.cache_creation_input_tokens),effort:s,isSidechain:h.isSidechain===!0,...i.ultracode?{ultracode:!0}:{},...i.planMode?{planMode:!0}:{},...i.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...$})}});let u=o(()=>({events:n,bytesRead:a,effortAtEnd:s,modesAtEnd:{...i},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var H0,Ph=b(()=>{"use strict";ii();Wa();H0={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}};o(G0,"modeFlagKey");o(ui,"num");o(W0,"extractUserText");o(ac,"streamTranscript")});var Mh=b(()=>{"use strict"});import{homedir as B0}from"node:os";import{join as K0}from"node:path";function lc(e){return e.replace(/[/.]/g,"-")}var V0,cc,$h=b(()=>{"use strict";V0=B0(),cc=K0(V0,".claude","projects");o(lc,"projectPathFromCwd")});var Pn=b(()=>{"use strict";Wa();uh();ph();bh();wh();ai();Ja();vh();Rh();Dh();Ph();ii();Mh();$h()});function dc(e,t){let n=e.split(/[.+-]/).slice(0,3).map(s=>Number.parseInt(s,10)||0),r=t.split(/[.+-]/).slice(0,3).map(s=>Number.parseInt(s,10)||0);for(let s=0;s<3;s++)if(n[s]!==r[s])return n[s]-r[s];return 0}function nA(e){if(e.raw===null)return null;if(e.kind==="toml"){let t=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!t)return null;let n=/^\s*command\s*=\s*"([^"]*)"/m.exec(t[1]),r=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(t[1]);return n?{command:n[1],args:r?[...r[1].matchAll(/"([^"]*)"/g)].map(s=>s[1]):[]}:null}try{let n=JSON.parse(e.raw).mcpServers?.maind;return!n||typeof n.command!="string"?null:{command:n.command,args:Array.isArray(n.args)?n.args.filter(r=>typeof r=="string"):[]}}catch{return null}}function $t(e,t){let n=`npm i -g ${Er}@${e}`;return t?`nvm use ${t} && ${n}`:n}function Uh(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(d=>d.bridgeVersion).filter(d=>d!==null)],r=e.latestVersion??n.sort(dc).at(-1)??e.runningVersion;e.latestVersion===null&&t.push({check:"version",level:"info",message:`doctor ${e.runningVersion}; the npm registry was not reachable, so "published" is unknown and installs are not compared.`});let s=e.nodeTrees.filter(d=>d.bridgeVersion!==null);if(e.nodeTrees.length>0){let d=e.pathWinner?.node??null,u=e.nodeTrees.find(m=>m.node===d);if(e.pathWinner===null?t.push({check:"node-trees",level:"error",message:"no `maind-mcp-bridge` on PATH \u2014 a client configured with the bare command cannot start it.",fix:$t(r,e.nvmDefault)}):u&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${u.node} tree (${u.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let m=e.nodeTrees.find(h=>h.node===e.nvmDefault);m&&m.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${m.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:$t(r,m.node)})}if(new Set(s.map(m=>m.bridgeVersion)).size>1)for(let m of s.filter(h=>dc(h.bridgeVersion,r)<0))t.push({check:"node-trees",level:"warn",message:`${m.node} carries bridge ${m.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:$t(r,m.node)})}let i=!1,a=new Map,c=o((d,u)=>{let p=a.get(d)??{version:e.installVersionOf(d),clients:[]};p.clients.push(u),a.set(d,p)},"noteInstall");for(let d of e.clientConfigs){let u=nA(d);if(u===null)continue;if(i=!0,/(^|\/)npx(\.cmd)?$/.test(u.command)&&u.args.some(h=>h.includes(Er))){t.push({check:"client-config",level:"warn",message:`${d.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${$t(r)}, then set "command": "maind-mcp-bridge" (no args) in ${d.path}`});continue}let m=/(^|[\\/])node(\.exe)?$/.test(u.command);if(m&&u.args.length>0){let h=u.args[0];if(!e.fileExists(h)){t.push({check:"client-config",level:"error",message:`${d.label} runs ${h}, which does not exist.`,fix:`re-run \`npx -y ${Er}@${r} install\` to rewrite the entry`});continue}c(h,d.label)}else if(u.command.includes("/")||u.command.includes("\\")){if(!e.fileExists(u.command)){t.push({check:"client-config",level:"error",message:`${d.label} points at ${u.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${d.path} (after ${$t(r)})`});continue}}else if(u.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${d.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:$t(r,e.nvmDefault)});continue}m||(u.command.includes("/")||u.command.includes("\\")?c(u.command,d.label):u.command==="maind-mcp-bridge"&&e.pathWinner&&c(e.pathWinner.path,d.label)),t.push({check:"client-config",level:"ok",message:`${d.label}: ${[u.command,...u.args].join(" ")}`})}if(i||t.push({check:"client-config",level:"warn",message:"no MCP client config names a `maind` server.",fix:`npx -y ${Er} install`}),e.latestVersion!==null)for(let[d,u]of a){let p=u.clients.join(", ");if(u.version===null)t.push({check:"version",level:"info",message:`${p}: cannot tell which bridge version ${d} is.`});else if(dc(u.version,e.latestVersion)<0){let m=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(d)?.[1]??null;t.push({check:"version",level:"warn",message:`${p} run bridge ${u.version} (${d}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:m?$t(e.latestVersion,m):`npx -y ${Er}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${p} run bridge ${u.version} (published: ${e.latestVersion}).`})}for(let d of e.npxStaleDirs)t.push({check:"npx-cache",level:"error",message:`a half-built better-sqlite3 was left in ${d} \u2014 every npx start of this entry now fails with ENOTEMPTY.`,fix:`rm -rf '${d.replace(/'/g,"'\\''")}'`});let l=e.envApiKey??e.apiKey;if((e.deviceId===null||!jh.test(e.deviceId))&&t.push({check:"credentials",level:"error",message:"no valid device id \u2014 the server binds keys to a device, so every call ends in 401 invalid_or_device_required.",fix:"maind-mcp-bridge --reauth"}),l===null?t.push({check:"credentials",level:"error",message:"no API key stored and none in MAIND_API_KEY.",fix:"maind-mcp-bridge --reauth"}):tA.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&jh.test(e.deviceId)?"ok":"info",message:`key ${l.slice(0,12)}\u2026 present${e.envApiKey?" (from MAIND_API_KEY)":""}. Whether the server still binds it to this device only the server can say \u2014 a 401 invalid_or_device_required means re-pair.`}):t.push({check:"credentials",level:"error",message:`the ${e.envApiKey?"MAIND_API_KEY value":"stored key"} is not a maind key (mnd_<8 hex>_<56 hex>).`,fix:e.envApiKey?"fix or remove MAIND_API_KEY in the client config":"maind-mcp-bridge --reauth"}),e.claudeSettings!==null){let d=Ot(e.claudeSettings,{fileExists:o(p=>e.fileExists(p),"fileExists")}),u=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let p of d){if(p.status==="missing")continue;if(p.status!=="ok"){t.push({check:"hooks",level:p.status==="broken"?"error":"warn",message:p.detail});continue}let m=p.command?/(\S+\/build\/index\.js)/.exec(p.command)?.[1]??null:null,h=m?e.installVersionOf(m):null;h!==null&&u!==null&&h!==u&&t.push({check:"hooks",level:"warn",message:`${p.event}/${p.subcommand} runs bridge ${h}, the MCP server runs ${u} \u2014 writer and reader of the presence snapshot must be the same install.`,fix:`point the hook at the same install as the server: ${e.pathWinner?.path??"maind-mcp-bridge"} ${p.subcommand}`})}t.some(p=>p.check==="hooks")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}return t}function Hh(e){let t={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...e].sort((a,c)=>n[a.level]-n[c.level]).flatMap(a=>[`${t[a.level]} [${a.check}] ${a.message}`,...a.fix?[` fix: ${a.fix}`]:[]]),s=e.filter(a=>a.level==="error").length,i=e.filter(a=>a.level==="warn").length;return r.push("",s+i===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${s} error(s), ${i} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
|
|
134
|
+
`)+`
|
|
135
|
+
`}var Er,tA,jh,Gh=b(()=>{"use strict";kn();Er="@maind-dev/mcp-bridge",tA=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,jh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(dc,"compareVersions");o(nA,"maindEntry");o($t,"installFix");o(Uh,"diagnose");o(Hh,"renderFindings")});var zh={};se(zh,{realProbe:()=>Vh,resolveNvmAlias:()=>Kh,runDoctor:()=>fA});import{execFileSync as rA}from"node:child_process";import{existsSync as fc,readFileSync as sA,readdirSync as uc,realpathSync as iA}from"node:fs";import{homedir as Ar,platform as fi}from"node:os";import{delimiter as oA,dirname as Wh,join as re}from"node:path";function Lt(e){try{return fc(e)?sA(e,"utf8"):null}catch{return null}}function aA(){try{let e=rA(fi()==="win32"?"npm.cmd":"npm",["view",Bh,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function pc(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:re(Ar(),".nvm")}function cA(){let e=re(pc(),"versions","node"),t=[];try{t=uc(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=Lt(re(e,n,"lib","node_modules","@maind-dev","mcp-bridge","package.json")),s=null;try{s=r?JSON.parse(r).version??null:null}catch{s=null}return{node:n,bridgeVersion:s}})}function Kh(e,t,n){let r=e.trim();for(let c=0;c<5;c++){let l=n(r);if(l===null)break;r=l.trim()}let s=[...t].sort((c,l)=>{let d=c.slice(1).split(".").map(Number),u=l.slice(1).split(".").map(Number);for(let p=0;p<3;p++)if(d[p]!==u[p])return(d[p]??0)-(u[p]??0);return 0});if(r==="node"||r==="stable")return s.at(-1)??null;let i=r.startsWith("v")?r:`v${r}`;if(t.includes(i))return i;let a=i.endsWith(".")?i:`${i}.`;return s.filter(c=>c.startsWith(a)).at(-1)??null}function lA(e){let t=Lt(re(pc(),"alias","default"));return t===null?null:Kh(t,e.map(n=>n.node),n=>{let r=Lt(re(pc(),"alias",n));return r===null?null:r})}function dA(){let e=fi()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(oA))if(t)for(let n of e){let r=re(t,n);if(fc(r)){let s=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:s?s[1]:null,path:r}}}return null}function uA(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:fi()==="win32"?re(process.env.LOCALAPPDATA??re(Ar(),"AppData","Local"),"npm-cache"):re(Ar(),".npm"),t=re(e,"_npx"),n=[],r=[];try{r=uc(t)}catch{return[]}for(let s of r)try{uc(re(t,s,"node_modules")).some(i=>i.startsWith(".better-sqlite3-"))&&n.push(re(t,s))}catch{}return n}function pA(e){let t;try{t=Wh(iA(e))}catch{return null}for(let n=0;n<6;n++){let r=Lt(re(t,"package.json"));if(r!==null)try{let i=JSON.parse(r);if(i.name===Bh)return i.version??null}catch{}let s=Wh(t);if(s===t)break;t=s}return null}function Vh(e=process.cwd()){let t=cA(),n=Lt(re(It(),"device-id")),r=Ms({projectRoot:e,homeDir:Ar(),platform:fi(),env:process.env}),s=null;try{s=B()}catch{s=null}let i=(process.env.MAIND_API_KEY??"").trim();return{runningVersion:H,latestVersion:aA(),nodeTrees:t,nvmDefault:lA(t),pathWinner:dA(),clientConfigs:Ps(r).map(a=>({label:a.label,path:a.path,kind:a.kind,raw:Lt(a.path)})),npxStaleDirs:uA(),claudeSettings:Lt(re(Ar(),".claude","settings.json")),fileExists:o(a=>fc(a),"fileExists"),installVersionOf:pA,deviceId:n===null?null:n.trim(),apiKey:s,envApiKey:i.length>0?i:null}}async function fA(e){let t=Uh(Vh());return e.includes("--json")?process.stdout.write(JSON.stringify({version:H,findings:t},null,2)+`
|
|
136
|
+
`):process.stdout.write(Hh(t)),t.some(n=>n.level==="error")?1:0}var Bh,qh=b(()=>{"use strict";ce();ga();Ze();Gh();Bh="@maind-dev/mcp-bridge";o(Lt,"readOrNull");o(aA,"latestVersion");o(pc,"nvmDir");o(cA,"nodeTrees");o(Kh,"resolveNvmAlias");o(lA,"nvmDefault");o(dA,"pathWinner");o(uA,"npxStaleDirs");o(pA,"installVersionOf");o(Vh,"realProbe");o(fA,"runDoctor")});async function Yh(e){return Ft("get_session_briefing",{tools:["claude-code"]},e)}async function Ft(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??mc,s=new AbortController,i=setTimeout(()=>s.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:s.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:mA,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),l=c.headers.get("mcp-session-id");if(await c.text().catch(()=>""),!c.ok||!l)return null;let d={...a,"mcp-session-id":l};await fetch(r,{method:"POST",headers:d,signal:s.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(y=>y.text().catch(()=>"")).catch(()=>"");let u=await fetch(r,{method:"POST",headers:d,signal:s.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!u.ok)return null;let m=(u.headers.get("content-type")??"").startsWith("text/event-stream")?await hA(u):await u.text();if(m.trim().length===0)return null;let h=JSON.parse(m);if(h.error||h.result?.isError)return null;let g=h.result?.content?.find(y=>y.type==="text"&&typeof y.text=="string")?.text;return typeof g=="string"&&g.trim().length>0?g:null}catch{return null}finally{clearTimeout(i)}}async function hA(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",s=[],i="",a=o(()=>{if(s.length===0)return;let c=s.join(`
|
|
129
137
|
`).trim();s=[],c.length>0&&(i=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
130
|
-
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&s.push(p.slice(5).replace(/^\s/,""))}}return a(),i}var
|
|
138
|
+
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&s.push(p.slice(5).replace(/^\s/,""))}}return a(),i}var mc,mA,Tr=b(()=>{"use strict";mc="https://mcp.maind.dev/mcp",mA="2025-06-18";o(Yh,"fetchSessionBriefing");o(Ft,"fetchToolText");o(hA,"readSseMessage")});function gA(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":te()}}async function Jh(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:gA(t),body:JSON.stringify({metrics:n})});if(!r.ok){let i=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:i.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 mi,hc=b(()=>{"use strict";ce();_n();mi=process.env.MAIND_ENDPOINT??yn("mcp-client-metrics-ingest");o(gA,"ingestHeaders");o(Jh,"postMetrics")});function Xh(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function Qh(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let s=r,i=Array.isArray(s.active_claims)?s.active_claims:[],a=[];for(let c of i){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let u=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;u<=0||a.push({path_prefix:l.path_prefix,note:typeof l.note=="string"?l.note:null,remaining_seconds:Math.round(u)})}n.push({session_id_short:typeof s.session_id_short=="string"?s.session_id_short:"?",is_own_user:s.is_own_user===!0,branch:typeof s.branch=="string"?s.branch:null,focus:typeof s.focus=="string"?s.focus:null,machine_label:typeof s.machine_label=="string"?s.machine_label:null,last_seen_seconds:typeof s.last_seen_seconds=="number"?s.last_seen_seconds:0,claims:a,working_paths:Array.isArray(s.working_paths)?s.working_paths.filter(c=>typeof c=="string"):[]})}return n}function Mn(e,t){if(t.hostPids.length>0){let r=e.find(s=>t.hostPids.includes(s.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 Rr(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function eg(e,t,n){let r=n.maxAgeMs??Zh,s=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(s)||s<0||s>r)return null;let i=s/1e3,a=Qh(e,i),c=[];for(let l of a)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let d of l.claims)Xh(t,d.path_prefix)&&c.push(`'${d.path_prefix}' is CLAIMED by peer session ${l.session_id_short}${l.branch?` (branch ${l.branch}`:" ("}${l.machine_label?`, ${l.machine_label}`:""}${l.focus?`, focus: "${l.focus}"`:""}, last seen ${Rr(l.last_seen_seconds+i)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${Rr(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(Xh(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${Rr(l.last_seen_seconds+i)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${Rr(i)} ago, advisory \u2014 never a lock):
|
|
131
139
|
`+c.map(l=>` \u2022 ${l}`).join(`
|
|
132
140
|
`)+`
|
|
133
|
-
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
|
|
134
|
-
${h}`:h}var
|
|
135
|
-
`),
|
|
141
|
+
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 tg(e,t){let n=typeof e?.own_session_id=="string"?e.own_session_id.toLowerCase():null,r=t!==null?t.toLowerCase():null;return r!==null&&n!==null&&n!==r?{id:r,announceError:null}:{id:e?.own_session_id??null,announceError:e?.announce_error??null}}function ng(e,t,n,r=Zh,s=null){if(!e)return null;let i=n-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let a=i/1e3,c=Qh(e,a),l=s!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${s}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let d=c.reduce((g,y)=>g+y.claims.length,0),u=c.filter(g=>g.focus===null&&g.working_paths.length===0&&g.claims.length===0).length,p=d>0?`${d} active claim${d===1?"":"s"}`:"no active claims",m=u>0?`, ${u} presence-only`:"",h=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${m}) as of ${Rr(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
|
|
142
|
+
${h}`:h}var Zh,gc=b(()=>{"use strict";o(Xh,"prefixConflict");Zh=10*6e4;o(Qh,"parsePeers");o(Mn,"selectOwnSnapshot");o(Rr,"ageDisplay");o(eg,"adviseOnPath");o(tg,"claimedIdentity");o(ng,"sessionStartSummary")});async function G(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=o(i=>{n||(n=!0,clearTimeout(s),t(i))},"settle"),s=setTimeout(()=>r({}),200);process.stdin.on("data",i=>e.push(i)),process.stdin.on("end",()=>{try{let i=Buffer.concat(e).toString("utf-8").trim();r(i?JSON.parse(i):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function $n(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function Re(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var Ie=b(()=>{"use strict";o(G,"readHookInput");o($n,"transcriptPathOf");o(Re,"toolFilePathOf")});function Ln(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function st(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function rg(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}var Fn=b(()=>{"use strict";o(Ln,"denyPayload");o(st,"advisoryPayload");o(rg,"postAdvisoryPayload")});import{realpathSync as yA}from"node:fs";import{basename as sg,dirname as ig,join as _A}from"node:path";function jt(e){let t=ig(e),n=[sg(e)];for(;;)try{let r=yA(t);return _A(r,...n.reverse())}catch{let r=ig(t);if(r===t)return e;n.push(sg(t)),t=r}}var hi=b(()=>{"use strict";o(jt,"realpathOfUnwritten")});import{mkdir as bA,readFile as wA,writeFile as vA,rename as kA}from"node:fs/promises";import{existsSync as ag}from"node:fs";import{homedir as SA}from"node:os";import{join as cg}from"node:path";function og(){return{config:null,sessions:{},pending_metrics:[]}}async function X(){if(!ag(gi))return og();try{let e=await wA(gi,"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)}
|
|
143
|
+
`),og()}}async function Ce(e){ag(Ut)||await bA(Ut,{recursive:!0,mode:448});let t=`${gi}.tmp`;await vA(t,JSON.stringify(e,null,2),{mode:384}),await kA(t,gi)}function yc(e){return e.thresholds??e.config?.thresholds??xA}var Ut,gi,xA,Ht=b(()=>{"use strict";Ut=cg(SA(),".maind"),gi=cg(Ut,"state.json"),xA={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};o(og,"emptyState");o(X,"loadState");o(Ce,"saveState");o(yc,"resolveThresholds")});import{existsSync as EA,realpathSync as AA,statSync as TA}from"node:fs";import{dirname as lg,isAbsolute as RA,join as IA}from"node:path";function OA(e,t){let n=e.filter(s=>dg.includes(s.id));if(n.length===0)return null;let r=n.map(s=>{let i=s.hint?`
|
|
136
144
|
\u2192 ${s.hint}`:"";return` \u2022 ${s.title}
|
|
137
145
|
${s.detail}${i}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
|
|
138
146
|
|
|
@@ -140,120 +148,120 @@ ${h}`:h}var yh,Ja=b(()=>{"use strict";o(gh,"prefixConflict");yh=10*6e4;o(_h,"par
|
|
|
140
148
|
|
|
141
149
|
`)+`
|
|
142
150
|
|
|
143
|
-
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
|
|
151
|
+
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 DA(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function PA(e,t,n,r=Date.now()){let s=e.repo_health_seen??{},i=s[t]??{};i[n]=new Date(r).toISOString(),s[t]=i,e.repo_health_seen=s}function _c(e){let t=lg(e);for(;;){try{if(TA(t).isDirectory())return t}catch{}let n=lg(t);if(n===t)return t;t=n}}async function MA(e,t,n){let r=await n.load();if(DA(r,e,t))return null;PA(r,e,t,n.now?.()),await n.save(r);let s;try{s=await n.check(t)}catch{return null}let i=s.filter(c=>dg.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:CA,metric_value:1},{session_id:e,metric_key:NA,metric_value:i}),await n.save(a),OA(s,t)}async function ug(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"";if(!n)return 0;let r=Re(e);if(!r)return 0;let s=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=RA(r)?r:IA(s,r),a=EA(i)?AA(i):jt(i),c=je(_c(a)),l=await MA(n,c,{load:X,save:Ce,check:o(async d=>(await zn(d,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(st(l)),0}catch{return 0}}var dg,CA,NA,bc=b(()=>{"use strict";hn();gn();Fn();Ie();hi();Ht();dg=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],CA="repo_health_hook_runs",NA="repo_health_hook_findings";o(OA,"formatRepoHealth");o(DA,"alreadySeen");o(PA,"markSeen");o(_c,"nearestExistingDir");o(MA,"repoHealthForEdit");o(ug,"runOnRepoHealth")});import{existsSync as $A,readFileSync as LA,realpathSync as FA}from"node:fs";import{isAbsolute as fg,join as mg,posix as jA,relative as UA,sep as HA}from"node:path";function pg(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function VA(e,t){return{contracts:t.filter(r=>pg(r.spec)===e||pg(r.impl)===e).map(r=>r.id),theme:BA.test(e),acl:KA.test(e)}}function zA(e){return e.contracts.length===0&&!e.theme&&!e.acl}function qA(e,t,n,r,s=Date.now()){let i=e.write_health_seen??{},a=i[t]??{},c=new Set(a[n]?.keys??[]),l=r.filter(d=>!c.has(d.key));if(l.length>0){for(let d of l)c.add(d.key);a[n]={at:new Date(s).toISOString(),keys:[...c]},i[t]=a,e.write_health_seen=i}return l}function YA(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:
|
|
144
152
|
|
|
145
153
|
`+e.map(n=>` \u2022 ${n.line}`).join(`
|
|
146
154
|
`)+`
|
|
147
155
|
|
|
148
|
-
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
|
|
149
|
-
`)}}catch{}try{let r=
|
|
150
|
-
`)}}catch{}return 0}function
|
|
156
|
+
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 JA(e,t){let n=UA(e,t);return!n||n.startsWith("..")||fg(n)?null:n.split(HA).join(jA.sep)}function XA(e){try{let t=LA(mg(e,Yr),"utf8"),{manifest:n}=Qr(t);return n?.contracts??[]}catch{return[]}}async function hg(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=Re(e);if(!n||!r)return 0;let s=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=fg(r)?r:mg(s,r),a=$A(i)?FA(i):jt(i),c=je(_c(a)),l=JA(c,a);if(l===null)return 0;let d=VA(l,XA(c));if(zA(d))return 0;let u=[];if(d.contracts.length>0)try{let g=await ct(c,{contracts:d.contracts});for(let y of g.findings)y.status==="open"&&u.push({key:`spec:${y.id}`,line:`spec-drift (${y.contract}): ${y.detail}`})}catch{}if(d.theme)try{let g=At(c);for(let y of g.findings)y.status==="open"&&u.push({key:`theme:${y.file}:${y.klass}`,line:`theme-class-drift: \`${y.klass}\` in ${y.file} \u2014 no token \`--color-${y.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(d.acl)try{let g=Et(c);for(let y of g.findings)y.status==="open"&&u.push({key:`acl:${y.id}`,line:`table-acl-lint: \`${y.table}\` (created in ${y.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let p=await X(),m=qA(p,n,c,u);p.pending_metrics.push({session_id:n,metric_key:GA,metric_value:1},{session_id:n,metric_key:WA,metric_value:m.length}),await Ce(p);let h=YA(m,l);return h!==null&&process.stdout.write(rg(h)),0}catch{return 0}}var GA,WA,BA,KA,gg=b(()=>{"use strict";hn();gn();Fn();Ie();bc();hi();Ht();GA="write_health_hook_runs",WA="write_health_hook_findings",BA=/\.(tsx?|jsx?|css)$/,KA=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;o(pg,"declPath");o(VA,"routesForPath");o(zA,"routesAreEmpty");o(qA,"takeUnreported");o(YA,"formatWriteHealth");o(JA,"repoRelative");o(XA,"readContracts");o(hg,"runOnWriteHealth")});var Rg={};se(Rg,{agentHostPidCandidates:()=>We,closeTrackedSession:()=>Sg,effectiveConfig:()=>Gt,grandparentPid:()=>Eg,recordGuardSignals:()=>kg,runFlush:()=>fT,runHookStatus:()=>mT,runOnFileEdit:()=>dT,runOnFileWrite:()=>lT,runOnRepoHealth:()=>ug,runOnSessionStart:()=>sT,runOnToolUse:()=>aT,runOnWriteHealth:()=>hg,runSessionEndMetrics:()=>vc,runSyncConfig:()=>gT,writeIdentitySideChannel:()=>wc});import{execFileSync as _g}from"node:child_process";import{existsSync as bi,readFileSync as bg,realpathSync as ZA}from"node:fs";import{writeFile as QA}from"node:fs/promises";import{homedir as wg}from"node:os";import{isAbsolute as _i,join as Ir,relative as vg}from"node:path";function kg(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let s=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"),i=n.includes("review_changes");if(!s&&!i)return;let a=e.guard_signals??{},c=a[t]??{},l=new Date(r).toISOString();s&&(c.consulted_at=l),i&&(c.reviewed_at=l),a[t]=c,e.guard_signals=a}function Sg(e,t,n=Date.now()){rT(e,n);let r=e.sessions[t];if(!r)return!1;let s=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,s)},{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 rT(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let s=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0);t-s>yi&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let s=Math.max(0,...Object.values(r).map(i=>Date.parse(i)||0));t-s>yi&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let s=Math.max(0,...Object.values(r).map(i=>Date.parse(i.at)||0));t-s>yi&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let s=Date.parse(r.started_at);!Number.isNaN(s)&&t-s>yi&&delete e.sessions[n]}}function Gt(e){if(e.config)return e.config;let t=B();return t===null?null:{api_key:t,endpoint:mi}}function xg(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 sT(){let e=await X();if(Gt(e)===null)return 0;let t=await G(),n=Tg(t);if(n===null)return 0;xg(e,n),await Ce(e);try{wc(t,n)}catch{}try{let r=z();if(r!==null){let s=Cn(r),i=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=Mn(s,{hostPids:We(),cwd:i}),c=tg(a?.snap??null,kr($n(t)||null,n)),l=ng(a?.snap??s[0]??null,c.id,Date.now(),void 0,c.announceError);l!==null&&process.stdout.write(l+`
|
|
157
|
+
`)}}catch{}try{let r=Ot(iT());if(ka(r)&&js(r)){let s=r.filter(i=>i.remedy==="run-install").map(i=>i.subcommand).join(", ");process.stderr.write(`[maind] New bridge capability not yet wired (${s}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
|
|
158
|
+
`)}}catch{}return 0}function iT(){try{let e=Ir(wg(),".claude","settings.json");return bi(e)?bg(e,"utf8"):null}catch{return null}}function wc(e,t,n,r=Nn()){let s=n??We();if(s.length===0)return;let i=kr($n(e)||null,t);if(i===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=$n(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of s)ah({dir:r,agentPid:d,sessionId:t,transcriptStem:i,cwd:a,transcriptPath:c,model:l})}function Eg(){try{if(process.platform==="win32")return null;let e=_g("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 We(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=Eg();return n!==null&&n>1&&n!==t&&e.push(n),e}async function aT(){let e=await X();if(Gt(e)===null)return 0;let t=await G(),n=Tg(t)??"unknown",r=xg(e,n);r.tool_call_count+=1;try{let a=We().filter(c=>ch(Nn(),c,oT));n!=="unknown"&&a.length>0&&wc(t,n,a)}catch{}let s=(t.tool_name??"").toString();(s.includes("search_lessons")||s.includes("get_session_briefing")||s.includes("get_lesson"))&&(r.lessons_consulted+=1),kg(e,n,s);let i=t.transcript_path;if(typeof i=="string"&&i&&!r.transcript_path&&(r.transcript_path=i),r.transcript_path){let a=await Ba(r.transcript_path);a&&(r.token_count=a.total_tokens,await pT(e,r))}return await Ce(e),0}function cT(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
|
|
151
159
|
`);return`${t.prefix}${e.number} is already taken:
|
|
152
160
|
${n}
|
|
153
161
|
|
|
154
162
|
Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
|
|
155
163
|
|
|
156
|
-
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
|
|
164
|
+
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 lT(){try{let e=await G();if((e.tool_name??"")!=="Write")return 0;let t=Re(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=_i(t)?t:Ir(n,t);if(bi(r))return 0;let s=je(n),i=vg(s,jt(r));if(i.length===0||i.startsWith("..")||_i(i))return 0;let a=await at(s,i);return!a.taken||a.namespace===null||process.stdout.write(Ln(cT(a,a.namespace))),0}catch{return 0}}async function dT(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=Re(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=_i(n)?n:Ir(r,n),i=z();if(i===null)return 0;let a=Cn(i);if(a.length===0)return 0;let c=Mn(a,{hostPids:We(),cwd:r});if(c===null)return 0;let l=je(r),d=bi(s)?ZA(s):jt(s),u=vg(l,d).replace(/\\/g,"/");if(u.length===0||u.startsWith("..")||_i(u))return 0;let p=eg(c.snap,u,{via:c.via,currentBranch:c.via==="cwd"?uT(r):null,nowMs:Date.now()});return p===null||process.stdout.write(st(p)),0}catch{return 0}}function uT(e){try{let n=_g("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 pT(e,t){let n=yc(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let s=r/n.model_token_limit,i="ok";if(s>=n.handoff_at_pct/100?i="handoff_recommended":s>=n.warn_at_pct/100&&(i="warn"),t.last_advisory_status===i||(t.last_advisory_status=i,i==="ok"))return;let a=Math.round(s*100),c={session_id:t.session_id,status:i,tokens:r,ratio:Number(s.toFixed(3)),pct:a,thresholds:n,suggested_next:i==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await QA(Ir(Ut,`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)}
|
|
157
165
|
`)}i==="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.
|
|
158
166
|
`):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.
|
|
159
|
-
`)}async function
|
|
160
|
-
`)}}async function
|
|
161
|
-
`),n.ok?0:1}async function
|
|
167
|
+
`)}async function vc(e){try{let t=await X(),n=Gt(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Sg(t,r),await Ce(t)),await Ag(n,tT)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
|
|
168
|
+
`)}}async function fT(){let e=await X(),t=Gt(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 Ag(t,nT);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
169
|
+
`),n.ok?0:1}async function Ag(e,t){let n=await X();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),s=Jh(e.endpoint,e.api_key,r),i=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([s,i]);if(a.ok){let c=await X();return c.pending_metrics=c.pending_metrics.slice(r.length),await Ce(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 mT(){let e=await X(),t=Gt(e),n=hT(),r=ka(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:yc(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(s=>({event:s.event,subcommand:s.subcommand,status:s.status,detail:s.detail})),...js(n.findings)?{remedy:yg}:{}}},null,2)+`
|
|
162
170
|
`),r){process.stderr.write(`
|
|
163
171
|
[maind] Claude Code hook wiring is incomplete:
|
|
164
172
|
`);for(let s of n.findings)s.status!=="ok"&&process.stderr.write(` \u2022 ${s.detail}
|
|
165
|
-
`);
|
|
166
|
-
`)}return 0}function
|
|
173
|
+
`);js(n.findings)&&process.stderr.write(` ${yg}
|
|
174
|
+
`)}return 0}function hT(){let e=Ir(wg(),".claude","settings.json"),t=null;try{bi(e)&&(t=bg(e,"utf8"))}catch{}return{settingsPath:e,findings:Ot(t)}}async function gT(){let e=await X(),t=Gt(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??eT,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)}
|
|
167
175
|
`),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
|
|
168
176
|
`);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
|
|
169
177
|
`),1}let s;try{s=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
|
|
170
178
|
`),1}let i=s;return typeof i.warn_at_pct!="number"||typeof i.handoff_at_pct!="number"||typeof i.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
|
|
171
|
-
`),1):(e.thresholds={warn_at_pct:i.warn_at_pct,handoff_at_pct:i.handoff_at_pct,model_token_limit:i.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await
|
|
172
|
-
`),0)}function
|
|
173
|
-
`)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([i,a])}async function
|
|
174
|
-
`)}return await
|
|
175
|
-
`,384)}var
|
|
176
|
-
`),1;let s={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},i=[];for(let l of
|
|
179
|
+
`),1):(e.thresholds={warn_at_pct:i.warn_at_pct,handoff_at_pct:i.handoff_at_pct,model_token_limit:i.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await Ce(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
|
|
180
|
+
`),0)}function Tg(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var eT,tT,nT,yi,oT,yg,kc=b(()=>{"use strict";Pn();hn();gn();ce();kn();ni();Qe();hc();gc();si();Ie();Fn();hi();Ht();_n();bc();gg();eT=process.env.MAIND_THRESHOLDS_ENDPOINT??yn("get-context-thresholds"),tT=1500,nT=1e4,yi=7*24*60*60*1e3;o(kg,"recordGuardSignals");o(Sg,"closeTrackedSession");o(rT,"gcState");o(Gt,"effectiveConfig");o(xg,"getOrCreateSession");o(sT,"runOnSessionStart");o(iT,"readSettingsRaw");o(wc,"writeIdentitySideChannel");oT=6e4;o(Eg,"grandparentPid");o(We,"agentHostPidCandidates");o(aT,"runOnToolUse");o(cT,"denyReason");o(lT,"runOnFileWrite");o(dT,"runOnFileEdit");o(uT,"currentGitBranch");o(pT,"maybeEmitAdvisory");o(vc,"runSessionEndMetrics");o(fT,"runFlush");o(Ag,"flushPending");o(mT,"runHookStatus");yg="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.";o(hT,"readHookWiring");o(gT,"runSyncConfig");o(Tg,"sessionIdOf")});function Ig(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Cg=b(()=>{"use strict";o(Ig,"resolveConnection")});function Og(e,t,n,r=Date.now()){let s=t===null?null:tc(t),i=sc(e,s,{repoRoot:n,nowMs:r});return i.length===0?null:{slices:i,context_ok:s!==null}}var Ng,Sc=b(()=>{"use strict";Pn();Ng=2e3;o(Og,"buildCostPayload")});function Pg(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!Dg.test(n))return null;let r=n.toLowerCase();return t!==null&&Dg.test(t)&&r!==t.toLowerCase()?null:r}var Dg,Mg=b(()=>{"use strict";Dg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(Pg,"snapshotSessionId")});async function $g(e){let t=e.now??Date.now,n=e.fetchContext(e.projectKey),{turns:r}=await xr(e.transcriptPath),s=e.resolveRoot?ic(r,e.resolveRoot):null,i=s&&e.projectKeyOf?e.projectKeyOf(s):null,a=s!==null&&i!==null&&i!==e.projectKey;a&&n.catch(()=>{});let[c,l,d]=await Promise.all([Va(e.transcriptPath,{turns:r}),oc(e.transcriptPath),a?e.fetchContext(i):n]),u=s??e.repoRoot;if(e.sessionId&&(c.session_id=e.sessionId,l.session_id=e.sessionId),c.maind_connected=e.connection(c.maind_connected==="connected",t()),!c.session_id)return{posted:!1,contextOk:d!==null,sentSlices:!1};let p=Og(r,d,u,t()),m=Ya(c,l,{client_session_id:e.coordSessionId,client:"claude-code"},"live_bridge",p);return await e.post(m,p!==null),{posted:!0,contextOk:p?.context_ok??d!==null,sentSlices:p!==null}}var Lg=b(()=>{"use strict";Pn();Sc();o($g,"ingestSessionEnd")});var Ug={};se(Ug,{runOnSessionEnd:()=>ET});import{execFileSync as xc}from"node:child_process";function _T(e,t){try{let n=z(),r=n!==null&&!Fa(process.env,Te()),s=null;if(n!==null){let i=Mn(Cn(n),{hostPids:We(),cwd:process.cwd()});if(i){let a=Date.parse(i.snap.written_at);s=Number.isFinite(a)?Math.max(0,t-a):null}}return Ig({ownSnapshotAgeMs:s,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function bT(e){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;try{let r=z();if(r!==null){let s=Mn(Cn(r),{hostPids:We(),cwd:process.cwd()}),i=Pg(s?.snap,e);if(i!==null)return i}}catch{}let n=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return t.test(n)?n:null}function wT(){try{let e=xc("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function vT(e){let t=Fg.get(e);if(t!==void 0)return t;let n=null;try{let r=xc("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();n=r.length>0?r:null}catch{n=null}return Fg.set(e,n),n}function kT(e){let t=jg.get(e);if(t!==void 0)return t;let n=null;try{let r=xc("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=ha(r))}catch{n=null}return jg.set(e,n),n}async function ST(e,t,n,r){if(n===null)return null;try{return await Ft("get_session_cost_context",{project_key:n,...r?{session_id:r}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:H,timeoutMs:Ng})}catch{return null}}async function xT(e,t,n,r,s){let i=fetch(yT,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":H},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=qa(za(await c.json().catch(()=>null)),s);l!==null&&process.stderr.write(`[maind] ${l}
|
|
181
|
+
`)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([i,a])}async function ET(){try{for(let s of We())lh(Nn(),s)}catch{}let e=B();if(!e)return 0;let t=await G(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=$n(t);if(r)try{let s=te(),i=bT(kr(r,n)),a=z();await $g({apiKey:e,deviceId:s,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:i,repoRoot:wT(),resolveRoot:vT,projectKeyOf:kT,fetchContext:o(c=>ST(e,s,c,i),"fetchContext"),post:o((c,l)=>xT(e,s,c,1500,l),"post"),connection:_T})}catch(s){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${s instanceof Error?s.message:String(s)}
|
|
182
|
+
`)}return await vc(n),0}var yT,Fg,jg,Hg=b(()=>{"use strict";Pn();Sn();ce();Tr();hc();gc();Ie();kc();ja();ni();Qe();si();Ze();Cg();Sc();Mg();Lg();yT=mi;o(_T,"connectionVerdict");o(bT,"presenceSessionId");o(wT,"sessionRepoRoot");Fg=new Map;o(vT,"gitRootOf");jg=new Map;o(kT,"projectKeyOfRoot");o(ST,"fetchCostContext");o(xT,"postWithTimeout");o(ET,"runOnSessionEnd")});function _e(e=process.env,t=Te()){let n=e.MAIND_GUARD;return{mode:n==="off"||n==="warn"||n==="block"?n:t?.guard_mode??"off",stopGate:t?.guard_stop_gate===!0}}async function jn(e,t=Ge()){let n={};try{let s=await ne(t);if(s!==null&&s.trim().length>0){let i=JSON.parse(s);typeof i=="object"&&i!==null&&!Array.isArray(i)&&(n=i)}}catch{}let r={...n,...e};await Y(t,JSON.stringify(r,null,2)+`
|
|
183
|
+
`,384)}var Wt=b(()=>{"use strict";Sn();Ue();o(_e,"resolveGuardConfig");o(jn,"writeGuardConfig")});function AT(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 s=e[++n];if(s!=="warn"&&s!=="block")return null;t.mode=s;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 Gg(e,t,n=process.stdout){let r=AT(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
|
|
184
|
+
`),1;let s={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},i=[];for(let l of Fs)i.push(await Aa(s,l));for(let l of i)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
|
|
177
185
|
`);let a=i.some(l=>l.detail==="user declined"),c=i.some(l=>l.status==="failed");return r.dryRun?(n.write(`
|
|
178
186
|
[dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
|
|
179
|
-
`),0):(await
|
|
187
|
+
`),0):(await jn({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
|
|
180
188
|
Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
|
|
181
189
|
flip: maind-mcp-bridge guard mode <warn|block>
|
|
182
190
|
disable: maind-mcp-bridge guard off (hooks stay wired, become no-ops)
|
|
183
191
|
check: maind-mcp-bridge guard status
|
|
184
192
|
Takes effect for NEW Claude Code sessions (hooks are read at session start).
|
|
185
193
|
`),a&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
|
|
186
|
-
`),c?1:0)}var
|
|
187
|
-
`;await
|
|
188
|
-
`);for(let l of s>0?c.slice(1):c)if(l.trim())try{let d=JSON.parse(l);typeof d.event=="string"&&d.event in t&&(t[d.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var
|
|
189
|
-
`),1):(await
|
|
190
|
-
`),0)}case"off":return await
|
|
194
|
+
`),c?1:0)}var Wg=b(()=>{"use strict";kn();Ta();Wt();o(AT,"parseGuardInstallFlags");o(Gg,"runGuardInstall")});import{existsSync as Bg}from"node:fs";import{mkdir as TT,readFile as RT,readdir as IT,rename as CT,stat as NT,unlink as OT,writeFile as DT}from"node:fs/promises";import{join as wi}from"node:path";function Kg(e){return wi(Cr,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function Be(e){try{let t=Kg(e);if(!Bg(t))return{};let n=JSON.parse(await RT(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function me(e,t){await TT(Cr,{recursive:!0,mode:448});let n=Kg(e),r=`${n}.tmp`;await DT(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await CT(r,n)}async function Vg(e=7*24*60*60*1e3,t=Date.now()){try{if(!Bg(Cr))return;for(let n of await IT(Cr)){if(!n.endsWith(".json"))continue;let r=wi(Cr,n);try{let s=await NT(r);t-s.mtimeMs>e&&await OT(r)}catch{}}}catch{}}var Un,Cr,Hn=b(()=>{"use strict";Ht();Un=wi(Ut,"guard"),Cr=wi(Un,"sessions");o(Kg,"sessionFile");o(Be,"loadGuardSession");o(me,"saveGuardSession");o(Vg,"sweepOldGuardSessions")});import{existsSync as PT}from"node:fs";import{appendFile as MT,mkdir as $T,open as LT}from"node:fs/promises";import{join as FT}from"node:path";async function le(e){try{await $T(Un,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
|
|
195
|
+
`;await MT(Gn,t,{mode:384})}catch{}}async function zg(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(!PT(Gn))return t;let n=await LT(Gn,"r");try{let r=(await n.stat()).size,s=Math.max(0,r-e),i=Buffer.alloc(r-s);await n.read(i,0,i.length,s);let c=i.toString("utf8").split(`
|
|
196
|
+
`);for(let l of s>0?c.slice(1):c)if(l.trim())try{let d=JSON.parse(l);typeof d.event=="string"&&d.event in t&&(t[d.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var Gn,Wn=b(()=>{"use strict";Hn();Gn=FT(Un,"events.jsonl");o(le,"appendGuardEvent");o(zg,"readGuardEventCounts")});var Yg={};se(Yg,{runGuard:()=>WT});import{existsSync as jT,readFileSync as UT}from"node:fs";import{homedir as qg}from"node:os";import{join as HT}from"node:path";async function WT(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Gg(n,qg());case"status":return KT();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
|
|
197
|
+
`),1):(await jn({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
198
|
+
`),0)}case"off":return await jn({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
|
|
191
199
|
`),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>
|
|
192
|
-
`),1):(await
|
|
193
|
-
`),0)}case"skip":return
|
|
194
|
-
`),1;let r=n.trim().slice(0,500),s=await
|
|
195
|
-
logged (auditable) in ${
|
|
196
|
-
`),0}async function
|
|
200
|
+
`),1):(await jn({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
201
|
+
`),0)}case"skip":return BT(n);default:return process.stdout.write(GT),t===void 0||t==="--help"||t==="-h"?0:1}}async function BT(e){let t=null,n=null;for(let i=0;i<e.length;i++)e[i]==="--session"?t=e[++i]??null:e[i]==="--reason"&&(n=e[++i]??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>"
|
|
202
|
+
`),1;let r=n.trim().slice(0,500),s=await Be(t);return await me(t,{...s,override_reason:r}),await le({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.
|
|
203
|
+
logged (auditable) in ${Gn}
|
|
204
|
+
`),0}async function KT(){let e=_e(),t=HT(qg(),".claude","settings.json"),n=null;try{jT(t)&&(n=UT(t,"utf8"))}catch{}let r=Ot(n,{},Fs),s=await zg();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:s,events_file:Gn},null,2)+`
|
|
197
205
|
`);let i=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"),i.length>0&&e.mode!=="off"){process.stderr.write(`
|
|
198
206
|
[maind] guard hook wiring is incomplete:
|
|
199
207
|
`);for(let a of i)process.stderr.write(` \u2022 ${a.detail}
|
|
200
|
-
`);i.some(a=>a.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var
|
|
201
|
-
`);o(
|
|
202
|
-
`),0):(process.stdout.write(
|
|
208
|
+
`);i.some(a=>a.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var GT,Jg=b(()=>{"use strict";kn();Wt();Wg();Wn();Hn();GT=["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(`
|
|
209
|
+
`);o(WT,"runGuard");o(BT,"runGuardSkip");o(KT,"runGuardStatus")});var ty={};se(ty,{BRIEFING_CACHE_FILE:()=>Zg,formatInjection:()=>ey,resolveBriefingInjection:()=>Qg,runGuardInject:()=>tR});import{existsSync as VT}from"node:fs";import{mkdir as zT,readFile as qT,rename as YT,writeFile as JT}from"node:fs/promises";import{dirname as XT,join as ZT}from"node:path";async function Qg(e,t,n={}){let r=n.nowMs??Date.now(),s=n.cacheFile??Zg,i=n.fetcher??Yh,a=await nR(s);if(a!==null&&r-Date.parse(a.fetched_at)<QT&&a.project_key===e)return{text:a.text,via:"cache"};let l=await i({apiKey:t,deviceId:sR(),projectKey:e,bridgeVersion:H,timeoutMs:eR});return l!==null?(await rR(s,{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 tR(){try{if(_e().mode==="off")return 0;let t=await G(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;await Vg();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let d=await Be(n);return await me(n,{...d,carryover:!0}),0}let s=B();if(s===null)return 0;let i=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=z(),c=await Qg(a,s),l=await Be(n);return c.text===null?(await me(n,{...l,inject_failed:!0}),await le({event:"inject_fail",session_id:n,cwd:i,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.
|
|
210
|
+
`),0):(process.stdout.write(ey(c.text,c.via)),await me(n,{...l,injected:!0}),await le({event:"inject_ok",session_id:n,cwd:i,project_key:a??void 0,detail:c.via}),0)}catch{return 0}}function ey(e,t){let n=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=e;return Buffer.byteLength(r,"utf8")>Xg&&(r=r.slice(0,Xg)+`
|
|
203
211
|
\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:
|
|
204
212
|
|
|
205
213
|
`+r+`
|
|
206
|
-
`}async function
|
|
214
|
+
`}async function nR(e){try{if(!VT(e))return null;let t=JSON.parse(await qT(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 rR(e,t){try{await zT(XT(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await JT(n,JSON.stringify(t,null,2),{mode:384}),await YT(n,e)}catch{}}function sR(){try{return te()}catch{return null}}var Zg,QT,eR,Xg,ny=b(()=>{"use strict";ce();Ie();Qe();Ze();Wt();Wn();Hn();Tr();Zg=ZT(Un,"briefing-cache.json"),QT=12*60*60*1e3,eR=3e3,Xg=10*1024;o(Qg,"resolveBriefingInjection");o(tR,"runGuardInject");o(ey,"formatInjection");o(nR,"readCache");o(rR,"writeCache");o(sR,"safeDeviceId")});var oy={};se(oy,{decideGate:()=>iy,runGuardGate:()=>oR});function iy(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:ry(n)}:(n.deny_count??0)>=sy?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. "+ry(n)}:{kind:"deny",reason:iR(e.sessionId,n)}}function ry(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 iR(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:
|
|
207
215
|
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
208
216
|
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
|
|
209
|
-
After ${
|
|
210
|
-
`,{mode:384}),await
|
|
211
|
-
`).filter(r=>r.trim());if(t.length<=
|
|
217
|
+
After ${sy} denies this gate downgrades itself to warn.`}async function oR(){try{let e=_e();if(e.mode==="off")return 0;let t=await G(),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 s=await Be(r),i=(await X()).guard_signals?.[r]?.consulted_at!==void 0,a=iy({mode:e.mode,session:s,consulted:i,sessionId:r}),c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),l=z()??void 0;return a.kind==="deny"?(process.stdout.write(Ln(a.reason)),await me(r,{...s,deny_count:(s.deny_count??0)+1}),await le({event:"deny",session_id:r,cwd:c,project_key:l}),0):a.kind==="warn"?(process.stdout.write(st(a.context)),await me(r,{...s,warned:!0,edits_seen:(s.edits_seen??0)+1}),await le({event:"warn",session_id:r,cwd:c,project_key:l}),0):(await me(r,{...s,edits_seen:(s.edits_seen??0)+1}),0)}catch{return 0}}var sy,ay=b(()=>{"use strict";Ie();Fn();Ht();Qe();Wt();Wn();Hn();sy=3;o(iy,"decideGate");o(ry,"warnText");o(iR,"denyText");o(oR,"runGuardGate")});var ly={};se(ly,{decideStopGate:()=>cy,runGuardStop:()=>cR});function cy(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function cR(){try{let e=_e();if(e.mode==="off"||!e.stopGate)return 0;let t=await G(),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 Be(n),s=(await X()).guard_signals?.[n]?.reviewed_at!==void 0;return cy({enabled:!0,editsSeen:r.edits_seen??0,reviewed:s,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:aR})),await me(n,{...r,stop_blocked:!0}),await le({event:"stop_block",session_id:n})),0}catch{return 0}}var aR,dy=b(()=>{"use strict";Ie();Ht();Wt();Wn();Hn();o(cy,"decideStopGate");aR="[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.";o(cR,"runGuardStop")});import{appendFile as lR,mkdir as dR,readFile as py,rename as fy,writeFile as my}from"node:fs/promises";import{homedir as hy}from"node:os";import{join as gy}from"node:path";function yy(e,t,n,r){if(t==="off"||e.length===0)return null;let s={},i=new Map,a=1/0,c=-1/0;for(let d of e){d.at<a&&(a=d.at),d.at>c&&(c=d.at);let u=s[d.tool]??={calls:0,warns:0,denies:0};if(d.event==="tool_call"?u.calls+=1:d.event==="policy_warn"||d.event==="sha_warn"?u.warns+=1:u.denies+=1,(d.event==="policy_warn"||d.event==="policy_deny")&&d.convention_id!==void 0&&d.convention_version!==void 0){let p=i.get(d.convention_id);(p===void 0||d.convention_version>p)&&i.set(d.convention_id,d.convention_version)}}let l=Object.entries(s).sort((d,u)=>u[1].calls+u[1].warns+u[1].denies-(d[1].calls+d[1].warns+d[1].denies)).slice(0,64);return{window_start:new Date(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:[...i.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function Bt(){return gy(hy(),".maind","gateway","attest-spool.jsonl")}async function Ec(e){let t=B();if(t===null)return!1;let n=await Ft("gateway_attest",{...e},{apiKey:t,deviceId:te(),projectKey:e.project_key??null,bridgeVersion:H,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function _y(e){try{await dR(gy(hy(),".maind","gateway"),{recursive:!0}),await lR(Bt(),JSON.stringify(e)+`
|
|
218
|
+
`,{mode:384}),await uR()}catch{}}async function uR(){try{let t=(await py(Bt(),"utf8")).split(`
|
|
219
|
+
`).filter(r=>r.trim());if(t.length<=uy)return;let n=`${Bt()}.${process.pid}.tmp`;await my(n,t.slice(-uy).join(`
|
|
212
220
|
`)+`
|
|
213
|
-
`,{mode:384}),await
|
|
214
|
-
`).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 s=null;try{s=JSON.parse(r)}catch{continue}await
|
|
221
|
+
`,{mode:384}),await fy(n,Bt())}catch{}}async function by(){let e;try{e=(await py(Bt(),"utf8")).split(`
|
|
222
|
+
`).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 s=null;try{s=JSON.parse(r)}catch{continue}await Ec(s)||(n=!0,t.push(r))}try{let r=`${Bt()}.${process.pid}.tmp`;await my(r,t.length>0?t.join(`
|
|
215
223
|
`)+`
|
|
216
|
-
`:"",{mode:384}),await
|
|
217
|
-
`,384)}async function
|
|
218
|
-
`),2;let n=
|
|
219
|
-
`);continue}let a=
|
|
220
|
-
`);continue}if(!(t.yes||await
|
|
224
|
+
`:"",{mode:384}),await fy(r,Bt())}catch{}}var uy,wy=b(()=>{"use strict";ce();Tr();Ze();uy=256;o(yy,"aggregateWindow");o(Bt,"attestSpoolPath");o(Ec,"postAttestation");o(_y,"spoolAttestation");o(uR,"capSpool");o(by,"flushAttestSpool")});function Nr(e=process.env,t=Te()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function vi(e=process.env,t=Te()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function vy(e,t=Ge()){let n={};try{let s=await ne(t);if(s!==null&&s.trim().length>0){let i=JSON.parse(s);typeof i=="object"&&i!==null&&!Array.isArray(i)&&(n=i)}}catch{}let r={...n,...e};await Y(t,JSON.stringify(r,null,2)+`
|
|
225
|
+
`,384)}async function ky(e,t=Ge()){await vy({gateway_mode:e},t)}async function Sy(e,t=Ge()){await vy({gateway_attest:e},t)}function xy(e=process.env,t=Te()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var Ac=b(()=>{"use strict";Sn();Ue();o(Nr,"resolveGatewayMode");o(vi,"resolveGatewayAttest");o(vy,"writeGatewayConfigPatch");o(ky,"writeGatewayMode");o(Sy,"writeGatewayAttest");o(xy,"resolveShaProofMode")});function Ay(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 s=r,i=s.gateway_gate;if(typeof i!="object"||i===null)continue;let a=i;if(a.enabled!==!0)continue;let c=typeof s.id=="string"&&s.id.length>0&&s.id.length<=64?s.id:null,l=typeof s.version=="number"&&Number.isInteger(s.version)&&s.version>=1?s.version:null;if(c===null||l===null)continue;let d=typeof s.severity=="string"&&pR.has(s.severity)?s.severity:"recommended",u=typeof s.summary=="string"?s.summary:"",p=Array.isArray(a.servers)?a.servers.filter(h=>typeof h=="string"&&h.length>0):null;if(p!==null&&p.length===0)continue;let m=Array.isArray(a.deny_tools)?a.deny_tools.filter(h=>typeof h=="string"&&h.length>0):[];for(let h of m){if(n.length>=256)return n;n.push({tool:h,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function fR(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Ty(e,t,n,r){if(r==="off")return{kind:"allow"};let s=null;for(let i of n)fR(i,e,t)&&(s===null||Ey[i.severity]>Ey[s.severity])&&(s=i);return s===null?{kind:"allow"}:s.severity==="required"&&r==="enforce"?{kind:"deny",rule:s}:{kind:"warn",rule:s}}function Ry(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 pR,Ey,Tc=b(()=>{"use strict";pR=new Set(["required","recommended","info"]);o(Ay,"extractGatewayRules");Ey={required:2,recommended:1,info:0};o(fR,"ruleMatches");o(Ty,"decideToolCall");o(Ry,"policyDenyText")});import{mkdirSync as mR,readFileSync as hR,renameSync as gR,writeFileSync as yR}from"node:fs";import{homedir as _R}from"node:os";import{dirname as bR,join as wR}from"node:path";function Iy(){return wR(_R(),".maind","gateway","policy-cache.json")}function ki(e,t,n=new Date().toISOString()){try{let r={version:Rc,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},s=Iy();mR(bR(s),{recursive:!0});let i=`${s}.${process.pid}.tmp`;yR(i,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),gR(i,s)}catch{}}function Si(e){try{let t=hR(Iy(),"utf8"),n=JSON.parse(t);return n.version!==Rc||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:Rc,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var Rc,Ic=b(()=>{"use strict";Rc=1;o(Iy,"policyCachePath");o(ki,"writePolicyCache");o(Si,"readPolicyCache")});function Or(e=process.env){let t=e.MAIND_MCP_URL??mc,n=B();return{mcpUrl:t,keyFp:n?Ss(n):"anon"}}async function xi(e=6e3){let t=B();if(t===null)return null;let n=null;try{n=z()}catch{n=null}let r=await Ft("get_conventions",{},{apiKey:t,deviceId:te(),projectKey:n,bridgeVersion:H,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let s;try{s=JSON.parse(r)}catch{return null}return Ay(s)}var Cc=b(()=>{"use strict";gn();ce();Tr();Qe();Ze();Tc();o(Or,"policyIdentity");o(xi,"fetchGatewayRules")});function Dr(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 vR(e){if(Dr(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 kR(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:Dr(e)?{action:"skip",reason:"already-wrapped"}:vR(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Cy(e,t,n){let r=String(e.command),s=Array.isArray(e.args)?e.args.map(String):[],i=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=i||t.env?{...i??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...s]};return a&&(c.env=a),c}function Ny(e){if(!Dr(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 Oy(e){return Object.entries(e).map(([t,n])=>{let r=kR(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var Dy=b(()=>{"use strict";o(Dr,"isGatewayWrapped");o(vR,"isMaindProxyEntry");o(kR,"classifyServer");o(Cy,"wrapServerEntry");o(Ny,"unwrapServerEntry");o(Oy,"planRewrites")});var jy={};se(jy,{runGatewayInstall:()=>RR,runGatewayUninstall:()=>IR});import{existsSync as SR,readFileSync as xR}from"node:fs";import{homedir as ER}from"node:os";import{join as Py}from"node:path";import{createInterface as AR}from"node:readline";function My(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 $y(){return[{label:"Claude Code (project .mcp.json)",path:Py(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:Py(ER(),".claude.json")}]}async function Ly(e){let t=AR({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 Fy(e){let t=TR(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,s=r.mcpServers;return typeof s!="object"||s===null||Array.isArray(s)?null:{raw:r,servers:s}}catch{return null}}function TR(e){try{return SR(e)?xR(e,"utf8"):null}catch{return null}}async function RR(e){let t=My(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
226
|
+
`),2;let n=Ee({entryPath:Ae(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let s of $y()){let i=Fy(s.path);if(i===null){process.stderr.write(` skipped ${s.label} \u2014 no mcpServers object
|
|
227
|
+
`);continue}let a=Oy(i.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${s.label} \xB7 ${c.key} \u2014 ${c.reason}
|
|
228
|
+
`);continue}if(!(t.yes||await Ly(`Wrap MCP server '${c.key}' in ${s.label} with the maind gateway?
|
|
221
229
|
Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
|
|
222
230
|
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${s.label} \xB7 ${c.key}
|
|
223
|
-
`);continue}i.servers[c.key]=
|
|
224
|
-
`)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await
|
|
231
|
+
`);continue}i.servers[c.key]=Cy(i.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${s.label} \xB7 ${c.key}
|
|
232
|
+
`)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await Y(s.path,JSON.stringify(i.raw,null,2)+`
|
|
225
233
|
`,384)}return process.stderr.write(r>0?`
|
|
226
234
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
|
|
227
235
|
`:`
|
|
228
236
|
Nothing to wrap.
|
|
229
|
-
`),0}async function
|
|
230
|
-
`),2;let n=0;for(let r of
|
|
237
|
+
`),0}async function IR(e){let t=My(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
238
|
+
`),2;let n=0;for(let r of $y()){let s=Fy(r.path);if(s===null)continue;let i=!1;for(let[a,c]of Object.entries(s.servers)){if(!Dr(c)||!(t.yes||await Ly(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=Ny(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
|
|
231
239
|
`);continue}s.servers[a]=d,i=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
|
|
232
|
-
`)}!t.dryRun&&i&&await
|
|
240
|
+
`)}!t.dryRun&&i&&await Y(r.path,JSON.stringify(s.raw,null,2)+`
|
|
233
241
|
`,384)}return process.stderr.write(n>0?`
|
|
234
242
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
|
|
235
243
|
`:`
|
|
236
244
|
Nothing wrapped \u2014 nothing to restore.
|
|
237
|
-
`),0}var
|
|
245
|
+
`),0}var Uy=b(()=>{"use strict";Ue();vn();Dy();o(My,"parseFlags");o($y,"targets");o(Ly,"confirm");o(Fy,"loadConfig");o(TR,"readFileSafeSync");o(RR,"runGatewayInstall");o(IR,"runGatewayUninstall")});var Hy={};se(Hy,{runGatewayAttest:()=>NR,runGatewayMode:()=>CR,runGatewayPolicy:()=>PR});async function CR(e){let t=e[0];if(t===void 0){let n=Nr(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
|
|
238
246
|
`),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
239
|
-
`),2):(await
|
|
247
|
+
`),2):(await ky(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
|
|
240
248
|
`:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
|
|
241
249
|
`:`Convention policy is off; only explicit --deny-tool flags apply.
|
|
242
|
-
`)),0)}async function
|
|
250
|
+
`)),0)}async function NR(e){let t=e[0];if(t===void 0){let n=vi(),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)":""}.
|
|
243
251
|
`+(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.
|
|
244
252
|
`)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
|
|
245
|
-
`),2):(await
|
|
253
|
+
`),2):(await Sy(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.
|
|
246
254
|
`:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
|
|
247
|
-
`),0)}function
|
|
255
|
+
`),0)}function OR(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
|
|
248
256
|
`;let t="";for(let n of e){let r=n.servers===null?"*":n.servers.join(","),s=n.severity==="required"?"deny-capable":"warn-only";t+=` ${n.tool} [servers: ${r}] ${n.conventionId} v${n.conventionVersion} (${n.severity} \u2192 ${s})
|
|
249
|
-
`}return t}function
|
|
250
|
-
`):(
|
|
251
|
-
`))}let s=
|
|
257
|
+
`}return t}function DR(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 s=Math.floor(r/60);return s<24?`${s} h ago`:`${Math.floor(s/24)} d ago`}async function PR(e){let t=e.includes("--refresh"),n=Nr(),r=Or();if(t){let i=await xi();i===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
258
|
+
`):(ki(r,i),process.stdout.write(`maind: policy refreshed (${i.length} rule(s)).
|
|
259
|
+
`))}let s=Si(r);return process.stdout.write(`maind: gateway mode '${n}'
|
|
252
260
|
`),s===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
|
|
253
|
-
`),0):(process.stdout.write(`maind: policy from cache (${
|
|
254
|
-
`),process.stdout.write(
|
|
255
|
-
`),0)}var
|
|
256
|
-
`,{mode:384})}catch{}}function
|
|
261
|
+
`),0):(process.stdout.write(`maind: policy from cache (${DR(s)}, ${r.mcpUrl}):
|
|
262
|
+
`),process.stdout.write(OR(s.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
|
|
263
|
+
`),0)}var Gy=b(()=>{"use strict";Ac();Ic();Cc();o(CR,"runGatewayMode");o(NR,"runGatewayAttest");o(OR,"renderRules");o(DR,"cacheAge");o(PR,"runGatewayPolicy")});var zy={};se(zy,{gatewayEventsFile:()=>Ky,parseGatewayArgs:()=>Vy,runGateway:()=>HR});import{spawn as MR}from"node:child_process";import{appendFile as $R,mkdir as LR}from"node:fs/promises";import{homedir as Wy}from"node:os";import{basename as FR,join as By}from"node:path";import{createInterface as jR}from"node:readline";function Ky(){return By(Wy(),".maind","gateway","events.jsonl")}async function UR(e){try{let t=Ky();await LR(By(Wy(),".maind","gateway"),{recursive:!0}),await $R(t,JSON.stringify(e)+`
|
|
264
|
+
`,{mode:384})}catch{}}function Vy(e){let t=new Set,n=null,r=0;for(;r<e.length;){let s=e[r];if(s==="--deny-tool"){let i=e[r+1];if(!i)return null;t.add(i),r+=2;continue}if(s==="--label"){let i=e[r+1];if(!i)return null;n=i,r+=2;continue}if(s==="--"){let i=e[r+1];return i?{denyTools:t,label:n,command:i,args:e.slice(r+2)}:null}return null}return null}async function HR(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:S,runGatewayUninstall:I}=await Promise.resolve().then(()=>(Uy(),jy));return e[0]==="install"?S(e.slice(1)):I(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:S,runGatewayMode:I,runGatewayPolicy:$}=await Promise.resolve().then(()=>(Gy(),Hy));return e[0]==="mode"?I(e.slice(1)):e[0]==="attest"?S(e.slice(1)):$(e.slice(1))}let t=Vy(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
|
|
257
265
|
maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
258
266
|
maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
259
267
|
maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
@@ -263,54 +271,54 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
|
|
|
263
271
|
NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
|
|
264
272
|
install/uninstall rewrite Claude Code MCP configs (consent per server).
|
|
265
273
|
mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
|
|
266
|
-
`),2;let{denyTools:n,label:r,command:s,args:i}=t,a=r??
|
|
267
|
-
`),process.exitCode=1});let k=
|
|
268
|
-
`),g(
|
|
269
|
-
`),g(
|
|
270
|
-
`),g(
|
|
271
|
-
`),g(
|
|
272
|
-
`)}),k.on("close",()=>{w.stdin.end()});let x=await new Promise(S=>{w.on("exit",(I
|
|
273
|
-
`),await
|
|
274
|
-
`),a.warned[i]=c.current,await
|
|
275
|
-
`);let g=r.params?.name;process.stdout.write(
|
|
276
|
-
`);return}s=
|
|
274
|
+
`),2;let{denyTools:n,label:r,command:s,args:i}=t,a=r??FR(s),c=Nr(),l=xy(),d=l==="off"?null:Pr(),u=c==="off"?[]:Si(Or())?.rules??[];c!=="off"&&xi().then(S=>{S!==null&&(u=S,ki(Or(),S))}).catch(()=>{});let p=[],m=vi()&&B()!==null&&c!=="off",h=null;try{h=z()}catch{h=null}let g=o(S=>{UR(S),m&&p.push(S)},"record"),y=o(async()=>{if(!m)return;let S=yy(p.splice(0),c,a,h);S!==null&&(await Ec(S)||await _y(S))},"attestAndReset");m&&by().catch(()=>{});let _=setInterval(()=>{y()},30*6e4);_.unref();let w=MR(s,i,{stdio:["pipe","pipe","inherit"]});w.stdout.pipe(process.stdout),w.on("error",S=>{process.stderr.write(`[maind gateway] failed to start '${s}': ${String(S)}
|
|
275
|
+
`),process.exitCode=1});let k=jR({input:process.stdin,terminal:!1});k.on("line",S=>{let I=Kc(S);if(I.kind==="request"&&I.method==="tools/call"&&I.toolName){if(n.has(I.toolName)&&I.id!==void 0){process.stdout.write(Vt(I.id,I.toolName)+`
|
|
276
|
+
`),g(Ai("deny",a,I.toolName,Date.now()));return}let $=Ty(I.toolName,a,u,c);if($.kind==="deny"&&I.id!==void 0){process.stdout.write(Vt(I.id,I.toolName,Ry(I.toolName,$.rule))+`
|
|
277
|
+
`),g(Ti("policy_deny",a,I.toolName,Date.now(),$.rule.conventionId,$.rule.conventionVersion));return}($.kind==="warn"||$.kind==="deny")&&g(Ti("policy_warn",a,I.toolName,Date.now(),$.rule.conventionId,$.rule.conventionVersion));let U=Mr(S,d);if(U.length>0){let j=U.find(W=>W.verdict==="fabricated");if(j!==void 0&&l==="enforce"&&c==="enforce"&&I.id!==void 0&&j!==void 0&&I.id!==void 0){process.stdout.write(Vt(I.id,I.toolName,zt(j,!0))+`
|
|
278
|
+
`),g(Ri("sha_deny",a,I.toolName,Date.now()));return}let L=j??U[0];process.stderr.write(`[maind gateway] ${zt(L,!1)}
|
|
279
|
+
`),g(Ri("sha_warn",a,I.toolName,Date.now()))}g(Ai("tool_call",a,I.toolName,Date.now()))}w.stdin.write(S+`
|
|
280
|
+
`)}),k.on("close",()=>{w.stdin.end()});let x=await new Promise(S=>{w.on("exit",(I,$)=>{S(I??($?1:0))})});return clearInterval(_),await y(),x}var qy=b(()=>{"use strict";Ii();wy();Ac();Tc();Ci();Ic();Cc();ce();Qe();o(Ky,"gatewayEventsFile");o(UR,"logEvent");o(Vy,"parseGatewayArgs");o(HR,"runGateway")});var Lc={};se(Lc,{MAX_ENTRIES:()=>Nc,TTL_MS:()=>Pc,crossSessionDir:()=>Mc,decideCrossSession:()=>Xy,parseSessionDb:()=>Jy,pruneDb:()=>$c,runGuardCrossCheck:()=>JR,runGuardCrossObserve:()=>YR,staleReason:()=>Oc});import{mkdir as GR,readFile as WR,readdir as BR,stat as Yy,unlink as KR,writeFile as VR}from"node:fs/promises";import{homedir as zR}from"node:os";import{join as Dc}from"node:path";function Mc(){return Dc(zR(),".maind","cross-session")}function Jy(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[i,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[i]={m:c.m,t:c.t})}let s={};if(typeof n.warned=="object"&&n.warned!==null)for(let[i,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(s[i]=a);return{files:r,warned:s}}function $c(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Pc);return n.length>Nc&&(n=n.sort((r,s)=>r[1].t-s[1].t).slice(n.length-Nc)),{files:Object.fromEntries(n),warned:e.warned}}function Xy(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Oc(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 Zy(e){let t=Mc();return await GR(t,{recursive:!0}),Dc(t,`${e}.json`)}async function Qy(e,t){try{let n=await WR(await Zy(e),"utf8");return $c(Jy(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function e_(e,t){try{await VR(await Zy(e),JSON.stringify(t),{mode:384})}catch{}}async function qR(e){try{let t=Mc();for(let n of await BR(t)){if(!n.endsWith(".json"))continue;let r=Dc(t,n),s=await Yy(r).catch(()=>null);s&&e-s.mtimeMs>Pc&&await KR(r).catch(()=>{})}}catch{}}async function t_(e){try{return(await Yy(e)).mtimeMs}catch{return}}async function YR(e,t=Date.now()){try{if(_e().mode==="off")return 0;let r=e??await G(),s=typeof r.session_id=="string"?r.session_id:"",i=Re(r);if(!s||!i)return 0;let a=await t_(i);if(a===void 0)return 0;let c=await Qy(s,t);return c.files[i]={m:a,t},delete c.warned[i],await e_(s,$c(c,t)),await qR(t),0}catch{return 0}}async function JR(e,t=Date.now()){try{let n=_e();if(n.mode==="off")return 0;let r=e??await G(),s=typeof r.session_id=="string"?r.session_id:"",i=Re(r);if(!s||!i)return 0;let a=await Qy(s,t),c=Xy(a.files[i]?.m,await t_(i));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(Ln(Oc(i,c))+`
|
|
281
|
+
`),await le({event:"cross_session_deny",session_id:s,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i}),0):(a.warned[i]===c.current||(process.stdout.write(st(Oc(i,c))+`
|
|
282
|
+
`),a.warned[i]=c.current,await e_(s,a),await le({event:"cross_session_warn",session_id:s,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:i})),0)}catch{return 0}}var Pc,Nc,Fc=b(()=>{"use strict";Ie();Fn();Wt();Wn();Pc=48*3600*1e3,Nc=500;o(Mc,"crossSessionDir");o(Jy,"parseSessionDb");o($c,"pruneDb");o(Xy,"decideCrossSession");o(Oc,"staleReason");o(Zy,"dbPath");o(Qy,"loadDb");o(e_,"saveDb");o(qR,"sweepStaleSessionFiles");o(t_,"fileMtime");o(YR,"runGuardCrossObserve");o(JR,"runGuardCrossCheck")});var Uc={};se(Uc,{INDEX_REFRESH_WORKER:()=>s_,acquireLock:()=>o_,releaseLock:()=>jc,runIndexRefreshWorker:()=>sI,runOnIndexRefresh:()=>rI});import{spawn as XR}from"node:child_process";import{existsSync as ZR,mkdirSync as QR,rmdirSync as n_,statSync as eI}from"node:fs";import{join as r_}from"node:path";function i_(e){return r_(e,".maind","index-refresh.lock")}function nI(e){return r_(e,".maind","code-index.sqlite")}function o_(e,t=Date.now()){let n=i_(e);try{if(t-eI(n).mtimeMs<tI)return!1;n_(n)}catch{}try{return QR(n,{recursive:!1}),!0}catch{return!1}}function jc(e){try{n_(i_(e))}catch{}}async function rI(){try{let e=await G(),t=fe(typeof e.cwd=="string"?e.cwd:process.cwd());if(!ZR(nI(t))||!o_(t))return 0;let n=process.argv[1];if(n===void 0)return jc(t),0;XR(process.execPath,[n,s_,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function sI(){let e=process.argv[3]??fe();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(Ma(),Sm)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{jc(e)}return 0}var tI,s_,Hc=b(()=>{"use strict";Ie();wr();tI=30*6e4,s_="index-refresh-run";o(i_,"lockPath");o(nI,"indexDbPath");o(o_,"acquireLock");o(jc,"releaseLock");o(rI,"runOnIndexRefresh");o(sI,"runIndexRefreshWorker")});import{randomUUID as iI}from"node:crypto";import{createInterface as uS}from"node:readline";var a_=[["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 c_(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of a_)if(t.includes(n))return r;return null}o(c_,"mapClientInfoNameToFamily");function Bc(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Ei(t)||t.method!=="initialize")return null;let n=t.params;if(!Ei(n))return null;let r=n.clientInfo;if(!Ei(r))return null;let s=r.name,i=c_(typeof s=="string"?s:null);if(i===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:i,version:c}}o(Bc,"tryExtractInitializeClient");function Ei(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Ei,"isRecord");Ii();Ci();gn();var pS="https://mcp.maind.dev/mcp",pr=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{o(this,"BridgeReauthNeeded")}},Rs=class{static{o(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=Ss(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=fS(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=mS(r),this.clientVersionLocked=this.clientVersion!==null;let s=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=s&&/^[a-f0-9]{64}$/.test(s)?s:null,this.localRouter=t.localRouter??null,this.presence=t.presence??null,this.shaRepoRoot=Pr(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??pS}async run(){let t=uS({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 u=Bc(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&As(t)&&(this.initFrame=t);let r=yS(t),s=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=Mr(t,this.shaRepoRoot);if(u.length>0){let p=u.find(h=>h.verdict==="fabricated"),m=p??u[0];if(p!==void 0&&Yc(p)&&r.id!==null){let h=zt(p,!0);process.stderr.write(`[maind] ${h}
|
|
283
|
+
`);let g=r.params?.name;process.stdout.write(Vt(r.id,typeof g=="string"?g:"unknown",h)+`
|
|
284
|
+
`);return}s=zt(m,!1),process.stderr.write(`[maind] ${s}
|
|
277
285
|
`)}}if(this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let u=await this.localRouter.handleToolCall(r?.id??null,r?.params);process.stdout.write(u+`
|
|
278
|
-
`);return}let i=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(u){let p=
|
|
279
|
-
`);return}if(
|
|
280
|
-
`);return}if(s!==null){let u=d.startsWith("text/event-stream")?await
|
|
281
|
-
`);return}if(d.startsWith("text/event-stream"))await
|
|
282
|
-
`)}}}async handle401(t,n){let r=await t.text().catch(()=>""),s=r.toLowerCase();if(s.includes("device_mismatch")||s.includes("device_revoked")||s.includes("device_required")||s.includes("invalid or revoked"))throw this.terminated=!0,new
|
|
283
|
-
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${
|
|
286
|
+
`);return}let i=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(u){let p=Es(t);if(this.serveInitializeFromCache(t,p))return;Ts(p,-32603,`bridge network error: ${bS(u)}`);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&&!As(t)){let u=await c.text().catch(()=>"");if(_S(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=Es(t);Ts(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=Es(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;Ts(u,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let d=c.headers.get("content-type")??"";if(i&&this.localRouter){let u=d.startsWith("text/event-stream")?await ua(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
|
|
287
|
+
`);return}if(As(t)){let u=d.startsWith("text/event-stream")?await ua(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
|
|
288
|
+
`);return}if(s!==null){let u=d.startsWith("text/event-stream")?await ua(c):await c.text(),p=gS(u,s);p.trim().length>0&&process.stdout.write(p+`
|
|
289
|
+
`);return}if(d.startsWith("text/event-stream"))await hS(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
|
|
290
|
+
`)}}}async handle401(t,n){let r=await t.text().catch(()=>""),s=r.toLowerCase();if(s.includes("device_mismatch")||s.includes("device_revoked")||s.includes("device_required")||s.includes("invalid or revoked"))throw this.terminated=!0,new pr(wS(s));let a=Es(n);Ts(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}}),s=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),i=await s.text().catch(()=>"");if(!s.ok)throw new Error(`presence: upstream HTTP ${s.status}`);return vS(i)}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=je()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&mf(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!As(t))return!1;let r=hf(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(gf(n,r)+`
|
|
291
|
+
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${xs(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function fS(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}o(fS,"normalizeClientFamily");function mS(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}o(mS,"normalizeClientVersion");async function hS(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",s=[],i=o(()=>{if(s.length===0)return;let a=s.join(`
|
|
284
292
|
`).trim();s=[],a.length>0&&process.stdout.write(a+`
|
|
285
293
|
`)},"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(`
|
|
286
|
-
`))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){i();continue}u.startsWith(":")||u.startsWith("data:")&&s.push(u.slice(5).replace(/^\s/,""))}}}finally{i()}}o(
|
|
294
|
+
`))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){i();continue}u.startsWith(":")||u.startsWith("data:")&&s.push(u.slice(5).replace(/^\s/,""))}}}finally{i()}}o(hS,"pipeSseToStdout");function gS(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}}o(gS,"appendNoteToToolResult");function yS(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}o(yS,"parseRpc");async function ua(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",s=[],i=[],a=o(()=>{if(i.length===0)return;let c=i.join(`
|
|
287
295
|
`).trim();i=[],c.length>0&&s.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
288
296
|
`))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}}finally{a()}return s.join(`
|
|
289
|
-
`)}o(
|
|
290
|
-
`)}o(
|
|
291
|
-
`).map(a=>a.trim()).filter(a=>a.startsWith("data:"));if(i.length===0)return null;n=i[i.length-1].slice(5).trim()}let s=JSON.parse(n).result?.content?.[0]?.text;return typeof s!="string"?null:JSON.parse(s)}catch{return null}}o(
|
|
292
|
-
`),null));if(p){if(p.status==="approved")return
|
|
297
|
+
`)}o(ua,"collectSseText");function Es(e){try{return JSON.parse(e).id??null}catch{return null}}o(Es,"tryExtractId");function As(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}o(As,"isInitializeRequest");function _S(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")}o(_S,"isSessionLossBody");function bS(e){return e instanceof Error?e.message:String(e)}o(bS,"stringifyErr");function Ts(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
298
|
+
`)}o(Ts,"emitJsonRpcError");function wS(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}o(wS,"extractHint");function vS(e){try{let t=e.trim();if(t.length===0)return null;let n=t;if(!t.startsWith("{")){let i=t.split(`
|
|
299
|
+
`).map(a=>a.trim()).filter(a=>a.startsWith("data:"));if(i.length===0)return null;n=i[i.length-1].slice(5).trim()}let s=JSON.parse(n).result?.content?.[0]?.text;return typeof s!="string"?null:JSON.parse(s)}catch{return null}}o(vS,"parsePresenceToolResult");ce();ce();_n();import{spawn as OS}from"node:child_process";import{platform as DS}from"node:os";async function bn(e,t=process.stderr){let n=mr(),r=`${n}/device-authorization-start`,s=`${n}/device-authorization-poll`,i=Cs(e),a=`mcp-bridge-${i.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:i})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await LS(l.verification_uri_complete).catch(()=>{}),$S(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await MS(u);let p=await PS(s,l.device_code).catch(m=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(m)}
|
|
300
|
+
`),null));if(p){if(p.status==="approved")return Ct(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
|
|
293
301
|
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
|
|
294
302
|
`),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
|
|
295
303
|
`),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
|
|
296
|
-
`),null}o(
|
|
304
|
+
`),null}o(bn,"runDeviceFlow");async function PS(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()}o(PS,"pollOnce");function MS(e){return new Promise(t=>setTimeout(t,e))}o(MS,"sleep");function $S(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: ${vf(e.verification_uri,56)} \u2502`,` \u2502 Code: ${vf(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(`
|
|
297
305
|
`)+`
|
|
298
|
-
`)}o(
|
|
299
|
-
`))}o(
|
|
306
|
+
`)}o($S,"printAuthInstructions");function vf(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}o(vf,"pad");async function LS(e){let t,n;switch(DS()){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,s)=>{try{let i=OS(t,n,{stdio:"ignore",detached:!0});i.on("error",s),i.unref(),r()}catch(i){s(i)}})}o(LS,"openExternalBrowser");Ze();Qe();Ze();import*as $m from"node:os";function kf(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 s=e[n+1];if(s===void 0||s.startsWith("--"))throw new xe("--project-root requires a path argument");t.projectRoot=s,n++;break}case"--token":{let s=e[n+1];if(s===void 0||s.startsWith("--"))throw new xe("--token requires a token argument");t.token=s,n++;break}case"--one-click-token":{let s=e[n+1];if(s===void 0||s.startsWith("--"))throw new xe("--one-click-token requires a token argument");t.oneClickToken=s,n++;break}case"--one-click-exchange-url":{let s=e[n+1];if(s===void 0||s.startsWith("--"))throw new xe("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=s,n++;break}case"--client":{let s=e[n+1];if(s===void 0||s.startsWith("--"))throw new xe("--client requires a family argument (e.g. claude-code, cursor, windsurf, copilot, codex, claude-desktop)");t.client=s,n++;break}default:throw new xe(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}o(kf,"parseInstallFlags");var xe=class extends Error{static{o(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function Sf(){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(`
|
|
307
|
+
`))}o(Sf,"printInstallHelp");var Ns=class{static{o(this,"InstallReport")}results=[];add(t){this.results.push(t)}results_(){return this.results}summary(){let t=0,n=0,r=0;for(let s of this.results)s.status==="created"||s.status==="merged"||s.status==="skipped"||s.status==="would-create"||s.status==="would-merge"||s.status==="would-pair"?t++:s.status==="needs-user-decision"?n++:s.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_
|
|
300
308
|
`;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(d=>d.target.length)),r=Math.max(t[1].length,...this.results.map(d=>d.action.length)),s=Math.max(t[2].length,...this.results.map(d=>d.status.length)),i=Math.max(t[3].length,...this.results.map(d=>(d.detail??"").length)),a=o((d,u)=>d+" ".repeat(Math.max(0,u-d.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(s)} | ${"-".repeat(i)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],s)} | ${a(t[3],i)} |`),l.push(c);for(let d of this.results)l.push(`| ${a(d.target,n)} | ${a(d.action,r)} | ${a(d.status,s)} | ${a(d.detail??"",i)} |`);return l.join(`
|
|
301
309
|
`)+`
|
|
302
310
|
`}print(t){let n=this.summary();t.write(`
|
|
303
311
|
`),t.write(this.toMarkdownTable()),t.write(`
|
|
304
312
|
Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
|
|
305
|
-
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as
|
|
313
|
+
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as xf from"node:fs/promises";import*as et from"node:path";import*as Ef from"node:readline";var WS=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function Af(e){let t=et.resolve(e),n=t;for(;;){if(await Rf(n))return n;let r=et.dirname(n);if(r===n)return t;n=r}}o(Af,"detectProjectRoot");async function Tf(e){let n=et.resolve(e),r=[];for(;;){await Rf(n)&&r.push(n);let s=et.dirname(n);if(s===n)break;n=s}return r}o(Tf,"findAllProjectRoots");async function Rf(e){for(let t of WS)try{return await xf.access(et.join(e,t)),!0}catch{}return!1}o(Rf,"hasAnyMarker");async function If(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
|
|
306
314
|
Multiple project roots found between cwd and the filesystem root:
|
|
307
315
|
`),e.forEach((i,a)=>{process.stdout.write(` [${a+1}] ${i}
|
|
308
316
|
`)}),process.stdout.write(`
|
|
309
|
-
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=
|
|
310
|
-
`),null):e[s-1]}o(
|
|
311
|
-
`;if(n)return{target:e.key,action:i==="create"?"write":"merge",status:i==="create"?"would-create":"would-merge",detail:e.path};try{await
|
|
317
|
+
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=Ef.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(i=>{n.question("",a=>i(a.trim()))});if(n.close(),r==="")return e[0];let s=Number.parseInt(r,10);return Number.isNaN(s)||s<1||s>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
|
|
318
|
+
`),null):e[s-1]}o(If,"disambiguateProjectRoot");ga();vn();Ue();var hr="maind";async function jf(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 ne(e.path)}catch(u){return _a(e,"read",u)}let s,i="create";if(r===null||r.trim().length===0)s={};else{i="merge";try{s=JSON.parse(r)}catch(u){return _a(e,"parse",u)}}if(!tt(s))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"&&JS(s),c,l=!1;if(a){let u=s[hr];tt(u)&&Ff(u,t)&&(l=!0),c={...s,[hr]:Lf(u,t)}}else{let u=tt(s.mcpServers)?s.mcpServers:{},p=u[hr];tt(p)&&Ff(p,t)&&(l=!0),c={...s,mcpServers:{...u,[hr]:Lf(p,t)}}}if(l&&r!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let d=JSON.stringify(c,null,2)+`
|
|
319
|
+
`;if(n)return{target:e.key,action:i==="create"?"write":"merge",status:i==="create"?"would-create":"would-merge",detail:e.path};try{await Y(e.path,d)}catch(u){return _a(e,"write",u)}return{target:e.key,action:i==="create"?"write":"merge",status:i==="create"?"created":"merged",detail:e.path}}o(jf,"mergeJsonConfig");function Lf(e,t){let n=tt(e)&&tt(e.env)?e.env:{},r={...t.env};for(let[s,i]of Object.entries(n))!(s in r)&&typeof i=="string"&&(r[s]=i);return{command:t.command,args:[...t.args],env:r}}o(Lf,"mergeEntry");function JS(e){return!("mcpServers"in e||!(hr in e))}o(JS,"hasRootShape");function Ff(e,t){if(!tt(e)||e.command!==t.command||!XS(e.args,t.args)||!tt(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}o(Ff,"serverEntriesEqual");function XS(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}o(XS,"arrayEquals");function tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(tt,"isObject");function _a(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}o(_a,"failed");Ue();import{parse as ZS,stringify as QS}from"smol-toml";async function Uf(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 ne(e.path)}catch(g){return Ls(e,"read",g)}let s,i="create";if(r===null||r.trim().length===0)s={};else{i="merge";try{let g=ZS(r);if(!Nt(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};s=g}catch(g){return Ls(e,"parse",g)}}let a=Nt(s.mcp_servers)?s.mcp_servers:{},c=a.maind;if(Nt(c)&&ex(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Nt(c)&&Nt(c.env)?c.env:{},d={...t.env};for(let[g,y]of Object.entries(l))!(g in d)&&typeof y=="string"&&(d[g]=y);let u={command:t.command,args:[...t.args],env:d},p={...s,mcp_servers:{...a,maind:u}},m;try{m=QS(p),m.endsWith(`
|
|
312
320
|
`)||(m+=`
|
|
313
|
-
`)}catch(g){return
|
|
321
|
+
`)}catch(g){return Ls(e,"write",g)}let h=m.match(/^\[mcp_servers\.maind\]/gm)??[];if(h.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${h.length}`};if(n)return{target:e.key,action:i==="create"?"write":"merge",status:i==="create"?"would-create":"would-merge",detail:e.path};try{await Y(e.path,m)}catch(g){return Ls(e,"write",g)}return{target:e.key,action:i==="create"?"write":"merge",status:i==="create"?"created":"merged",detail:e.path}}o(Uf,"mergeTomlConfig");function ex(e,t){if(!Nt(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(!Nt(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}o(ex,"tomlServerEntryEqual");function Nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Nt,"isObject");function Ls(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}o(Ls,"failed");import*as He from"node:path";var tx="__STACK__";var nx="__INTENT__";var ba="https://mcp.maind.dev/mcp",rx=`?stack=${tx}&intent=${nx}`;function sx(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}o(sx,"buildStackAwareEndpoint");var oL=sx(ba,{stack:["nextjs","supabase"],intent:"mixed"}),yr=`## maind MCP integration \u2014 Mandatory consultation
|
|
314
322
|
|
|
315
323
|
This project uses the maind MCP server (mcp.maind.dev/mcp) as
|
|
316
324
|
authoritative source for vetted coding conventions and lessons. The
|
|
@@ -379,7 +387,7 @@ For non-trivial changes, resolve documentation path in this order:
|
|
|
379
387
|
If no path is discoverable, provide a guided fallback:
|
|
380
388
|
\`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
|
|
381
389
|
|
|
382
|
-
Full tool set + provenance via \`get_conventions\`.`;function
|
|
390
|
+
Full tool set + provenance via \`get_conventions\`.`;function ix(e){return`I want to add the **maind MCP server** to my AI coding agent.
|
|
383
391
|
|
|
384
392
|
- My stack: \`__STACK__\`
|
|
385
393
|
- MCP endpoint: \`${e}\`
|
|
@@ -575,7 +583,7 @@ written config.
|
|
|
575
583
|
|
|
576
584
|
--- Preamble block ---
|
|
577
585
|
|
|
578
|
-
${
|
|
586
|
+
${yr}`}o(ix,"buildAiPromptBody");function gr(e,t,n){let r=n?`
|
|
579
587
|
MAIND_CLIENT_FAMILY="${n}"`:"";return`#!/usr/bin/env bash
|
|
580
588
|
set -euo pipefail
|
|
581
589
|
|
|
@@ -610,7 +618,7 @@ ${n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":""}
|
|
|
610
618
|
config.mcpServers.maind = server;
|
|
611
619
|
fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
|
|
612
620
|
console.log("WROTE " + file);
|
|
613
|
-
NODE`}o(
|
|
621
|
+
NODE`}o(gr,"buildJsonConfigInstaller");function ox(e){return`#!/usr/bin/env bash
|
|
614
622
|
set -euo pipefail
|
|
615
623
|
|
|
616
624
|
CONFIG_FILE="$HOME/.codex/config.toml"
|
|
@@ -663,7 +671,7 @@ if (serverCount !== 1 || envCount !== 1) {
|
|
|
663
671
|
|
|
664
672
|
fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
|
|
665
673
|
console.log("WROTE " + file);
|
|
666
|
-
NODE`}o(
|
|
674
|
+
NODE`}o(ox,"buildCodexTomlInstaller");function ax(e=ba){let t=`${e}${rx}`;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:ix(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:`{
|
|
667
675
|
"mcpServers": {
|
|
668
676
|
"maind": {
|
|
669
677
|
"command": "npx",
|
|
@@ -674,7 +682,7 @@ NODE`}o(F_,"buildCodexTomlInstaller");function j_(e=Ai){let t=`${e}${M_}`;return
|
|
|
674
682
|
}
|
|
675
683
|
}
|
|
676
684
|
}
|
|
677
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the project .mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-code.sh",lang:"bash",template:
|
|
685
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the project .mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-code.sh",lang:"bash",template:gr(".mcp.json",t,"claude-code")}]},{id:"claude-desktop",label:"Claude Desktop",description:"Browser-pairing desktop config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:"~/Library/Application Support/Claude/claude_desktop_config.json",lang:"json",template:`{
|
|
678
686
|
"mcpServers": {
|
|
679
687
|
"maind": {
|
|
680
688
|
"command": "npx",
|
|
@@ -685,13 +693,13 @@ NODE`}o(F_,"buildCodexTomlInstaller");function j_(e=Ai){let t=`${e}${M_}`;return
|
|
|
685
693
|
}
|
|
686
694
|
}
|
|
687
695
|
}
|
|
688
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Claude Desktop. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-desktop.sh",lang:"bash",template:
|
|
696
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for Claude Desktop. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-claude-desktop.sh",lang:"bash",template:gr("$HOME/Library/Application Support/Claude/claude_desktop_config.json",t,"claude-desktop")}]},{id:"codex",label:"Codex CLI",description:"Browser-pairing Codex config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:"~/.codex/config.toml",lang:"toml",template:`[mcp_servers.maind]
|
|
689
697
|
command = "npx"
|
|
690
698
|
args = ["-y", "@maind-dev/mcp-bridge"]
|
|
691
699
|
|
|
692
700
|
[mcp_servers.maind.env]
|
|
693
701
|
MAIND_CLIENT_FAMILY = "codex"
|
|
694
|
-
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:
|
|
702
|
+
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:ox(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:`{
|
|
695
703
|
"mcpServers": {
|
|
696
704
|
"maind": {
|
|
697
705
|
"command": "npx",
|
|
@@ -702,7 +710,7 @@ MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",
|
|
|
702
710
|
}
|
|
703
711
|
}
|
|
704
712
|
}
|
|
705
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the workspace .mcp.json used by VS Code Copilot. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-copilot.sh",lang:"bash",template:
|
|
713
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for the workspace .mcp.json used by VS Code Copilot. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-copilot.sh",lang:"bash",template:gr(".mcp.json",t,"copilot")}]},{id:"agent-preamble",label:"Agent preamble files (CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, .cursorrules, .windsurfrules + optional SessionStart reminder)",description:"Idempotent shell script that creates or extends SIX artefacts: the five agent-preamble files (CLAUDE.md / AGENTS.md / .github/copilot-instructions.md / .cursorrules / .windsurfrules) plus a SessionStart-Reminder file at ~/.claude/maind-session-start-reminder.md (for Claude Code users \u2014 referenced by an optional SessionStart-Hook). Existing installations are detected via grep on the line `## maind MCP integration` (matches both the legacy soft variant and the new hardened variant). The script also emits a copy-paste JSON snippet for merging the SessionStart-Hook into ~/.claude/settings.json \u2014 manual merge step because naive append breaks JSON syntax. Switching between agents later does not require any MCP re-config. Drift-note: the five preamble files carry duplicated content (single source: this snippet's heredoc).",filename:"writes CLAUDE.md + AGENTS.md + .github/copilot-instructions.md + .cursorrules + .windsurfrules + ~/.claude/maind-session-start-reminder.md",lang:"bash",template:`#!/usr/bin/env bash
|
|
706
714
|
# maind agent-preamble installer \u2014 idempotent. Creates or extends:
|
|
707
715
|
# CLAUDE.md (Claude Code)
|
|
708
716
|
# AGENTS.md (Codex, Windsurf, newer Cursor \u2014 cross-agent standard)
|
|
@@ -719,7 +727,7 @@ set -e
|
|
|
719
727
|
|
|
720
728
|
read -r -d '' MAIND_BLOCK <<'MAIND_PREAMBLE_EOF' || true
|
|
721
729
|
|
|
722
|
-
${
|
|
730
|
+
${yr}
|
|
723
731
|
MAIND_PREAMBLE_EOF
|
|
724
732
|
|
|
725
733
|
mkdir -p .github
|
|
@@ -768,7 +776,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
768
776
|
}
|
|
769
777
|
}
|
|
770
778
|
}
|
|
771
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cursor/mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cursor.sh",lang:"bash",template:
|
|
779
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.cursor/mcp.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-cursor.sh",lang:"bash",template:gr("$HOME/.cursor/mcp.json",t,"cursor")}]},{id:"windsurf",label:"Windsurf",description:"Browser-pairing Windsurf config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:"~/.codeium/windsurf/mcp_config.json",lang:"json",template:`{
|
|
772
780
|
"mcpServers": {
|
|
773
781
|
"maind": {
|
|
774
782
|
"command": "npx",
|
|
@@ -779,7 +787,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
779
787
|
}
|
|
780
788
|
}
|
|
781
789
|
}
|
|
782
|
-
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codeium/windsurf/mcp_config.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-windsurf.sh",lang:"bash",template:
|
|
790
|
+
}`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codeium/windsurf/mcp_config.json. It merges the bridge-backed maind server and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-windsurf.sh",lang:"bash",template:gr("$HOME/.codeium/windsurf/mcp_config.json",t,"windsurf")}]},{id:"langchain-ts",label:"LangChain / LangGraph (TS)",description:"Bridge-backed stdio MCP client. The bridge opens browser pairing, creates a fresh device-bound key, and forwards calls to the stack-aware maind endpoint. Replace `__STACK__` with your stack slugs.",filename:"agent.ts",lang:"ts",template:`import { MultiServerMCPClient } from "@langchain/mcp-adapters";
|
|
783
791
|
|
|
784
792
|
const mcp = new MultiServerMCPClient({
|
|
785
793
|
maind: {
|
|
@@ -800,15 +808,15 @@ const tools = await mcp.getTools();
|
|
|
800
808
|
"env": {
|
|
801
809
|
"MAIND_MCP_URL": "${t}"
|
|
802
810
|
}
|
|
803
|
-
}`}]}o(
|
|
804
|
-
`:
|
|
805
|
-
`;return await
|
|
811
|
+
}`}]}o(ax,"buildSnippetTemplates");var aL=ax(ba);Ue();var cx="## maind MCP integration";function lx(e){return[{key:"preamble:CLAUDE.md",path:He.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:He.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:He.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:He.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:He.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:He.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}o(lx,"buildPreambleTargets");async function Hf(e,t=!1){let n=lx(e),r=[];for(let s of n)r.push(await dx(s,t));return r}o(Hf,"writePreambleFiles");async function dx(e,t){try{if(e.mayNeedParentDir&&!t&&await ya(He.dirname(e.path)),await Mf(e.path,cx))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await ne(e.path);if(t)return{target:e.key,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:e.path};let s=r===null||r.length===0?`${yr}
|
|
812
|
+
`:ux(r)+`${yr}
|
|
813
|
+
`;return await Y(e.path,s),{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}}}o(dx,"writeOnePreambleFile");function ux(e){return e.endsWith(`
|
|
806
814
|
|
|
807
815
|
`)?e:e.endsWith(`
|
|
808
816
|
`)?e+`
|
|
809
817
|
`:e+`
|
|
810
818
|
|
|
811
|
-
`}o(
|
|
819
|
+
`}o(ux,"ensureTrailingBlankLine");Ta();Sn();Ue();import*as qf from"node:readline";var Dt="config:auto_working_paths",Sx=`
|
|
812
820
|
Enable presence enrichment (auto working_paths)?
|
|
813
821
|
With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
|
|
814
822
|
locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
|
|
@@ -817,34 +825,34 @@ before editing the same area. Directory names only: never file contents, never
|
|
|
817
825
|
absolute paths. Server-side these paths are account-private (org members never
|
|
818
826
|
see them) and revocable any time on the dashboard consent page or via
|
|
819
827
|
{"auto_working_paths": false} in the bridge config.
|
|
820
|
-
[y/N]: `;async function
|
|
821
|
-
`;if(e.dryRun)return{target:
|
|
822
|
-
`)}let r=n===null?"":` (after exchange failure: ${n})`,s=
|
|
823
|
-
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw k}if(n.help)return
|
|
824
|
-
`),2;let a;if(n.projectRoot!==null)a=n.projectRoot;else{let k=await
|
|
828
|
+
[y/N]: `;async function Yf(e){let t=e.configPath??Ge(),n={};try{let a=await ne(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:Dt,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:Dt,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??xx)(e.out,Sx)}else return{target:Dt,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:Dt,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 s={...n,auto_working_paths:!0},i=JSON.stringify(s,null,2)+`
|
|
829
|
+
`;if(e.dryRun)return{target:Dt,action:"merge",status:"would-merge",detail:t};try{await Y(t,i,384)}catch(a){return{target:Dt,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:Dt,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}o(Yf,"applyWorkingPathsConsent");async function xx(e,t){e.write(t);let n=qf.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(s=>{n.question("",i=>s(i.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}o(xx,"promptYesNoDefaultNo");ce();async function Jf(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let s=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}),i={};try{i=await s.json()}catch{}return s.ok?i.status!=="exchanged"||typeof i.api_key!="string"||!i.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:i.api_key,plan:i.plan??"unknown"}:{ok:!1,reason:i.error??`http_${s.status}`}}catch(s){return s instanceof Error&&s.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:s instanceof Error?s.message:String(s)}}finally{clearTimeout(r)}}o(Jf,"exchangeOneClickToken");async function Qf(e){let t="browser-pair";if(e.token!==null)try{let i=Ex(e.token);return e.dryRun?{apiKey:i,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(fr(),Ct(i),{apiKey:i,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(i){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:Xf(i)}}}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 i=Cs(e.bridgeVersion),a=await Jf({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:i.device_id,label:wf(),clientMeta:{...i}});if(a.ok)return fr(),Ct(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,Zf(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
|
|
830
|
+
`)}let r=n===null?"":` (after exchange failure: ${n})`,s=B();if(s!==null)return{apiKey:s,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 i=await bn(e.bridgeVersion,Zf(e));return i===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:i.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${i.plan})${r}`}}}catch(i){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:Xf(i)}}}}o(Qf,"pairOrUseToken");function Ex(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}o(Ex,"validateTokenShape");function Xf(e){return e instanceof Error?e.message:String(e)}o(Xf,"errMessage");function Zf(e){return e.out??process.stdout}o(Zf,"out");_n();var Ax="install-completed",Tx=3e3;async function em(e){if(!e.enabled||e.apiKey===null)return;let t=yn(Ax),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:Ix(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:Rx(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,s=setTimeout(()=>r.abort(),Tx);try{await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${e.installerVersion}`},body:JSON.stringify(n),signal:r.signal})}catch{}finally{clearTimeout(s)}}o(em,"postInstallTelemetry");function Rx(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}o(Rx,"countStatuses");function Ix(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}o(Ix,"parseNodeMajor");wr();var nE="https://mcp.maind.dev/mcp";async function Lm(e){let t=Date.now(),n;try{n=kf(e)}catch(k){if(k instanceof xe)return process.stderr.write(`error: ${k.message}
|
|
831
|
+
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw k}if(n.help)return Sf(),0;let s=!!process.stdin.isTTY&&!n.nonInteractive,i=$m.homedir();if(i.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
|
|
832
|
+
`),2;let a;if(n.projectRoot!==null)a=n.projectRoot;else{let k=await Tf(process.cwd());if(k.length===0)a=await Af(process.cwd());else if(k.length===1)a=k[0];else{let x=await If(k,s);if(x===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
|
|
825
833
|
`);for(let S of k)process.stderr.write(` candidate: ${S}
|
|
826
|
-
`);return 2}a=x}}let c=new
|
|
834
|
+
`);return 2}a=x}}let c=new Ns,l=(process.env.MAIND_MCP_URL??"").trim()||nE;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
|
|
827
835
|
`),process.stdout.write(`maind install \u2014 project root: ${a}
|
|
828
836
|
`),process.stdout.write(` \u2014 mcp endpoint: ${l}
|
|
829
837
|
|
|
830
|
-
`);let d=await
|
|
838
|
+
`);let d=await Qf({bridgeVersion:H,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(c.add(d.result),d.result.status==="failed")return process.stderr.write(`
|
|
831
839
|
pairing failed: ${d.result.detail??"unknown"}
|
|
832
840
|
Skipping remaining steps.
|
|
833
|
-
`),c.print(process.stdout),2;let u=
|
|
841
|
+
`),c.print(process.stdout),2;let u=Ms({projectRoot:a,homeDir:i,platform:process.platform,env:process.env}),p=Ps(u);if(p=Pf(p,n.client),n.skipCodex&&(p=p.filter(k=>k.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.
|
|
834
842
|
`:`error: no client targets selected (did you skip all of them?)
|
|
835
|
-
`),c.print(process.stdout),2;for(let k of p){let x=
|
|
843
|
+
`),c.print(process.stdout),2;for(let k of p){let x=Df({mcpUrl:l,clientFamily:k.clientFamilyEnv}),S;k.kind==="json"?S=await jf(k,x,n.dryRun):S=await Uf(k,x,n.dryRun),c.add(S)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let k=await Hf({projectRoot:a,homeDir:i},n.dryRun);for(let x of k)c.add(x)}let m={homeDir:i,isInteractive:s,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await Vf(m));for(let k of await zf(m))c.add(k);c.add(await Yf({isInteractive:s,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let h=Cm();h.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${h.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await em({enabled:n.telemetry||n.full,installerVersion:H,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:d.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let g=c.exitCode(),y=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
|
|
836
844
|
DRY RUN finished in ${y}s. No files were modified. Re-run without --dry-run to apply.
|
|
837
845
|
`):process.stdout.write(`
|
|
838
846
|
Finished in ${y}s. Restart your MCP client so it picks up the new server entry.
|
|
839
|
-
`);let _=
|
|
847
|
+
`);let _=Ee({entryPath:Ae(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),w=_.fallbackReason===null?`${wn(_)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${w}
|
|
840
848
|
`),g===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.
|
|
841
|
-
`),g}o(Qf,"runInstall");mr();import{readFileSync as nx}from"node:fs";import{join as em}from"node:path";function Us(e){return e?Math.ceil(e.length/4):0}o(Us,"estimateTokens");var tm=1e6,Hs=class{static{o(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 nm(e){try{let t=nx(e,"utf8");return t.length>tm?t.slice(0,tm):t}catch{return""}}o(nm,"readFileCapped");function rx(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]}o(rx,"distinctFilePaths");function rm(e,t,n,r){try{let s=Us(n);if(e==="codebase_search"){let i=rx(t);if(i.length===0)return 0;let a=0;for(let c of i)a+=Us(nm(em(r,c)));return Math.max(0,a-s)}if(e==="codebase_snippet"){let i=t?.filePath;if(typeof i!="string"||i.length===0)return 0;let a=Us(nm(em(r,i)));return Math.max(0,a-s)}return 0}catch{return 0}}o(rm,"measureLocalToolSaved");hr();mr();import{createHash as fx}from"node:crypto";function Ws(e){return fx("sha256").update(e,"utf8").digest("hex")}o(Ws,"nodeKeyHash");var mx=["module","class","interface","function","method","type_alias","enum","variable"],va=[{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:mx,description:"Restrict to a symbol kind."},limit:{type:"number",description:"Max results (default 20)."}},required:["query"]}},{name:"codebase_trace",description:"Traverse the call/dependency graph from a symbol. direction 'out' = what this symbol calls/contains/imports; 'in' = what calls/depends on it. Returns edges as node_key \u2192 node_key with the edge kind. CALLS/EXTENDS are best-effort name heuristics.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"Start symbol's node_key (from codebase_search)."},direction:{type:"string",enum:["out","in"],description:"Traversal direction (default out)."},max_depth:{type:"number",description:"BFS depth 1\u20135 (default 3)."},limit:{type:"number",description:"Max edges returned (default 100)."}},required:["node_key"]}},{name:"codebase_snippet",description:"Return the exact source text of a symbol by node_key (read locally from disk \u2014 never uploaded). Use after codebase_search/trace to read a function/class without opening the file.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"The symbol's node_key."}},required:["node_key"]}},{name:"codebase_map",description:"Architecture overview of the indexed repo: symbol-kind distribution, languages, and the most-imported (highest fan-in) modules \u2014 a cheap way to orient in an unfamiliar codebase.",inputSchema:{type:"object",properties:{top_n:{type:"number",description:"How many top modules to list (default 10)."}}}},{name:"codebase_changes",description:"Enumerate the symbols in files you changed (git diff/status against the LOCAL index \u2014 runs on this machine, nothing is uploaded). Call after finishing an edit batch, before committing. The output includes a ready-to-paste `briefing_args` block with paths deliberately stripped \u2014 feed it to the cloud tool codebase_change_briefing to get the maind conventions and lessons that apply to exactly these symbols. Requires a built index (codebase_index) for symbol enumeration; files without index rows are counted but contribute no symbols.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."}}}},{name:"codebase_review_changes",description:"Review-grade change enumeration (ADR-228): like codebase_changes, but hunk-aware \u2014 each symbol is graded added|modified|co_located by intersecting git diff hunks with symbol spans (runs on this machine, nothing is uploaded), plus closed-enum risk_flags from the raw path list (SQL migrations, RLS/SECURITY DEFINER, CI workflows, env files \u2014 files the index itself cannot see). The output's `review_args` block is path-free by construction \u2014 feed it to the cloud tool review_changes for provenance-backed convention findings. It ALSO runs the four repo-health detectors (number collisions, spec drift, dead theme classes, table ACL \u2014 ADR-324) and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full keeps a run attestation-grade. diff_stats carries the attest anchors (head_sha, dirty, resolved base_sha \u2014 commit object hashes, no source): pass them through to review_verdict to persist a replayable review_runs record (ADR-230). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, a COMMIT on the shared base tree \u2014 one that a branch switch undone by a parallel session redirected there, which no success message reports and which `git push` would make worse, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],ym=new Set(va.map(e=>e.name));function J(e){return typeof e=="string"&&e.length>0?e:void 0}o(J,"str");var hx=10;function gx(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,s=0,i=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=hx&&r++,c>s&&(s=c);for(let d of a.ownership?.topAuthors??[])n.add(d.email.toLowerCase()||d.name);let l=a.lastCommits[0]?.dateIso;if(l){let d=Date.parse(l);Number.isFinite(d)&&d>i&&(i=d)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:s,distinct_authors:n.size,newest_change_age_days:i>0?Math.max(0,Math.floor((t-i)/864e5)):0}}o(gx,"aggregateHistoryContext");function Nt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}o(Nt,"num");function hm(e){if(e===void 0)return{repoRoot:pe(),scanDirs:void 0};let t=js(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}o(hm,"anchorRepo");function gm(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}.`}}o(gm,"dirNotFound");async function _m(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 s=r.findings.filter(a=>a.status==="open").length,i=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:s,warn_count:i,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${s} blocking (open) + ${i} 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,s=J(n.for_path);if(s!==void 0){let u=Yf(s);if(u===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:s,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 lt(u.repoRoot,u.repoRelPath,{minFiles:r}),m=p.namespace,h=o(y=>y===null?null:`${m?.prefix??""}${y}`,"full"),g=m===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:u.repoRoot,namespace:m===null?null:{dir:m.dir,prefix:m.prefix,file_count:m.fileCount},number:h(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:h(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${h(p.number)} is already held (see held_by). Create the file as ${h(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${h(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let i=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(i!==void 0&&i.length>0){let u=new Map,p=[];for(let x of i){let S=js(x);if(S===null){p.push(x);continue}let I=u.get(S.repoRoot)??new Set;I.add(S.repoRelDir),u.set(S.repoRoot,I)}if(u.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let m=[],h=[],g=[],y=[];for(let[x,S]of u){let I=[...S],L=I.includes(""),U=await ct(x,{dirs:L?void 0:I,minFiles:r});m.push({repo_root:x,dirs:L?null:I}),h.push(...U.findings),g.push(...U.facts.namespaces.map(F=>({repo_root:x,dir:F.dir,prefix:F.prefix,file_count:F.fileCount}))),y.push(...U.facts.skipped)}let _=h.filter(x=>x.status==="open"),w=h.filter(x=>x.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:w.length,findings:_,preexisting:w.map(x=>`${x.namespace.prefix}${x.number}`),namespaces:g,skipped:y,scanned:m,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?g.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.":`${_.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+k}}let a=pe(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(u=>u.status==="open"),d=c.findings.filter(u=>u.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:d.length,findings:l,preexisting:d.map(u=>`${u.namespace.prefix}${u.number}`),namespaces:c.facts.namespaces.map(u=>({dir:u.dir,prefix:u.prefix,file_count:u.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:J(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),s=o(p=>r.findings.filter(m=>m.status===p),"of"),i=s("open"),a=s("warn"),c=s("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let d="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",u=i.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:i.length,warn_count:a.length,preexisting_count:c.length,findings:[...i,...a],preexisting:c.map(p=>p.id),coverage_note:d,hint:(r.ok?"The declared entries agree.":u.length>0?`${u.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${i.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${i.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+d}}case"check_theme_class_drift":{let r=J(n.dir),s,i;if(r!==void 0){let u=js(r);if(u===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."};s=u.repoRoot,i=u.repoRelDir===""?void 0:[u.repoRelDir]}else s=pe(),i=void 0;let a=At(s,{dirs:i,baseRef:J(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:s,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(u=>u.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:s,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(u=>({file:u.file,class:u.klass,status:u.status,missing_token:u.token,namespace:u.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=hm(J(n.dir));if(r===null)return gm("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let s=Rt(r.repoRoot,{dirs:r.scanDirs,baseRef:J(n.base_ref),includeBaseline:n.include_baseline!==!1}),i="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(s.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=s.findings.filter(l=>l.status==="open"),c=s.findings.filter(l=>l.status==="info");return{ok:s.ok,verdict:s.verdict,repo_root:r.repoRoot,base_ref:s.facts.baseRef,projects:s.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:s.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.`)+" "+i}}case"check_migration_ledger_drift":{let r=hm(J(n.dir));if(r===null)return gm("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let s=wa(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:J(n.remote_db_url)}),i=s.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(s.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:s.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=o(p=>s.findings.filter(m=>m.status===p),"of"),c=a("open"),l=a("warn"),d=a("info"),u=i.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:s.ok,verdict:s.verdict,repo_root:r.repoRoot,projects:i,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:s.facts.remoteConsulted,skipped:s.facts.skipped,database_targets:u,hint:(s.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:s.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=J(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:J(n.kind),limit:Nt(n.limit)})).map(i=>({...i,nodeKeyHash:Ws(i.nodeKey)}))}case"codebase_trace":{let r=J(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let s=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:s,maxDepth:Nt(n.max_depth),limit:Nt(n.limit)})}case"codebase_snippet":{let r=J(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let s=await e.getCodeSnippet(r);if(!s)throw new Error(`no symbol found for node_key: ${r}`);return{...s,nodeKeyHash:Ws(r)}}case"codebase_map":return e.getArchitecture({topN:Nt(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:J(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Nt(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(s=>({name:s.name,qualified_name:s.qualifiedName,kind:s.kind,language:s.language,file:s.filePath,start_line:s.startLine,node_key:s.nodeKey,node_key_hash:Ws(s.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(s=>({name:s.name,qualified_name:s.qualifiedName,kind:s.kind,language:s.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:J(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Nt(n.limit)}),s;if(n.include_history!==!1)try{s=gx(await e.fileHistory({since:J(n.since),limit:1}))}catch{s=void 0}let i;try{i=await e.reviewDetectors({baseRef:J(n.since)})}catch(l){i=mn(lr(`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:mm,detector_coverage:i.coverage},c=i.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,d)=>l+d.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:Ws(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,...s?{history:s}:{}},verdict_args:{detector_findings:i.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:i.coverage,truncated:i.truncated,block_eligible:c,engines:i.engines,findings:i.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 ${i.findings.length} detector row(s) (${c} block-eligible, coverage ${i.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(i=>typeof i=="string"):void 0,s=await e.fileHistory({paths:r,since:J(n.since),limit:Nt(n.limit),includeOwnership:n.include_ownership!==!1});return{history:s.history.map(i=>({path:i.path,last_commits:i.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:i.ownership?{top_authors:i.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:i.ownership.commitsInWindow}:null})),regression:s.regression?{since_input:s.regression.sinceInput,since_resolved:s.regression.sinceResolved,truncated:s.regression.truncated,commits:s.regression.commits.map(i=>({sha:i.sha,date_iso:i.dateIso,author_name:i.authorName,subject:i.subject,files_touched:i.filesTouched}))}:null,ownership_window_commits:s.ownershipWindowCommits,paths_truncated:s.pathsTruncated,hint:s.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}`)}}o(_m,"dispatchLocalTool");var Bs=class{constructor(t=Xf,n=null,r=pe){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{o(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return va}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&ym.has(r)}async handleToolCall(t,n){let r=n??{},s=typeof r.name=="string"?r.name:"",i=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=await _m(this.getEngine(),s,i),c=JSON.stringify(a,null,2);return this.recordSavings(s,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=zf(a)?`${qf} (${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(i=>i&&typeof i=="object"?i.name:void 0).filter(i=>typeof i=="string")),s=this.descriptors().filter(i=>!r.has(i.name));return n.result.tools=[...n.result.tools,...s],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 s=rm(t,n,r,this.repoRootCache);this.aggregator.add(s)}catch{}}};Kt();var yx="/mcp-client-metrics-ingest",_x=4e3,bx="codebase_search_tokens_saved";async function bm(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${jn()}${yx}`,n=new AbortController,r=setTimeout(()=>n.abort(),_x);try{let s=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:bx,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await s.text().catch(()=>""),s.ok}catch(s){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${s instanceof Error?s.message:String(s)}
|
|
842
|
-
`),!1}finally{clearTimeout(r)}}o(
|
|
843
|
-
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,
|
|
844
|
-
`),process.exit(1)),n.apiKey}o(
|
|
845
|
-
`),process.exit(1)),e.apiKey}o(
|
|
846
|
-
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(
|
|
847
|
-
`),process.exit(0));let t=te(),n=await
|
|
848
|
-
`),n=await
|
|
849
|
-
`))}o(
|
|
849
|
+
`),g}o(Lm,"runInstall");wr();import{readFileSync as rE}from"node:fs";import{join as Fm}from"node:path";function Xs(e){return e?Math.ceil(e.length/4):0}o(Xs,"estimateTokens");var jm=1e6,Zs=class{static{o(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 Um(e){try{let t=rE(e,"utf8");return t.length>jm?t.slice(0,jm):t}catch{return""}}o(Um,"readFileCapped");function sE(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]}o(sE,"distinctFilePaths");function Hm(e,t,n,r){try{let s=Xs(n);if(e==="codebase_search"){let i=sE(t);if(i.length===0)return 0;let a=0;for(let c of i)a+=Xs(Um(Fm(r,c)));return Math.max(0,a-s)}if(e==="codebase_snippet"){let i=t?.filePath;if(typeof i!="string"||i.length===0)return 0;let a=Xs(Um(Fm(r,i)));return Math.max(0,a-s)}return 0}catch{return 0}}o(Hm,"measureLocalToolSaved");hn();wr();import{createHash as iE}from"node:crypto";function Qs(e){return iE("sha256").update(e,"utf8").digest("hex")}o(Qs,"nodeKeyHash");var oE=["module","class","interface","function","method","type_alias","enum","variable"],$a=[{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:oE,description:"Restrict to a symbol kind."},limit:{type:"number",description:"Max results (default 20)."}},required:["query"]}},{name:"codebase_trace",description:"Traverse the call/dependency graph from a symbol. direction 'out' = what this symbol calls/contains/imports; 'in' = what calls/depends on it. Returns edges as node_key \u2192 node_key with the edge kind. CALLS/EXTENDS are best-effort name heuristics.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"Start symbol's node_key (from codebase_search)."},direction:{type:"string",enum:["out","in"],description:"Traversal direction (default out)."},max_depth:{type:"number",description:"BFS depth 1\u20135 (default 3)."},limit:{type:"number",description:"Max edges returned (default 100)."}},required:["node_key"]}},{name:"codebase_snippet",description:"Return the exact source text of a symbol by node_key (read locally from disk \u2014 never uploaded). Use after codebase_search/trace to read a function/class without opening the file.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"The symbol's node_key."}},required:["node_key"]}},{name:"codebase_map",description:"Architecture overview of the indexed repo: symbol-kind distribution, languages, and the most-imported (highest fan-in) modules \u2014 a cheap way to orient in an unfamiliar codebase.",inputSchema:{type:"object",properties:{top_n:{type:"number",description:"How many top modules to list (default 10)."}}}},{name:"codebase_changes",description:"Enumerate the symbols in files you changed (git diff/status against the LOCAL index \u2014 runs on this machine, nothing is uploaded). Call after finishing an edit batch, before committing. The output includes a ready-to-paste `briefing_args` block with paths deliberately stripped \u2014 feed it to the cloud tool codebase_change_briefing to get the maind conventions and lessons that apply to exactly these symbols. Requires a built index (codebase_index) for symbol enumeration; files without index rows are counted but contribute no symbols.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."}}}},{name:"codebase_review_changes",description:"Review-grade change enumeration (ADR-228): like codebase_changes, but hunk-aware \u2014 each symbol is graded added|modified|co_located by intersecting git diff hunks with symbol spans (runs on this machine, nothing is uploaded), plus closed-enum risk_flags from the raw path list (SQL migrations, RLS/SECURITY DEFINER, CI workflows, env files \u2014 files the index itself cannot see). The output's `review_args` block is path-free by construction \u2014 feed it to the cloud tool review_changes for provenance-backed convention findings. It ALSO runs the four repo-health detectors (number collisions, spec drift, dead theme classes, table ACL \u2014 ADR-324) and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full keeps a run attestation-grade. diff_stats carries the attest anchors (head_sha, dirty, resolved base_sha \u2014 commit object hashes, no source): pass them through to review_verdict to persist a replayable review_runs record (ADR-230). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, a COMMIT on the shared base tree \u2014 one that a branch switch undone by a parallel session redirected there, which no success message reports and which `git push` would make worse, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],Bm=new Set($a.map(e=>e.name));function J(e){return typeof e=="string"&&e.length>0?e:void 0}o(J,"str");var aE=10;function cE(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,s=0,i=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=aE&&r++,c>s&&(s=c);for(let d of a.ownership?.topAuthors??[])n.add(d.email.toLowerCase()||d.name);let l=a.lastCommits[0]?.dateIso;if(l){let d=Date.parse(l);Number.isFinite(d)&&d>i&&(i=d)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:s,distinct_authors:n.size,newest_change_age_days:i>0?Math.max(0,Math.floor((t-i)/864e5)):0}}o(cE,"aggregateHistoryContext");function Pt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}o(Pt,"num");function Gm(e){if(e===void 0)return{repoRoot:fe(),scanDirs:void 0};let t=Js(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}o(Gm,"anchorRepo");function Wm(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}.`}}o(Wm,"dirNotFound");async function Km(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 s=r.findings.filter(a=>a.status==="open").length,i=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:s,warn_count:i,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${s} blocking (open) + ${i} 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,s=J(n.for_path);if(s!==void 0){let u=Dm(s);if(u===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:s,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 at(u.repoRoot,u.repoRelPath,{minFiles:r}),m=p.namespace,h=o(y=>y===null?null:`${m?.prefix??""}${y}`,"full"),g=m===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:u.repoRoot,namespace:m===null?null:{dir:m.dir,prefix:m.prefix,file_count:m.fileCount},number:h(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:h(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${h(p.number)} is already held (see held_by). Create the file as ${h(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${h(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let i=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(i!==void 0&&i.length>0){let u=new Map,p=[];for(let x of i){let S=Js(x);if(S===null){p.push(x);continue}let I=u.get(S.repoRoot)??new Set;I.add(S.repoRelDir),u.set(S.repoRoot,I)}if(u.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let m=[],h=[],g=[],y=[];for(let[x,S]of u){let I=[...S],$=I.includes(""),U=await ot(x,{dirs:$?void 0:I,minFiles:r});m.push({repo_root:x,dirs:$?null:I}),h.push(...U.findings),g.push(...U.facts.namespaces.map(j=>({repo_root:x,dir:j.dir,prefix:j.prefix,file_count:j.fileCount}))),y.push(...U.facts.skipped)}let _=h.filter(x=>x.status==="open"),w=h.filter(x=>x.status==="info"),k=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:_.length===0,open_count:_.length,preexisting_count:w.length,findings:_,preexisting:w.map(x=>`${x.namespace.prefix}${x.number}`),namespaces:g,skipped:y,scanned:m,...p.length>0?{unresolved_dirs:p}:{},hint:(_.length===0?g.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.":`${_.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+k}}let a=fe(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(u=>u.status==="open"),d=c.findings.filter(u=>u.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:d.length,findings:l,preexisting:d.map(u=>`${u.namespace.prefix}${u.number}`),namespaces:c.facts.namespaces.map(u=>({dir:u.dir,prefix:u.prefix,file_count:u.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:J(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),s=o(p=>r.findings.filter(m=>m.status===p),"of"),i=s("open"),a=s("warn"),c=s("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let d="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",u=i.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:i.length,warn_count:a.length,preexisting_count:c.length,findings:[...i,...a],preexisting:c.map(p=>p.id),coverage_note:d,hint:(r.ok?"The declared entries agree.":u.length>0?`${u.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${i.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${i.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+d}}case"check_theme_class_drift":{let r=J(n.dir),s,i;if(r!==void 0){let u=Js(r);if(u===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."};s=u.repoRoot,i=u.repoRelDir===""?void 0:[u.repoRelDir]}else s=fe(),i=void 0;let a=At(s,{dirs:i,baseRef:J(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:s,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(u=>u.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:s,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(u=>({file:u.file,class:u.klass,status:u.status,missing_token:u.token,namespace:u.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=Gm(J(n.dir));if(r===null)return Wm("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let s=Et(r.repoRoot,{dirs:r.scanDirs,baseRef:J(n.base_ref),includeBaseline:n.include_baseline!==!1}),i="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(s.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=s.findings.filter(l=>l.status==="open"),c=s.findings.filter(l=>l.status==="info");return{ok:s.ok,verdict:s.verdict,repo_root:r.repoRoot,base_ref:s.facts.baseRef,projects:s.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:s.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.`)+" "+i}}case"check_migration_ledger_drift":{let r=Gm(J(n.dir));if(r===null)return Wm("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let s=ca(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:J(n.remote_db_url)}),i=s.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(s.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:s.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=o(p=>s.findings.filter(m=>m.status===p),"of"),c=a("open"),l=a("warn"),d=a("info"),u=i.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:s.ok,verdict:s.verdict,repo_root:r.repoRoot,projects:i,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:s.facts.remoteConsulted,skipped:s.facts.skipped,database_targets:u,hint:(s.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:s.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=J(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:J(n.kind),limit:Pt(n.limit)})).map(i=>({...i,nodeKeyHash:Qs(i.nodeKey)}))}case"codebase_trace":{let r=J(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let s=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:s,maxDepth:Pt(n.max_depth),limit:Pt(n.limit)})}case"codebase_snippet":{let r=J(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let s=await e.getCodeSnippet(r);if(!s)throw new Error(`no symbol found for node_key: ${r}`);return{...s,nodeKeyHash:Qs(r)}}case"codebase_map":return e.getArchitecture({topN:Pt(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:J(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Pt(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(s=>({name:s.name,qualified_name:s.qualifiedName,kind:s.kind,language:s.language,file:s.filePath,start_line:s.startLine,node_key:s.nodeKey,node_key_hash:Qs(s.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(s=>({name:s.name,qualified_name:s.qualifiedName,kind:s.kind,language:s.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:J(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Pt(n.limit)}),s;if(n.include_history!==!1)try{s=cE(await e.fileHistory({since:J(n.since),limit:1}))}catch{s=void 0}let i;try{i=await e.reviewDetectors({baseRef:J(n.since)})}catch(l){i=un(cr(`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:df,detector_coverage:i.coverage},c=i.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,d)=>l+d.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:Qs(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,...s?{history:s}:{}},verdict_args:{detector_findings:i.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:i.coverage,truncated:i.truncated,block_eligible:c,engines:i.engines,findings:i.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 ${i.findings.length} detector row(s) (${c} block-eligible, coverage ${i.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(i=>typeof i=="string"):void 0,s=await e.fileHistory({paths:r,since:J(n.since),limit:Pt(n.limit),includeOwnership:n.include_ownership!==!1});return{history:s.history.map(i=>({path:i.path,last_commits:i.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:i.ownership?{top_authors:i.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:i.ownership.commitsInWindow}:null})),regression:s.regression?{since_input:s.regression.sinceInput,since_resolved:s.regression.sinceResolved,truncated:s.regression.truncated,commits:s.regression.commits.map(i=>({sha:i.sha,date_iso:i.dateIso,author_name:i.authorName,subject:i.subject,files_touched:i.filesTouched}))}:null,ownership_window_commits:s.ownershipWindowCommits,paths_truncated:s.pathsTruncated,hint:s.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}`)}}o(Km,"dispatchLocalTool");var ei=class{constructor(t=Mm,n=null,r=fe){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{o(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return $a}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Bm.has(r)}async handleToolCall(t,n){let r=n??{},s=typeof r.name=="string"?r.name:"",i=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=await Km(this.getEngine(),s,i),c=JSON.stringify(a,null,2);return this.recordSavings(s,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=Nm(a)?`${Om} (${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(i=>i&&typeof i=="object"?i.name:void 0).filter(i=>typeof i=="string")),s=this.descriptors().filter(i=>!r.has(i.name));return n.result.tools=[...n.result.tools,...s],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 s=Hm(t,n,r,this.repoRootCache);this.aggregator.add(s)}catch{}}};_n();var lE="/mcp-client-metrics-ingest",dE=4e3,uE="codebase_search_tokens_saved";async function Vm(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${mr()}${lE}`,n=new AbortController,r=setTimeout(()=>n.abort(),dE);try{let s=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:uE,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await s.text().catch(()=>""),s.ok}catch(s){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${s instanceof Error?s.message:String(s)}
|
|
850
|
+
`),!1}finally{clearTimeout(r)}}o(Vm,"postSavingsMetric");ja();ni();si();Pn();import{join as z0}from"node:path";var q0="<synthetic>";function Lh(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:z0(cc,lc(e.cwd),`${e.transcript_stem}.jsonl`)}o(Lh,"transcriptPathFromSideChannel");var pi=class{constructor(t){this.deps=t}static{o(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 s=await(this.deps.stream??ac)(n,{start:this.offset});for(let i of s.events)if(i.kind==="title"){let a=i.title.trim();a.length>0&&(this.title=a)}else i.kind==="assistant"&&!i.isSidechain&&typeof i.model=="string"&&i.model.length>0&&i.model!==q0&&(this.model=i.model);s.bytesRead>this.offset&&(this.offset=s.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 Y0}from"node:child_process";var J0=8,X0=32;function Z0(e){return e.split(`
|
|
851
|
+
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,X0)}o(Z0,"parsePorcelain");function Q0(e,t=J0){let n=[];for(let r of e){let s=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(s.length===0)continue;let i=s.includes("/")?s.slice(0,s.lastIndexOf("/")):s;if(!(i.length===0||n.includes(i))&&(n.push(i),n.length>=t))break}return n}o(Q0,"condenseToDirs");async function Fh(e=eA){let t=await e();if(t===null)return null;let n=Q0(Z0(t));return n.length>0?n:null}o(Fh,"deriveWorkingPaths");async function eA(){return await new Promise(e=>{Y0("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}o(eA,"defaultGitStatus");var oI=1,aI=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function cI(e){return aI.includes(e)}o(cI,"isHookSubcommand");var lI=6e4;async function dI(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==B()&&Ct(e),e;let t=B();if(t!==null)return t;let n=await bn(H);return n===null&&(process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
|
|
852
|
+
`),process.exit(1)),n.apiKey}o(dI,"ensureApiKey");async function uI(){let e=await bn(H);return e===null&&(process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
|
|
853
|
+
`),process.exit(1)),e.apiKey}o(uI,"reauth");async function pI(){let e=process.argv.slice(2).find(_=>!_.startsWith("-"));if(e==="install"){let _=process.argv.indexOf("install"),w=process.argv.slice(_+1),k=await Lm(w);process.exit(k)}if(e==="doctor"){let{runDoctor:_}=await Promise.resolve().then(()=>(qh(),zh));process.exit(await _(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:_}=await Promise.resolve().then(()=>(Hg(),Ug));process.exit(await _())}if(e==="guard"){let _=process.argv.indexOf("guard"),{runGuard:w}=await Promise.resolve().then(()=>(Jg(),Yg));process.exit(await w(process.argv.slice(_+1)))}if(e==="guard-inject"){let{runGuardInject:_}=await Promise.resolve().then(()=>(ny(),ty));process.exit(await _())}if(e==="guard-gate"){let{runGuardGate:_}=await Promise.resolve().then(()=>(ay(),oy));process.exit(await _())}if(e==="guard-stop"){let{runGuardStop:_}=await Promise.resolve().then(()=>(dy(),ly));process.exit(await _())}if(e==="gateway"){let _=process.argv.indexOf("gateway"),{runGateway:w}=await Promise.resolve().then(()=>(qy(),zy));process.exit(await w(process.argv.slice(_+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:_}=await Promise.resolve().then(()=>(Fc(),Lc));process.exit(await _())}if(e==="guard-cross-check"){let{runGuardCrossCheck:_}=await Promise.resolve().then(()=>(Fc(),Lc));process.exit(await _())}if(e==="on-index-refresh"){let{runOnIndexRefresh:_}=await Promise.resolve().then(()=>(Hc(),Uc));process.exit(await _())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:_}=await Promise.resolve().then(()=>(Hc(),Uc));process.exit(await _())}if(e!==void 0&&cI(e)){let _=await Promise.resolve().then(()=>(kc(),Rg)),w={"on-session-start":_.runOnSessionStart,"on-tool-use":_.runOnToolUse,"on-file-write":_.runOnFileWrite,"on-file-edit":_.runOnFileEdit,"on-repo-health":_.runOnRepoHealth,"on-write-health":_.runOnWriteHealth,"sync-config":_.runSyncConfig,flush:_.runFlush,status:_.runHookStatus}[e];process.exit(await w())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(H+`
|
|
854
|
+
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(fI(),process.exit(0)),process.argv.includes("--reauth")&&(fr(),await bn(H,process.stdout)===null&&process.exit(1),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
|
|
855
|
+
`),process.exit(0));let t=te(),n=await dI(),r=z(),i=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Zs:null,a=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new ei(void 0,i),c=`bridge-${iI()}`,l=o(async()=>{if(!i)return;let _=i.takePending();_.tokens<=0||await Vm({apiKey:n,deviceId:t,sessionId:c,tokensSaved:_.tokens,bridgeVersion:H})},"flushSavings"),d=i?setInterval(()=>{l()},lI):null;d?.unref();let u=null,p=new ri({projectKey:r}),m=new pi({resolvePath:o(()=>Lh(p.sideChannel()),"resolvePath"),fallbackModel:o(()=>p.sideChannel()?.model??null,"fallbackModel")}),h=new ti({projectKey:r,identity:p,sessionMeta:o(()=>m.read(),"sessionMeta"),postToolCall:o((_,w)=>u===null?Promise.reject(new Error("presence: no active forwarder")):u.postPresenceToolCall(_,w),"postToolCall"),deriveWorkingPaths:o(()=>Fh(),"deriveWorkingPaths"),snapshot:r!==null?rh({projectKey:r}):void 0}),g=h.isEnabled?setInterval(()=>{h.pollActivity()},Ym):null;if(g?.unref(),h.isEnabled){let _=o(w=>{h.end().finally(()=>process.exit(w))},"endAndExit");process.on("SIGTERM",()=>_(143)),process.on("SIGINT",()=>_(130))}let y=0;try{for(;;){let _=new Rs({apiKey:n,deviceId:t,bridgeVersion:H,projectKey:r,localRouter:a,presence:h});u=_;try{await _.run();return}catch(w){if(w instanceof pr&&y<oI){y+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${w.message}; re-authorizing\u2026
|
|
856
|
+
`),n=await uI();continue}throw w}}}finally{d&&clearInterval(d),g&&clearInterval(g),await h.end(),await l()}}o(pI,"main");function fI(){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 doctor # offline self-diagnosis with fix commands (--json)"," 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(`
|
|
857
|
+
`))}o(fI,"printHelp");pI().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
|
|
850
858
|
`),process.exit(1)});
|