@maind-dev/mcp-bridge 0.72.1 → 0.74.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 +204 -193
- package/build/meta.json +1 -1
- package/package.json +2 -2
package/build/index.js
CHANGED
|
@@ -1,41 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
`,{encoding:"utf8",mode:384});try{jc(n,384)}catch{}}function K(){let e=Ei();if(!Lr(e))return null;let t=Fc(e,"utf8").trim();return t.length>0?t:null}function jn(){let e=Ei();Lr(e)&&xi(e,"",{encoding:"utf8",mode:384})}function Hc(){try{return`mcp-bridge-${s_()}`}catch{return"mcp-bridge"}}function $r(e){return{os:`${Si()} ${i_()}`,ide:"mcp-bridge",ext_version:e,device_id:te()}}var a_,c_,l_,ae=b(()=>{"use strict";o(Fn,"configDir");o(Uc,"ensureDir");a_="device-id",c_="api-key";o(te,"ensureDeviceId");l_=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;o(d_,"isUuid");o(Ei,"apiKeyPath");o(rt,"writeApiKey");o(K,"readApiKey");o(jn,"clearApiKey");o(Hc,"bridgeLabel");o($r,"clientMeta")});function Un(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:u_}function Bt(e){return`${Un()}/${e.replace(/^\/+/,"")}`}var u_,Kt=b(()=>{"use strict";u_="https://fn.maind.dev/functions/v1";o(Un,"functionsOrigin");o(Bt,"functionsUrl")});var W,st=b(()=>{"use strict";W="0.72.1"});import{execFileSync as __}from"node:child_process";import{createHash as b_}from"node:crypto";function w_(e){return b_("sha256").update(e).digest("hex")}function v_(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 Ti(e){let t=v_(e);return t?w_(t):null}function V(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&k_.test(e))return e;let t;try{t=__("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Ti(t):null}var k_,We=b(()=>{"use strict";o(w_,"sha256Hex");o(v_,"normalizeRemoteUrl");o(Ti,"projectKeyFromRemote");k_=/^[a-f0-9]{64}$/;o(V,"computeProjectKey")});import x_ from"node:path";import{fileURLToPath as E_}from"node:url";function T_(e,t=x_.sep){return e.split(t).includes("_npx")}function be(e){let t=e.extraArgs??[],n=o(r=>({command:"npx",args:["-y",Zc,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):T_(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=E_(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}=${Xc(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Xc(n)).join(" ")}function jr(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Zc)}function Ur(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Xc(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Zc,qt=b(()=>{"use strict";Zc="@maind-dev/mcp-bridge";o(T_,"isEphemeralEntry");o(be,"resolveBridgeLaunch");o(we,"currentBridgeEntry");o(zt,"launchToShellCommand");o(jr,"isNpxForm");o(Ur,"isLegacyHookForm");o(Xc,"shellQuote")});import*as z from"node:fs/promises";import*as Hr from"node:path";async function ne(e){try{return await z.readFile(e,"utf8")}catch(t){if(A_(t))return null;throw t}}async function Ri(e){await z.mkdir(e,{recursive:!0})}async function q(e,t,n){let r=Hr.dirname(e);await Ri(r);let s=Hr.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(I_(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 sl(e,t){let n=await ne(e);return n===null?!1:n.split(/\r?\n/).some(s=>s.startsWith(t))}function A_(e){return il(e)&&e.code==="ENOENT"}function I_(e){return!il(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function il(e){return typeof e=="object"&&e!==null&&"code"in e}var Ne=b(()=>{"use strict";o(ne,"readFileSafe");o(Ri,"ensureDir");o(q,"atomicWriteFile");o(sl,"hasLinePrefix");o(A_,"isNoEnt");o(I_,"isWindowsRenameFailure");o(il,"isNodeError")});import{existsSync as V_}from"node:fs";import*as ul from"node:path";function Bn(e,t={},n=Ni){let r=t.fileExists??V_,s=t.expectedCommand??z_,i={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Ci(a)&&(i=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=q_(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(Ur(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(jr(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=Y_(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 Oi(e){return e.some(t=>t.status!=="ok")}function Br(e){return e.some(t=>t.remedy==="run-install")}function z_(e){return zt(be({entryPath:we(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function q_(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let s of r){if(!Ci(s))continue;let i=s.hooks;if(Array.isArray(i))for(let a of i){if(!Ci(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function Y_(e){for(let t of J_(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return ul.isAbsolute(t)?t:null;return null}function J_(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 Ci(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ni,Wr,Kn=b(()=>{"use strict";qt();Ni=[{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."}],Wr=[{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(Bn,"inspectHookWiring");o(Oi,"hasWiringDrift");o(Br,"needsInstallRun");o(z_,"defaultExpectedCommand");o(q_,"findCommand");o(Y_,"extractScriptPath");o(J_,"tokenize");o(Ci,"isObject")});import*as Mi from"node:path";import*as fl from"node:readline";async function ml(e,t){let n=Mi.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: ${Di(m)}`}}let i,a="create";if(s===null||s.trim().length===0)i={};else{a="merge";try{let m=JSON.parse(s);if(!Pi(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: ${Di(m)}`}}}let c=Z_(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 Q_(e.out,`
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
`)
|
|
13
|
-
`)
|
|
14
|
-
`)){if(
|
|
15
|
-
`)){if(l.
|
|
16
|
-
`)){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 Hb(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(`
|
|
17
|
-
`))
|
|
18
|
-
`),_=od(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,os),truncated:h.length>os}}return{history:l,regression:d,ownershipWindowCommits:i,pathsTruncated:a.length>zi}}var Gb,Wb,ad,zi,os,sd,qi=b(()=>{"use strict";re();Gb="",Wb="\0",ad=200,zi=50,os=100,sd="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";o(Bb,"clamp");o(id,"splitRecords");o(od,"parseHistoryRecord");o(Kb,"aggregateOwnership");o(cd,"readFileHistory")});import{execFileSync as Vb}from"node:child_process";import{readdirSync as zb,statSync as ld}from"node:fs";import{isAbsolute as qb,join as Yi,relative as Yb,resolve as Jb}from"node:path";function Zb(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function Qb(e,t){try{let n=Vb("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 ew(e){let t;try{t=zb(e)}catch{return null}for(let n of t.filter(Zb))try{let r=ld(Yi(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function tw(e){try{return ld(e).isDirectory()}catch{return!1}}function nw(e,t){let n=Yb(e,t);return!n||n.startsWith("..")?t:n}function Ji(e){let t=Xb.filter(c=>tw(Yi(e,c))),n=Qb(e,"core.hooksPath"),r=n?qb(n)?n:Jb(e,n):Yi(e,".git","hooks"),s=nw(e,r),i=ew(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 Xi(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 Xb,Zi=b(()=>{"use strict";Xb=[".githooks",".husky"];o(Zb,"isRealHook");o(Qb,"gitConfig");o(ew,"hasExecutableHook");o(tw,"isDir");o(nw,"displayPath");o(Ji,"resolveHookState");o(Xi,"describeHookState")});import{posix as dd}from"node:path";function Zt(e){let t=rw.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=dd.basename(i),c=Zt(a);if(c===null)continue;let l=dd.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 ud(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 rw,qn=b(()=>{"use strict";re();rw=/^(\d+)_.+\.sql$/;o(Zt,"parseMigrationVersion");o(Pe,"compareVersions");o(at,"discoverSupabaseProjects");o(ud,"resolveDefaultBranch")});import{execFileSync as sw}from"node:child_process";import{existsSync as Z,readFileSync as ze,readdirSync as as,statSync as eo}from"node:fs";import{posix as P}from"node:path";function cw(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&&no(n,i))){let c=lw(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=P.dirname(r)}return null}function lw(e,t){let n=[];for(let r of ow){let s;try{s=as(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=eo(c),u=eo(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>aw)continue;ze(c).equals(ze(l))||n.push(a)}catch{continue}}}return n.sort()}function _d(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 ${ro}.`})}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=dw(e.hooks);return a&&t.push(a),uw(t)}function dw(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:Xi(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 uw(e){return[...e].sort((t,n)=>pd[t.status]-pd[n.status]||t.id.localeCompare(n.id))}function bd(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function Me(e){let t=e?.trim();return t||null}function pw(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 fw(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 mw(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
|
-
`)
|
|
20
|
-
`).map(
|
|
21
|
-
`).
|
|
22
|
-
`).
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
`,
|
|
26
|
-
`:s==="r"?"\r":s==="t"?" ":s)}function Dw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wo(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${Dw(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(Qn(a)){s=us(e,s);continue}if(fs(e,s)){s=ps(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 ls(e,s);if(a===";")return null;s++}return null}function vo(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();Qn(i[0]??"")&&(t[s]=Pd(i))}return t}function Pw(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 Md(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Ld(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function $d(e,t){let n=wo(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Ld(),s=[],i=0;for(let a of nn(n.slice(1,-1))){if(!a.startsWith("{")){i++;continue}let c=vo(a),l=c[t.key_field];if(!l){i++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");s.push({key:l,fields:Md(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 Fd(e,t){let n=wo(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=Ld(),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=vo(m);for(let[_,w]of Object.entries(u.fields??{}))h[_]=y[String(w)]??"";if(!p&&typeof u.children=="string"){let _=Pw(m,u.children);g=_&&_.startsWith("[")?ls(_,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&&Qn(k[0]??"")?Pd(k):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?ls(_,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:Md(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 Nd(e,t){return t.extractor==="object-array"?$d(e,t):Fd(e,t)}function jd(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 Ud(e,t,n){return`spec.drift:${e}#${t}:${n}`}function Mw(e){return e.orderPath.join(" / ")||"(flat)"}function Hd(e,t,n,r){let s=[],i=o((d,u,p,m,h,g)=>{s.push({id:Ud(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 ${Mw(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
|
-
|
|
28
|
-
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>Dd[u.status]-Dd[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 bo(e){let t=e?.trim();return t||null}function ms(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 $w(e){let t=bo(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 Fw(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 Wd(e,t={}){let n=o((g,y)=>Nw.join(g,y),"join"),r=t.manifestPath??ds,s=[],i={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:s};if(bo(R(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...i,manifestError:"not a git work tree"};let a=n(e,r);if(!Cw(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}=ms(Cd(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 Fw(c))try{d.set(g,Cd(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:$w(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=bo(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 Wd(e,t);return{...Gd(n,t),facts:n}}function ko(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var ds,Dd,er=b(()=>{"use strict";re();ds=".maind/spec-contracts.json";o(us,"endOfString");o(ps,"skipComment");o(Qn,"isQuote");o(fs,"isCommentStart");o(ls,"sliceBalanced");o(Ow,"stripLeadingTrivia");o(nn,"splitTopLevel");o(Pd,"readStringLiteral");o(Dw,"escapeRe");o(wo,"findSymbolArray");o(vo,"parseObjectFields");o(Pw,"objectFieldRaw");o(Md,"pickFields");o(Ld,"makeOrdinals");o($d,"extractObjectArray");o(Fd,"extractNestedList");o(Nd,"extractRecords");o(jd,"isGrounded");o(Ud,"findingId");o(Mw,"partitionOf");o(Hd,"compareContract");o(Lw,"checkAssertions");o(Od,"unreadable");Dd={open:0,warn:1,info:2,passed:3};o(Gd,"computeSpecDrift");o(bo,"trimOrNull");o(ms,"parseManifest");o($w,"resolveDefaultBranch");o(Fw,"declaredPaths");o(Wd,"gatherSpecDriftFacts");o(dt,"checkSpecDrift");o(ko,"isSpecDriftGraded")});var M,So,T,Se,tr=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})})(So||(So={}));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,jw,se,hs=b(()=>{tr();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"]),jw=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 Uw,Le,xo=b(()=>{hs();tr();Uw=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=Uw});function Hw(e){Bd=e}function rn(){return Bd}var Bd,gs=b(()=>{xo();Bd=Le;o(Hw,"setErrorMap");o(rn,"getErrorMap")});function E(e,t){let n=rn(),r=nr({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 nr,Gw,Y,C,ut,Q,ys,_s,qe,sn,Eo=b(()=>{gs();xo();nr=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"),Gw=[];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"),ys=o(e=>e.status==="aborted","isAborted"),_s=o(e=>e.status==="dirty","isDirty"),qe=o(e=>e.status==="valid","isValid"),sn=o(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var Kd=b(()=>{});var A,Vd=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 Jd(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 iv(e){return new RegExp(`^${Jd(e)}$`)}function Xd(e){let t=`${Yd}T${Jd(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 ov(e,t){return!!((t==="v4"||!t)&&Zw.test(e)||(t==="v6"||!t)&&ev.test(e))}function av(e,t){if(!qw.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 cv(e,t){return!!((t==="v4"||!t)&&Qw.test(e)||(t==="v6"||!t)&&tv.test(e))}function lv(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 Ro(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=Ro(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=Ro(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 Zd(e,t){return new kt({values:e,typeName:N.ZodEnum,...O(t)})}function qd(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Qd(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=qd(t,r),l=c.fatal??n??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=qd(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}}):Je.create()}var de,zd,D,Ww,Bw,Kw,Vw,zw,qw,Yw,Jw,Xw,To,Zw,Qw,ev,tv,nv,rv,Yd,sv,Ye,pt,ft,mt,ht,an,gt,yt,Je,Fe,he,cn,je,ie,_t,$e,bs,bt,xe,ws,ln,dn,vs,wt,vt,kt,St,Xe,ue,le,Ee,xt,Et,un,dv,rr,sr,Tt,uv,N,pv,eu,tu,fv,mv,nu,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,zv,qv,ru=b(()=>{hs();gs();Vd();Eo();tr();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}},zd=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 zd(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 zd(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 rr({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 sr.create(this,t)}readonly(){return Tt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ww=/^c[^\s-]{8,}$/i,Bw=/^[0-9a-z]+$/,Kw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Vw=/^[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,zw=/^[a-z0-9_-]{21}$/i,qw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yw=/^[-+]?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)?)??$/,Jw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zw=/^(?:(?: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])$/,Qw=/^(?:(?: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])$/,ev=/^(([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]))$/,tv=/^(([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])$/,nv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Yd="((\\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])))",sv=new RegExp(`^${Yd}$`);o(Jd,"timeRegexSource");o(iv,"timeRegex");o(Xd,"datetimeRegex");o(ov,"isValidIP");o(av,"isValidJWT");o(cv,"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")Jw.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")To||(To=new RegExp(Xw,"u")),To.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")Vw.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")zw.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")Ww.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")Bw.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")Kw.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"?Xd(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"?sv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:v.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?iv(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"?Yw.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"duration",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?ov(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"?av(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"?cv(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"?nv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"base64",code:v.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?rv.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(lv,"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"?lv(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 Zd(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 rr||e instanceof Tt?$e(e.unwrap()):e instanceof Et?$e(e._def.innerType):[],"getDiscriminator"),bs=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(Ro,"mergeValues");bt=class extends D{static{o(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=o((i,a)=>{if(ys(i)||ys(a))return C;let c=Ro(i.value,a.value);return c.valid?((_s(i)||_s(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)})};ws=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)});vs=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 nr({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 nr({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(Zd,"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=Zd;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)});dv=Symbol("zod_brand"),rr=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}},sr=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(qd,"cleanParams");o(Qd,"custom");uv={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={}));pv=o((e,t={message:`Input not instance of ${e.name}`})=>Qd(n=>n instanceof e,t),"instanceOfType"),eu=Ye.create,tu=pt.create,fv=un.create,mv=ft.create,nu=mt.create,hv=ht.create,gv=an.create,yv=gt.create,_v=yt.create,bv=Je.create,wv=Fe.create,vv=he.create,kv=cn.create,Sv=je.create,xv=ie.create,Ev=ie.strictCreate,Tv=_t.create,Rv=bs.create,Av=bt.create,Iv=xe.create,Cv=ws.create,Nv=ln.create,Ov=dn.create,Dv=vs.create,Pv=wt.create,Mv=vt.create,Lv=kt.create,$v=St.create,Fv=Xe.create,jv=ue.create,Uv=le.create,Hv=Ee.create,Gv=ue.createWithPreprocess,Wv=sr.create,Bv=o(()=>eu().optional(),"ostring"),Kv=o(()=>tu().optional(),"onumber"),Vv=o(()=>nu().optional(),"oboolean"),zv={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")},qv=C});var f={};oe(f,{BRAND:()=>dv,DIRTY:()=>ut,EMPTY_PATH:()=>Gw,INVALID:()=>C,NEVER:()=>qv,OK:()=>Q,ParseStatus:()=>Y,Schema:()=>D,ZodAny:()=>Je,ZodArray:()=>je,ZodBigInt:()=>ft,ZodBoolean:()=>mt,ZodBranded:()=>rr,ZodCatch:()=>Et,ZodDate:()=>ht,ZodDefault:()=>xt,ZodDiscriminatedUnion:()=>bs,ZodEffects:()=>ue,ZodEnum:()=>kt,ZodError:()=>se,ZodFirstPartyTypeKind:()=>N,ZodFunction:()=>vs,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:()=>sr,ZodPromise:()=>Xe,ZodReadonly:()=>Tt,ZodRecord:()=>ws,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:()=>bv,array:()=>Sv,bigint:()=>mv,boolean:()=>nu,coerce:()=>zv,custom:()=>Qd,date:()=>hv,datetimeRegex:()=>Xd,defaultErrorMap:()=>Le,discriminatedUnion:()=>Rv,effect:()=>jv,enum:()=>Lv,function:()=>Dv,getErrorMap:()=>rn,getParsedType:()=>Se,instanceof:()=>pv,intersection:()=>Av,isAborted:()=>ys,isAsync:()=>sn,isDirty:()=>_s,isValid:()=>qe,late:()=>uv,lazy:()=>Pv,literal:()=>Mv,makeIssue:()=>nr,map:()=>Nv,nan:()=>fv,nativeEnum:()=>$v,never:()=>vv,null:()=>_v,nullable:()=>Hv,number:()=>tu,object:()=>xv,objectUtil:()=>So,oboolean:()=>Vv,onumber:()=>Kv,optional:()=>Uv,ostring:()=>Bv,pipeline:()=>Wv,preprocess:()=>Gv,promise:()=>Fv,quotelessJson:()=>jw,record:()=>Cv,set:()=>Ov,setErrorMap:()=>Hw,strictObject:()=>Ev,string:()=>eu,symbol:()=>gv,transformer:()=>jv,tuple:()=>Iv,undefined:()=>yv,union:()=>Tv,unknown:()=>wv,util:()=>M,void:()=>kv});var Ao=b(()=>{gs();Eo();Kd();tr();ru();hs()});var ee=b(()=>{Ao();Ao()});var Io,Co=b(()=>{"use strict";ee();Io=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 Yv,su=b(()=>{"use strict";ee();Co();Yv=Io.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 iu,ou,au,cu,No,lu,du,uu,Jv,pu=b(()=>{"use strict";ee();iu=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],ou=f.enum(iu),au=["new_to_ai_agents","new_to_this_client","experienced"],cu=f.enum(au),No=[{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"}],lu=No.map(e=>e.header),du=f.object({experience_level:f.array(cu).default([]),stack_filters:f.array(f.string()).default([])}).default({experience_level:[],stack_filters:[]}),uu=f.object({id:f.string().min(1),client:ou,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:du,version:f.number().int().min(1).default(1),changelog:f.string().max(500).optional()}),Jv=uu.extend({body:f.string().min(1)})});var mu,ks,hu,Ss,Xv,Zv,gu,yu,_u,bu,xs,Qv,ek,fu,tk,wu,nk,vu=b(()=>{"use strict";ee();mu=["operating_procedure","code_review","communication_style"],ks=f.enum(mu),hu=["info","recommended","required"],Ss=f.enum(hu),Xv=["optional","default_on","mandatory"],Zv=f.enum(Xv),gu=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],yu=f.enum(gu),_u=["verify","contribute","mixed"],bu=f.enum(_u),xs=f.object({clients:f.array(yu).default([]),stacks:f.array(f.string()).default([]),intents:f.array(bu).default([])}).default({clients:[],stacks:[],intents:[]}),Qv=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,ek=64,fu=200,tk=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")),wu=f.object({id:f.string().min(5).max(ek).regex(Qv,"id must match conv_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),scope:ks,version:f.number().int().min(1),changed_at:tk,changelog:f.string().max(500).optional(),applies_to:xs,severity:Ss.default("recommended"),disableability:Zv.default("default_on"),summary:f.string().min(1).max(fu,`summary must be \u2264 ${fu} 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()}),nk=wu.extend({body:f.string().min(1)})});var Ze=b(()=>{"use strict";Co();su();pu();vu()});var Oo,Es,Do,ku,Su,xu,rk,Eu=b(()=>{"use strict";ee();Oo=f.object({type:f.literal("text"),md:f.string().min(1).max(2e4)}),Es=f.number().min(0).max(1).optional(),Do=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:Es,right:Es,bottom:Es,left:Es}).optional()}),ku=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")}),Su=f.object({type:f.literal("accordion"),title:f.string().min(1).max(200),subtag:ku.optional(),blocks:f.array(f.discriminatedUnion("type",[Oo,Do])).max(50)}),xu=f.discriminatedUnion("type",[Oo,Do,Su]),rk=f.array(xu).max(100)});var Tu,sk,Ru,Au,ik,ok,ak,Iu=b(()=>{"use strict";ee();Tu=["free","solo_pro","team","enterprise"],sk=f.enum(Tu),Ru=["solo_pro","team","enterprise"],Au=f.enum(Ru),ik=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),ok=f.object({user_id:f.string().uuid(),tier:Au,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:ik.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"}),ak=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Cu=b(()=>{"use strict"});var ck,lk,dk,Nu=b(()=>{"use strict";ee();ck=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),lk=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:ck.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"}),dk=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Ou,uk,Du,Pu,Mu,Lu,pk,$u=b(()=>{"use strict";ee();Ou=f.enum(["info","important","critical"]),uk=f.enum(["pass","warn","fail"]),Du=f.object({type:f.enum(["template","lesson"]),id:f.string().min(1)}),Pu=f.object({languages:f.array(f.string()).optional(),tools:f.array(f.string()).optional()}).optional(),Mu=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")})]),Lu=f.object({id:f.string().min(1),title:f.string().min(1),severity:Ou,weight:f.number().int().positive().max(100),applies_when:Pu,check:Mu,fail_message:f.string().min(1),warn_message:f.string().optional(),remediation:Du.optional()}),pk=f.object({version:f.literal(1),checks:f.array(Lu).min(1)})});function mk(e){if(!fk.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function Ts(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 hk(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var fk,Rs,Fu,ju,Te,Uu,gk,Hu=b(()=>{"use strict";ee();fk=/^\d{4}-\d{2}-\d{2}$/;o(mk,"isRealDate");Rs=f.string().refine(mk,{message:"expected a real calendar date as YYYY-MM-DD"}),Fu=["exact","prefix"],ju=f.enum(Fu),Te=f.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Uu=f.object({model_pattern:f.string().min(1).max(100),match_kind:ju,valid_from:Rs,valid_to:Rs.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=>Ts(e)===0||Ts(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"||Ts(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=>Ts(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(Ts,"aboveRateCount");o(hk,"rowKey");gk=f.object({changelog:f.string().min(1).max(500),as_of:Rs,source_url:f.string().url().max(500),rows:f.array(Uu).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((s,i)=>{let a=hk(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 ir=b(()=>{"use strict"});var Ku=b(()=>{"use strict";ir();pn()});var Vu=b(()=>{"use strict";pn()});var zu=b(()=>{"use strict";Ze();ir();pn()});var qu=b(()=>{"use strict";ir();pn()});var Yu=b(()=>{"use strict";pn();Ku();Vu();zu();qu();ir()});var Mk,Lk,Ju,$k,Xu,Po,Zu,Qu,ep,tp,Fk,Mo=b(()=>{"use strict";ee();Ze();Mk=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,Lk=64,Ju=200,$k=1e3,Xu=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")),Po=f.enum(["low","medium","high"]),Zu=f.object({owner:f.string().min(1).max(160).optional(),risk_level:Po.optional(),reviewed_at:Xu.optional()}).default({}),Qu=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}),ep=f.object({lesson_query:Qu,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:[]}),tp=f.object({id:f.string().min(6).max(Lk).regex(Mk,"id must match skill_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),version:f.number().int().min(1),changed_at:Xu,tier:f.enum(["community","curated"]).default("curated"),summary:f.string().min(1).max(Ju,`summary must be \u2264 ${Ju} chars (rendered as one line in skill_index)`),description:f.string().max($k).optional(),applies_to:xs,membership:ep,governance:Zu}),Fk=tp.extend({body:f.string().default(""),org_id:f.string().uuid().optional(),org_name:f.string().optional()})});var np,rp,sp,ip,op,ap,jk,cp,Uk,Hk,lp=b(()=>{"use strict";ee();Mo();np=f.enum(["maind","agent-skill"]),rp=f.enum(["ready","needs_attention","blocked"]),sp=f.enum(["info","important","critical"]),ip=f.enum(["pass","warn","fail"]),op=f.enum(["structure","governance","scope","membership","package","references"]),ap=f.object({id:f.string().min(1),title:f.string().min(1),status:ip,severity:sp,category:op,field:f.string().nullable().optional(),message:f.string().min(1),hint:f.string().optional()}),jk=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({}),cp=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(),Uk=f.object({directory_name:f.string().min(1).max(120).optional(),frontmatter:cp,body:f.string().default(""),file_listing:f.array(f.string()).optional()}),Hk=f.object({format:np,subject:f.string().min(1),status:rp,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(ap),next_steps:f.array(f.string()),trust_note:f.string().min(1)})});var dp,Gk,up,pp,fp,fn,Wk,mp,hp,gp,yp,_p,Bk,Kk,bp,Vk,wp=b(()=>{"use strict";ee();Ze();dp=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],Gk=f.enum(dp),up=["verdict","advisory"],pp=f.enum(up),fp=["block","warn","note"],fn=f.enum(fp),Wk=f.object({convention_id:f.string().min(1).max(64),convention_version:f.number().int().min(1),severity:Ss,scope:ks,grade:pp,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()}),mp=["open","warn","info"],hp=f.enum(mp),gp=["introduced","pre_existing"],yp=f.enum(gp),_p=["full","partial","none"],Bk=f.enum(_p),Kk=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:hp,baseline:yp,evidence_hash:f.string().regex(/^[a-f0-9]{64}$/),count:f.number().int().min(1).max(1e5)}),bp=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()}),Vk=bp.parse({})});var vp,kp,Sp,xp,Ep,Lo,zk,qk,Tp,Rp,Ap,Ip,Cp,Yk,Jk,Np,Op,Xk,Dp=b(()=>{"use strict";ee();vp=14,kp=14,Sp=14,xp=1,Ep=365,Lo=f.number().int().min(xp).max(Ep),zk=["propose","direct"],qk="propose",Tp=["propose","direct"],Rp="propose",Ap=["propose","direct"],Ip="propose",Cp=["off","propose","direct"],Yk=["member","admin","owner"],Jk="member",Np="off",Op=f.object({version:f.literal(1).default(1),at_risk_days:Lo.default(vp),stagnation_days:Lo.default(kp),agent_date_mode:f.enum(zk).default(qk),health_manual_ttl_days:Lo.default(Sp),agent_event_mode:f.enum(Tp).default(Rp),agent_update_mode:f.enum(Ap).default(Ip),agent_pull_mode:f.enum(Cp).default(Np),org_wide_authoring_min_role:f.enum(Yk).default(Jk)}),Xk=Op.parse({})});var Pp,Zk,Mp=b(()=>{"use strict";ee();Pp=f.object({version:f.literal(1).default(1),org_visibility:f.boolean().default(!1),session_span_visibility:f.boolean().default(!0)}),Zk=Pp.parse({})});var Lp,$p,Qk,eS,Fp=b(()=>{"use strict";ee();Lp=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([])}),$p=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:Lp.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()}),Qk=$p.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()}),eS=f.object({id:f.string().uuid(),title:f.string(),summary:f.string(),tags:f.array(f.string()).default([])})});var jp=b(()=>{"use strict"});var Up=b(()=>{"use strict"});function As(e){let t=[],n=null;return e.split(`
|
|
29
|
-
`).
|
|
30
|
-
|
|
31
|
-
|
|
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=_S.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} ${Vo}`),null;l.push({name:p,version:m,content:h})}return l}function Rt(e,t={}){let n=t.maxFileBytes??vS,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=ud(e);a=m?`origin/${m}`:null,a===null&&r.push(`no default branch resolvable ${Cs}`)}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=kS(yS(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:SS(e,m.dir,h,a,r);c.push(...of({dir:m.dir,files:g,baseFiles:y})),l.push({dir:m.dir,migrationCount:g.length,tableCount:Ko(g).size})}let d=l.reduce((m,h)=>m+h.migrationCount,0),u=af(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 lr,wS,vS,Cs,Vo,Ns=b(()=>{"use strict";re();qn();o(rf,"stripSql");o(ge,"normalizeQualifiedIdent");o(Ue,"splitTopLevel");lr=["INSERT","UPDATE","DELETE"];o(bS,"parseDefaultAclTables");wS=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;o(sf,"parseTableRevoke");o(Ko,"foldTableAcl");o(Bo,"evaluateTableAcl");o(of,"computeTableAclFindings");o(af,"deriveTableAclVerdict");vS=5e6,Cs="\u2014 findings reported ungraded (open)",Vo="\u2014 baseline degraded";o(zo,"isTableAclGraded");o(kS,"safeRead");o(SS,"baseFilesFor");o(Rt,"checkTableAclLint")});import{readFileSync as xS}from"node:fs";import{join as qo}from"node:path";function Jo(e){return e.verdict!=="no_opinion"&&e.graded}function Xo(e){let t=new Set;for(let n of e.matchAll(ES))t.add(n[1]);return t}function Zo(e){return new Set([...e].map(t=>t.split("-")[0]))}function ff(e){return e.split(`
|
|
2
|
+
var Xc=Object.defineProperty;var o=(e,t)=>Xc(e,"name",{value:t,configurable:!0});var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(e,t)=>{for(var n in t)Xc(e,n,{get:t[n],enumerable:!0})};function Qc(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let s={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(s.toolName=c)}}return s}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function Yt(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 Rs(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Is(e,t,n,r,i,s){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:s}}function Cs(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Ns=b(()=>{"use strict";o(Qc,"parseFrame");o(Yt,"denyResult");o(Rs,"toolEvent");o(Is,"policyEvent");o(Cs,"shaEvent")});import{execFileSync as nl}from"node:child_process";function rl(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=b_}function w_(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let i=[];for(let s of g_){let a=r[s];typeof a=="string"&&el.test(a)&&i.push({field:s,sha:a})}for(let[s,a]of y_){let c=r[s];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&el.test(l)&&i.push({field:`${s}.${a}`,sha:l})}return i}function v_(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,tl);for(let i=tl;i>=__;i--){let s=r.slice(0,i),a=t(s);if(a!==null&&a.startsWith(s))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function Jt(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 il(){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=nl("git",["rev-parse","--show-toplevel"],{cwd:e,env:il(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function k_(e){return t=>{try{let r=nl("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:il(),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=w_(e);if(n.length===0)return[];let r=k_(t),i=[];for(let{field:s,sha:a}of n){let c=v_(a,r);c.verdict!=="proven"&&i.push({...c,field:s})}return i}var g_,y_,el,__,tl,b_,Os=b(()=>{"use strict";g_=["commit_sha","base_sha","head_sha"],y_=[["diff_stats","head_sha"],["diff_stats","base_sha"]],el=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,__=7,tl=12,b_=10;o(rl,"isDenyGrade");o(w_,"extractShaArgs");o(v_,"classifySha");o(Jt,"shaFindingText");o(il,"cleanGitEnv");o(Pr,"resolveRepoRootForSha");o(k_,"gitShaResolver");o(Mr,"inspectLineForShas")});var sl=b(()=>{"use strict"});function ol(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
|
|
3
|
+
`).slice(0,1e3)}var al=b(()=>{"use strict";o(ol,"nodeEmbedText")});var Ds,Ps=b(()=>{"use strict";Ds=["function","method","class","interface","enum","type_alias"]});function cl(e,t){let n=Math.min(e.length,t.length),r=0,i=0,s=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,i+=c*c,s+=l*l}return i===0||s===0?0:r/(Math.sqrt(i)*Math.sqrt(s))}var ll=b(()=>{"use strict";o(cl,"cosineSimilarity")});function $r(e){return`${e}#<module>`}function Lr(e,t,n){return`${e}#${t}:${n}`}var Kn=b(()=>{"use strict";o($r,"moduleKey");o(Lr,"symbolKey")});import{posix as Ms}from"node:path";function dl(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!S_.has(r.kind))continue;let i=t.get(r.name);i?i.push(r.nodeKey):t.set(r.name,[r.nodeKey])}return{nameToKeys:t,files:n}}function ul(e,t){let n=new Set,r=[],i=new Set,s=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}),i.add(a))},"push");for(let a of e.edges)s(a.srcKey,a.dstKey,a.kind);for(let a of e.nodes)i.add(a.nodeKey);for(let a of e.refs){let c=t.nameToKeys.get(a.targetName);!c||c.length!==1||s(a.fromKey,c[0],a.kind)}for(let a of e.imports){let c=x_(e.filePath,a.specifier,t.files);c&&s(a.fromModuleKey,$r(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}function x_(e,t,n){if(!t.startsWith("."))return null;let r=Ms.normalize(Ms.join(Ms.dirname(e),t)),i=[],s=Fr.some(c=>r.endsWith(c));s&&i.push(r);let a=/\.(js|jsx|mjs|cjs)$/.exec(r);if(a){let c=r.slice(0,-a[0].length);for(let l of Fr)i.push(c+l)}if(!s){for(let c of Fr)i.push(r+c);for(let c of Fr)i.push(`${r}/index${c}`)}for(let c of i)if(n.has(c))return c;return null}var S_,Fr,pl=b(()=>{"use strict";Kn();S_=new Set(["function","method","class","interface","enum","type_alias"]),Fr=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];o(dl,"buildResolutionIndex");o(ul,"resolveFileEdges");o(x_,"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 $s(e){return e.toLowerCase().endsWith(".d.ts")}var Ur=b(()=>{"use strict";o(jr,"languageForPath");o($s,"isSkippablePath")});import{appendFileSync as E_,existsSync as fl,mkdirSync as A_,readFileSync as T_}from"node:fs";import{join as R_}from"node:path";function Vn(e,t={}){try{if(!fl(e)){if(!t.create)return"skipped";A_(e,{recursive:!0})}let n=R_(e,".gitignore"),r=fl(n)?T_(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),s=Hr.filter(l=>!i.has(l));if(s.length===0)return"unchanged";let a=r===null?[...I_,...s]:s,c=r&&!r.endsWith(`
|
|
4
|
+
`)?`
|
|
5
|
+
`:"";return E_(n,c+a.join(`
|
|
6
|
+
`)+`
|
|
7
|
+
`),r===null?"created":"appended"}catch{return"skipped"}}var Hr,Ls,I_,Gr=b(()=>{"use strict";Hr=["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"],Ls=["# 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).'],I_=Ls;o(Vn,"ensureMaindLocalIgnore")});import{execFileSync as C_}from"node:child_process";import{createHash as N_}from"node:crypto";import{readFileSync as O_,readdirSync as D_,statSync as P_}from"node:fs";import{posix as js,sep as ml}from"node:path";function T(e,t){try{return C_("git",[...M_,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function $_(e){return ml==="/"?e:e.split(ml).join("/")}function Wr(e){let t=[];for(let n of e){let r=$_(n).trim();if(!r||$s(r))continue;let i=jr(r);i&&t.push({path:r,language:i})}return t}function gl(e){return Wr(e)}function yl(e){let t=Ve(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Wr(t.split(`
|
|
8
|
+
`));let n=[];return _l(e,"",n),Wr(n)}function _l(e,t,n){let r;try{r=D_(js.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&hl.has(i.name)||hl.has(i.name))continue;let s=t?`${t}/${i.name}`:i.name;i.isDirectory()?_l(e,s,n):i.isFile()&&n.push(s)}}function Us(e,t){return Hs(e,t)??t}function Hs(e,t){let n=T(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function Br(e,t={}){if(zn(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Us(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=Ve(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of s.split(`
|
|
9
|
+
`)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=Fs((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=Ve(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
|
|
10
|
+
`)){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=Fs(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 Fs(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function bl(e,t={}){let n=Br(e,t);return n===null?null:Wr(n.keys())}function wl(e,t){try{let n=P_(js.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function Kr(e){return N_("sha256").update(e).digest("hex")}function zn(e){return Ve(e,["rev-parse","HEAD"])?.trim()??null}function Vr(e,t){return Ve(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function vl(e){let t=Ve(e,["status","--porcelain","-uall"]);if(t===null)return!1;let n=t.split(`
|
|
11
|
+
`).filter(i=>i.trim().length>0);if(n.length===0)return!1;let r=L_(e);return n.some(i=>r===null||!F_(e,i,r))}function L_(e){let t=Ve(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function F_(e,t,n){let r=t[0],i=t[1];if(Fs(t.slice(3))!==n)return!1;let s;if(r==="?"&&i==="?"||r==="A"&&(i===" "||i==="M"))s="";else if((r===" "||r==="M")&&(i===" "||i==="M")){let p=Ve(e,["show",`HEAD:${n}`]);if(p===null)return!1;s=p}else return!1;let a;try{a=O_(js.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=o(p=>p.replace(/\r\n/g,`
|
|
12
|
+
`),"norm"),l=c(s),d=c(a);if(!d.startsWith(l))return!1;let u=new Set([...Hr,...Ls]);return d.slice(l.length).split(`
|
|
13
|
+
`).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var hl,M_,Ve,se=b(()=>{"use strict";Ur();Gr();hl=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),M_=["-c","diff.renames=true","-c","core.quotePath=false","-c","diff.algorithm=myers","-c","diff.indentHeuristic=true","-c","diff.interHunkContext=0","-c","diff.noprefix=false","-c","diff.mnemonicPrefix=false","-c","diff.srcPrefix=a/","-c","diff.dstPrefix=b/","-c","diff.relative=false","-c","diff.renameLimit=1000"];o(T,"runGit");Ve=T;o($_,"toPosix");o(Wr,"classify");o(gl,"classifyPaths");o(yl,"discoverSourceFiles");o(_l,"walk");o(Us,"resolveDiffBase");o(Hs,"resolveMergeBase");o(Br,"enumerateChangedPaths");o(Fs,"unquote");o(bl,"changedSourceFiles");o(wl,"statFile");o(Kr,"hashContent");o(zn,"headCommit");o(Vr,"resolveCommitSha");o(vl,"isWorktreeDirty");o(L_,"toolIgnoreRepoPath");o(F_,"isToolOnlyIgnoreChange")});function Sl(e,t={}){if(T(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?Us(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=T(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(s,"utf8")>j_?c="none":W_(s,a,()=>{c="partial"}),n){let l=T(e,["status","--porcelain","-uall"])??"";for(let d of l.split(`
|
|
14
|
+
`)){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 W_(e,t,n){let r=null,i=0,s=!1,a=!1,c=o(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
|
|
15
|
+
`)){if(l.startsWith("diff --git ")){c(),s=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){s=!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":s?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=G_.exec(l);if(d){if(i++,i>U_){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<H_&&r.addedLines.push(l.slice(1))}c()}var j_,U_,H_,kl,G_,xl=b(()=>{"use strict";se();j_=16*1024*1024,U_=500,H_=4e3,kl=256*1024,G_=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;o(Sl,"changedHunks");o(W_,"parseUnifiedDiff")});function V_(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function Al(e){return e.split(B_).filter(t=>t.trim().length>0)}function Tl(e){let[t,n,r,i,s]=e.replace(/\n+$/,"").split(K_);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:s??""}}function z_(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,i=t.get(r);i?i.commits+=1:t.set(r,{name:n.authorName,email:n.authorEmail,commits:1,lastDateIso:n.dateIso})}return[...t.values()].sort((n,r)=>r.commits-n.commits||n.email.localeCompare(r.email)).slice(0,10)}function Il(e,t,n={}){let r=V_(n.limit,20,100),i=n.includeOwnership!==!1,s=Math.max(r,Rl),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,Gs),l=[];for(let u of c){let p=T(e,["log","-n",String(s),El,"--",u]),m=p===null?[]:Al(p).map(Tl).filter(h=>h!==null);l.push({path:u,lastCommits:m.slice(0,r),ownership:i?{topAuthors:z_(m),commitsInWindow:m.length}:null})}let d=null;if(n.since){let u=Vr(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],m=T(e,["log",...p,"-n",String(zr+1),El,"--name-only","--",...c]),h=[];if(m!==null)for(let g of Al(m)){let y=g.split(`
|
|
16
|
+
`),_=Tl(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,zr),truncated:h.length>zr}}return{history:l,regression:d,ownershipWindowCommits:s,pathsTruncated:a.length>Gs}}var B_,K_,Rl,Gs,zr,El,Ws=b(()=>{"use strict";se();B_="",K_="\0",Rl=200,Gs=50,zr=100,El="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s";o(V_,"clamp");o(Al,"splitRecords");o(Tl,"parseHistoryRecord");o(z_,"aggregateOwnership");o(Il,"readFileHistory")});import{execFileSync as q_}from"node:child_process";import{readdirSync as Y_,statSync as Cl}from"node:fs";import{isAbsolute as J_,join as Bs,relative as X_,resolve as Z_}from"node:path";function eb(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function tb(e,t){try{let n=q_("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 nb(e){let t;try{t=Y_(e)}catch{return null}for(let n of t.filter(eb))try{let r=Cl(Bs(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function rb(e){try{return Cl(e).isDirectory()}catch{return!1}}function ib(e,t){let n=X_(e,t);return!n||n.startsWith("..")?t:n}function Ks(e){let t=Q_.filter(c=>rb(Bs(e,c))),n=tb(e,"core.hooksPath"),r=n?J_(n)?n:Z_(e,n):Bs(e,".git","hooks"),i=ib(e,r),s=nb(r);if(s===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?s===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:a,hookDirs:t,hooksPath:n,effectiveDir:i}}function Vs(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 Q_,zs=b(()=>{"use strict";Q_=[".githooks",".husky"];o(eb,"isRealHook");o(tb,"gitConfig");o(nb,"hasExecutableHook");o(rb,"isDir");o(ib,"displayPath");o(Ks,"resolveHookState");o(Vs,"describeHookState")});import{posix as Nl}from"node:path";function Xt(e){let t=sb.exec(e);return t?t[1]:null}function Oe(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function at(e,t){let n=T(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=o(s=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||s===c||s.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let s of n.split("\0").filter(Boolean)){if(!r(s))continue;let a=Nl.basename(s),c=Xt(a);if(c===null)continue;let l=Nl.dirname(s),d=i.get(l)??[];d.push({path:s,name:a,version:c}),i.set(l,d)}return[...i.entries()].map(([s,a])=>({dir:s,files:a.sort((c,l)=>Oe(c.version,l.version))})).sort((s,a)=>s.dir.localeCompare(a.dir))}function Ol(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 sb,qn=b(()=>{"use strict";se();sb=/^(\d+)_.+\.sql$/;o(Xt,"parseMigrationVersion");o(Oe,"compareVersions");o(at,"discoverSupabaseProjects");o(Ol,"resolveDefaultBranch")});import{execFileSync as ob}from"node:child_process";import{existsSync as Z,readFileSync as ze,readdirSync as qr,statSync as Ys}from"node:fs";import{posix as P}from"node:path";function db(e,t){let n=(()=>{let i=T(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=P.dirname(e);for(let i=0;i<8&&r&&r!==P.dirname(r);i++){if(Z(P.join(r,".git"))){let s=(()=>{let c=T(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&s!=null&&Xs(n,s))){let c=ub(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=P.dirname(r)}return null}function ub(e,t){let n=[];for(let r of cb){let i;try{i=qr(P.join(e,r),{withFileTypes:!0}).filter(s=>s.isFile()).map(s=>s.name)}catch{continue}for(let s of i){let a=`${r}/${s}`,c=P.join(e,a),l=P.join(t,a);try{let d=Ys(c),u=Ys(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>lb)continue;ze(c).equals(ze(l))||n.push(a)}catch{continue}}}return n.sort()}function jl(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,i=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}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let s=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(s){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(!s&&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 ${Zs}.`})}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=pb(e.hooks);return a&&t.push(a),fb(t)}function pb(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:Vs(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 fb(e){return[...e].sort((t,n)=>Dl[t.status]-Dl[n.status]||t.id.localeCompare(n.id))}function Ul(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function De(e){let t=e?.trim();return t||null}function mb(e){let t=De(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 hb(e){let t=De(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 gb(e){let t=[],n=null,r=o(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
|
|
17
|
+
`))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function yb(e){let t=P.join(e,Zs);if(!Z(t))return[];try{return ze(t,"utf8").split(`
|
|
18
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function _b(e){try{return at(e).map(t=>P.join(P.dirname(t.dir),"config.toml"))}catch{return[]}}function bb(e){let t=T(e,["ls-files","-z","--",...ab]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=Fl[P.basename(r)];if(i===void 0)continue;let s=P.dirname(r);if(!wb(e,s))continue;let a=s==="."?"node_modules":P.join(s,"node_modules");n.has(a)||n.set(a,{dir:a,install:i})}return[...n.values()]}function wb(e,t){return t==="."?!0:Js(e,t)}function Js(e,t){if(Z(P.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(ze(P.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Hl(e,t={}){if(De(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=De(T(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",s=i?null:r,a=mb(e),c=De(T(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let j=De(T(e,["rev-parse","HEAD"])),K=De(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=De(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(`
|
|
19
|
+
`).filter(j=>j.trim().length>0).length,g=hb(e),y=De(T(e,["rev-parse","--show-toplevel"]))??e,_=gb(T(e,["worktree","list","--porcelain"])??""),w=_[0]?.path??null,k=w!=null&&Xs(w,y),x=Math.max(0,_.length-1),S=null;if(w&&!Xs(w,y)){let j=o(L=>Z(P.join(w,L))&&!Z(P.join(y,L)),"here"),K=[...Ll,..._b(y),...yb(y),...t.probePaths??[]];S={mainWorktreePath:w,currentWorktreePath:y,missing:[...new Set(K.filter(j))],missingDeps:bb(y).filter(L=>j(L.dir))}}let I=db(y,e),$=t.includeRelease===!1?null:Tb(e,s),U=[];return a&&(U=(T(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
|
|
20
|
+
`).map(K=>K.trim()).filter(K=>K.length>0)),{isRepo:!0,branch:s,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:p,uncommitted:h,detachedHead:i,inProgressOp:g,isSharedMainTree:k,otherWorktrees:x,worktreeParity:S,toolCopyDrift:I,stalePackageBuilds:Gl(y),release:$,unmergedMigrations:U,hooks:Ks(e)}}function Xs(e,t){let n=o(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function Sb(e){let t=new Set;Js(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<Ml;){let i=n.pop();if(i===void 0)break;if(i.depth>=kb)continue;let s;try{s=qr(P.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let a of s){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=i.rel==="."?a.name:P.join(i.rel,a.name);if(r+=1,r>=Ml)break;Js(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function xb(e){let t=[];try{let n=P.join(e,"pnpm-workspace.yaml");if(Z(n)){let r=!1;for(let i of ze(n,"utf8").split(`
|
|
21
|
+
`)){let s=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);a?t.push(a[1]):s.trim().length>0&&!/^\s/.test(s)&&(r=!1)}}}else{let r=P.join(e,"package.json");if(Z(r)){let i=JSON.parse(ze(r,"utf8")),s=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(s)&&t.push(...s.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function Eb(e){let t=[];for(let n of Sb(e)){let r=n==="."?e:P.join(e,n),i=o(s=>n==="."?s:P.join(n,s),"prefix");for(let s of xb(r)){if(t.length>=qs)break;if(!(s.startsWith("!")||s.includes("**")))try{if(s.endsWith("/*")){let a=s.slice(0,-2),c=P.join(r,a);if(!Z(c))continue;for(let l of qr(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(P.join(a,l.name))),t.length>=qs)break}else s.includes("*")||t.push(i(s))}catch{}}}return t.slice(0,qs)}function $l(e){let t=null,n=0,r=[e];for(;r.length>0&&n<Pl;){let i=r.pop();if(i===void 0)break;let s;try{s=qr(i,{withFileTypes:!0})}catch{continue}for(let a of s){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=P.join(i,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=Ys(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=Pl)break}}}return t}function Ab(e,t){let n=new Set;for(let r of t)try{let i=P.join(e,r,"package.json");if(!Z(i))continue;let s=JSON.parse(ze(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=s[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 Gl(e){let t=[],n=Eb(e),r=Ab(e,n);for(let i of n)try{let s=P.join(e,i,"package.json");if(!Z(s))continue;let a=JSON.parse(ze(s,"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,i,"src"),h=P.join(e,i,u);if(!Z(m)||!Z(h))continue;let g=$l(m),y=$l(h);if(g===null||y===null)continue;let _=g-y;_>vb&&t.push({packageDir:i,buildDir:u,srcNewerByMs:Math.round(_),impact:p})}catch{}return t.sort((i,s)=>i.packageDir.localeCompare(s.packageDir))}function Tb(e,t){if(!t)return null;let n=Rb(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(s=>s.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}function Rb(e,t){try{return ob("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function Yn(e,t={}){let n=await Hl(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=jl(n),i=Ul(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var Ll,Zs,Fl,ab,cb,lb,Dl,vb,qs,Pl,kb,Ml,Qs=b(()=>{"use strict";zs();se();qn();Ll=["supabase/config.toml","supabase/.temp",".env"],Zs=".maind/worktree-requirements",Fl={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},ab=Object.keys(Fl).flatMap(e=>[e,"*/"+e]),cb=["scripts"],lb=512*1024;o(db,"gatherToolCopyDrift");o(ub,"compareToolDirs");o(jl,"computeDivergence");o(pb,"computeHookFinding");Dl={open:0,warn:1,info:2,passed:3};o(fb,"sortFindings");o(Ul,"isHealthy");o(De,"trimOrNull");o(mb,"resolveDefaultBranch");o(hb,"detectInProgressOp");o(gb,"parseWorktrees");o(yb,"readWorktreeRequirements");o(_b,"discoverSupabaseConfigProbes");o(bb,"discoverDependencyDirs");o(wb,"isWorkspaceRoot");o(Js,"hasWorkspaceMarkers");o(Hl,"gatherRepoHealthFacts");o(Xs,"samePath");vb=2e3,qs=64,Pl=4e3,kb=3,Ml=400;o(Sb,"findWorkspaceRoots");o(xb,"workspacePatternsAt");o(Eb,"listWorkspacePackageDirs");o($l,"newestMtimeUnder");o(Ab,"consumedWorkspaceNames");o(Gl,"gatherStalePackageBuilds");o(Tb,"gatherReleaseFact");o(Rb,"runGh");o(Yn,"checkDivergence")});import{existsSync as eo,readdirSync as Wl}from"node:fs";import{posix as be}from"node:path";function no(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(to)}function Kl(e,t={}){let n=t.minFiles??ro;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Bl)}function Qt(e){return`${e.dir}#${e.prefix}`}function Jn(e){let t=Ib.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function Vl(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let s=Qt(i),a=e.sightingsByNamespace.get(s);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=`${i.prefix}${l}`;t.push(p?{id:`number.collision:${s}#${l}`,status:"open",namespace:i,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:`${i.prefix}${io(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:${s}#${l}`,status:"info",namespace:i,number:l,title:`${h} is used more than once (pre-existing)`,detail:`${h} is carried by ${u.length} files: ${u.join(", ")}.`,sightings:d,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,s)=>r[i.status]-r[s.status]||i.id.localeCompare(s.id))}function zl(e){return!e.some(t=>t.status==="open")}function io(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}function so(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function ql(e,t){let n=so(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=Jn(be.basename(n));if(!i)return r;let s=`${be.dirname(n)}#${i.prefix}`,a=e.namespaces.find(u=>Qt(u)===s)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(s)??new Map,l=new Set,d=[];for(let u of c.get(i.number)??[])u.path===n||l.has(u.path)||(l.add(u.path),d.push(u));return{path:n,namespace:a,number:i.number,taken:d.length>0,sightings:d,suggestion:io(c.keys(),i.number)}}function Yr(e){let t=e?.trim();return t||null}function Zt(e){return e?e.split(`
|
|
22
|
+
`).filter(Boolean):[]}function Cb(e){let t=Yr(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 Yl(e,t={}){let n=t.minFiles??ro,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=T(e,r);if(i===null)return[];let s=new Map;for(let a of i.split("\0").filter(Boolean)){let c=be.dirname(a),l=Jn(be.basename(a));if(!l)continue;let d=`${c}#${l.prefix}`,u=s.get(d);u?u.numbers.push(l.number):s.set(d,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...s.values()].filter(a=>Kl(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)=>Qt(a).localeCompare(Qt(c)))}async function oo(e,t={}){let n=[];if(Yr(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 i=Yl(e,t),s=new Map(i.map(h=>[Qt(h),h])),a=[...new Set(i.map(h=>h.dir))],c=new Map,l=o((h,g,y)=>{let _=be.dirname(h),w=Jn(be.basename(h));if(!w)return;let k=`${_}#${w.prefix}`;if(!s.has(k))return;let x=c.get(k)??new Map,S=x.get(w.number)??[];S.push({kind:g,where:y,path:h}),x.set(w.number,S),c.set(k,x)},"record"),d=o((h,g,y)=>{if(a.length===0)return;let _=T(e,["ls-tree","-r","--name-only",h,"--",...a]);if(_===null){n.push(`could not read ${y}`);return}for(let w of Zt(_))l(w,g,y)},"scanTree");for(let h of a){let g=be.join(e,h);if(eo(g))try{for(let y of Wl(g))l(`${h}/${y}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let u=Cb(e),p=t.baseRef??(u?`origin/${u}`:null);if(p?d(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped"),t.includeBranches!==!1){let h=Yr(T(e,["rev-parse","--abbrev-ref","HEAD"]));for(let g of Zt(T(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))g!==h&&d(g,"branch",`Branch ${g}`)}if(t.includeWorktrees!==!1){let h=Yr(T(e,["rev-parse","--show-toplevel"]));for(let g of Zt(T(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===h||!eo(y)))for(let _ of a){let w=be.join(y,_);if(eo(w))try{for(let k of Wl(w))l(`${_}/${k}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${_} in ${y}`)}}}}let m=[];if(p&&a.length>0){let h=T(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);h===null?n.push(to):m=Zt(h);let g=T(e,["ls-files","--others","--exclude-standard","--",...a]);g!==null&&(m=[...m,...Zt(g)]);let y=T(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);y!==null&&(m=[...m,...Zt(y)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:i,sightingsByNamespace:c,addedPaths:m,skipped:n}}async function ct(e,t={}){let n=await oo(e,t),r=Vl(n);return{ok:zl(r),findings:r,facts:n}}async function lt(e,t,n={}){let r=so(t);if(!Jn(be.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await oo(e,{...n,dirs:n.dirs??[be.dirname(r)]});return ql(i,r)}var to,Ib,ro,Bl,Xn=b(()=>{"use strict";se();to="could not diff against the base ref \u2014 everything reported as info";o(no,"isNumberCollisionsGraded");Ib=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,ro=3,Bl=.8;o(Kl,"isCounterNamespace");o(Qt,"namespaceKey");o(Jn,"parseNumbered");o(Vl,"computeNumberCollisions");o(zl,"isCollisionFree");o(io,"suggestNextNumber");o(so,"normaliseRepoPath");o(ql,"checkProposedNumber");o(Yr,"trimOrNull");o(Zt,"lines");o(Cb,"resolveDefaultBranch");o(Yl,"detectNamespaces");o(oo,"gatherNumberCollisionFacts");o(ct,"checkNumberCollisions");o(lt,"checkNumberForPath")});import{execFileSync as Nb}from"node:child_process";import{createHash as Ob}from"node:crypto";function ao(e){return Ob("sha256").update(e).digest("hex")}function Db(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 Pb(e){let t=Db(e);return t?ao(t):null}function $b(e){return typeof e=="string"&&Mb.test(e)}function Jl(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if($b(t))return t;let n;try{n=Nb("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?Pb(n):null}var Mb,co=b(()=>{"use strict";o(ao,"sha256Hex");o(Db,"normalizeRemoteUrl");o(Pb,"projectKeyFromRemote");Mb=/^[a-f0-9]{64}$/;o($b,"isProjectKey");o(Jl,"computeProjectKey")});function mo(e){return`spec.${e}`}function en(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 Lb(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let s=0;s<i;s++){let a=(n[s].codePointAt(0)??0)-(r[s].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function Xl(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(Lb)}function Zn(e){return ao(JSON.stringify(Xl(e)))}var lo,uo,po,fo,ho=b(()=>{"use strict";co();lo={det_number_collisions:{version:"1.2.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"]}},uo="number.collision",po="theme.dead_class",fo="acl.missing_revoke";o(mo,"specDriftRuleId");o(en,"gradeEngineStatus");o(Lb,"codePointCompare");o(Xl,"normalizeEvidenceForHash");o(Zn,"hashDetectorEvidence")});import{existsSync as Fb,readFileSync as Zl}from"node:fs";import{posix as jb}from"node:path";function Zr(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}function Qr(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
|
|
23
|
+
`,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 Qn(e){return e==='"'||e==="'"||e==="`"}function ei(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function Jr(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let s=e[i];if(Qn(s)){i=Zr(e,i);continue}if(ei(e,i)){i=Qr(e,i);continue}if(s==="["||s==="{")r++;else if((s==="]"||s==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function Ub(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(ei(e,t)){t=Qr(e,t);continue}break}return e.slice(t)}function tn(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let s=e[i];if(Qn(s)){i=Zr(e,i);continue}if(ei(e,i)){i=Qr(e,i);continue}s==="["||s==="{"||s==="("?n++:s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(s=>Ub(s).trim()).filter(s=>s.length>0)}function nd(e){let t=Zr(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
|
|
24
|
+
`:i==="r"?"\r":i==="t"?" ":i)}function Hb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yo(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${Hb(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,s=!1;for(;i<e.length;){let a=e[i];if(Qn(a)){i=Zr(e,i);continue}if(ei(e,i)){i=Qr(e,i);continue}if(!s){if(a==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))s=!0;else if(a===";")return null;i++;continue}if(a==="[")return Jr(e,i);if(a===";")return null;i++}return null}function _o(e){let t={};if(!e.startsWith("{"))return t;for(let n of tn(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],s=r[4].trim();Qn(s[0]??"")&&(t[i]=nd(s))}return t}function Gb(e,t){if(!e.startsWith("{"))return null;for(let n of tn(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 rd(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function id(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function sd(e,t){let n=yo(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=id(),i=[],s=0;for(let a of tn(n.slice(1,-1))){if(!a.startsWith("{")){s++;continue}let c=_o(a),l=c[t.key_field];if(!l){s++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");i.push({key:l,fields:rd(c,t.fields),orderPath:d,ordinal:r(d)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function od(e,t){let n=yo(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=id(),i=[],s=0,a=o((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let m of tn(c.slice(1,-1))){let h={...d},g=null;if(u.shape==="object"){if(!m.startsWith("{")){s++;continue}let y=_o(m);for(let[_,w]of Object.entries(u.fields??{}))h[_]=y[String(w)]??"";if(!p&&typeof u.children=="string"){let _=Gb(m,u.children);g=_&&_.startsWith("[")?Jr(_,0):null}}else{if(!m.startsWith("[")){s++;continue}let y=tn(m.slice(1,-1));for(let[_,w]of Object.entries(u.fields??{})){let k=y[Number(w)];h[_]=k!==void 0&&Qn(k[0]??"")?nd(k):""}if(!p&&typeof u.children=="number"){let _=y[u.children];g=_!==void 0&&_.startsWith("[")?Jr(_,0):null}}if(p){let y=h[t.key_field];if(!y){s++;continue}let _=(t.partition_by??[]).map(w=>h[w]??"");i.push({key:y,fields:rd(h,t.fields),orderPath:_,ordinal:r(_)});continue}g!==null&&a(g,l+1,h)}},"walk");return a(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function Ql(e,t){return t.extractor==="object-array"?sd(e,t):od(e,t)}function ad(e,t,n){let r=e;return t.strip_prefix&&r.startsWith(t.strip_prefix)&&(r=r.slice(t.strip_prefix.length)),t.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}function cd(e,t,n){return`spec.drift:${e}#${t}:${n}`}function Wb(e){return e.orderPath.join(" / ")||"(flat)"}function ld(e,t,n,r){let i=[],s=o((d,u,p,m,h,g)=>{i.push({id:cd(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){s("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${Wb(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&&s("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)";s("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${m.join(" \u2192 ")}
|
|
25
|
+
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)||s("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(ad(d,e.grounding,r))continue;let u=a.has(d);s("unrealized",u?"open":"warn",d,u?`${d} is referenced by the implementation but has no artefact`:`${d} is declared by the specification but not built yet`,u?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}function Bb(e,t,n){let r=[];for(let i of e.assertions??[]){let s=n.get(i.path);if(!s)continue;let a=s.indexOf(i.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(s.slice(a+i.prefix.length));if(!c)continue;let l=Number(c[1]),d=t[i.counts];l!==d&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${d}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function ed(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 dd(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 i=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(ed(h.id,`Declared file could not be read: ${x}`)),m.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let _=Ql(g,h.spec),w=Ql(y,h.impl);if(_.error||w.error){p.push(ed(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(...ld(h,_.records,w.records,e.files)),p.push(...Bb(h,{spec:_.records.length,impl:w.records.length},u))}return{findings:p,contracts:m}},"runOnce"),s=i(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let u of i(e.baselineSources).findings)u.id.startsWith("contract.unreadable:")||a.add(u.id);let c=new Map;for(let u of r)for(let p of u.exceptions??[])c.set(cd(u.id,p.dimension,p.key),p);let l=s.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}
|
|
26
|
+
Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>td[u.status]-td[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:s.contracts}}function go(e){let t=e?.trim();return t||null}function ti(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"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let s=o(a=>({manifest:null,error:a}),"bad");for(let[a,c]of i.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${a+1}`;if(!l)return s(`${u}: not an object`);if(!d)return s(`${u}: \`id\` is missing`);if(!r(l.reason))return s(`${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 s(`${u}: \`${p}\` is missing`);let h=r(m.extractor);if(!h)return s(`${u}: \`${p}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return s(`${u}: unknown \`${p}.extractor\` "${h}"`);if(!r(m.path)||!r(m.symbol)||!r(m.key_field))return s(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(m.levels))return s(`${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 s(`${u}: exception for "${r(m?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}function Kb(e){let t=go(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 Vb(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 ud(e,t={}){let n=o((g,y)=>jb.join(g,y),"join"),r=t.manifestPath??Xr,i=[],s={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(go(T(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...s,manifestError:"not a git work tree"};let a=n(e,r);if(!Fb(a))return{...s,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}=ti(Zl(a,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...s,isRepo:!0,manifestError:l};let d=new Map;for(let g of Vb(c))try{d.set(g,Zl(n(e,g),"utf8"))}catch{d.set(g,null),i.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=T(e,["ls-files","-z"]);if(p===null)i.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:Kb(e),y=t.baseRef??(g?`origin/${g}`:null);if(!y)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(m=go(T(e,["merge-base",y,"HEAD"])),!m)i.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:i}}async function dt(e,t={}){let n=await ud(e,t);return{...dd(n,t),facts:n}}function bo(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var Xr,td,er=b(()=>{"use strict";se();Xr=".maind/spec-contracts.json";o(Zr,"endOfString");o(Qr,"skipComment");o(Qn,"isQuote");o(ei,"isCommentStart");o(Jr,"sliceBalanced");o(Ub,"stripLeadingTrivia");o(tn,"splitTopLevel");o(nd,"readStringLiteral");o(Hb,"escapeRe");o(yo,"findSymbolArray");o(_o,"parseObjectFields");o(Gb,"objectFieldRaw");o(rd,"pickFields");o(id,"makeOrdinals");o(sd,"extractObjectArray");o(od,"extractNestedList");o(Ql,"extractRecords");o(ad,"isGrounded");o(cd,"findingId");o(Wb,"partitionOf");o(ld,"compareContract");o(Bb,"checkAssertions");o(ed,"unreadable");td={open:0,warn:1,info:2,passed:3};o(dd,"computeSpecDrift");o(go,"trimOrNull");o(ti,"parseManifest");o(Kb,"resolveDefaultBranch");o(Vb,"declaredPaths");o(ud,"gatherSpecDriftFacts");o(dt,"checkSpecDrift");o(bo,"isSpecDriftGraded")});var M,wo,A,we,tr=b(()=>{(function(e){e.assertEqual=i=>{};function t(i){}o(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}o(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},e.getValidEnumValues=i=>{let s=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(let c of s)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},e.find=(i,s)=>{for(let a of i)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}o(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(M||(M={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(wo||(wo={}));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,zb,oe,ni=b(()=>{tr();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"]),zb=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(s){return s.message},r={_errors:[]},i=o(s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(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 i(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 i of this.issues)if(i.path.length>0){let s=i.path[0];n[s]=n[s]||[],n[s].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};oe.create=e=>new oe(e)});var qb,Pe,vo=b(()=>{ni();tr();qb=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"),Pe=qb});function Yb(e){pd=e}function nn(){return pd}var pd,ri=b(()=>{vo();pd=Pe;o(Yb,"setErrorMap");o(nn,"getErrorMap")});function E(e,t){let n=nn(),r=nr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Pe?void 0:Pe].filter(i=>!!i)});e.common.issues.push(r)}var nr,Jb,V,C,ut,Q,ii,si,qe,rn,ko=b(()=>{ri();vo();nr=o(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:t,defaultError:c}).message;return{...i,path:s,message:c}},"makeIssue"),Jb=[];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 i of n){if(i.status==="aborted")return C;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let s=await i.key,a=await i.value;r.push({key:s,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return C;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[s.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"),ii=o(e=>e.status==="aborted","isAborted"),si=o(e=>e.status==="dirty","isDirty"),qe=o(e=>e.status==="valid","isValid"),rn=o(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var fd=b(()=>{});var R,md=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:i}=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:i}:{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:i}}function _d(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 fw(e){return new RegExp(`^${_d(e)}$`)}function bd(e){let t=`${yd}T${_d(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 mw(e,t){return!!((t==="v4"||!t)&&ow.test(e)||(t==="v6"||!t)&&cw.test(e))}function hw(e,t){if(!nw.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,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function gw(e,t){return!!((t==="v4"||!t)&&aw.test(e)||(t==="v6"||!t)&&lw.test(e))}function yw(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}function sn(e){if(e instanceof ae){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=de.create(sn(r))}return new ae({...e._def,shape:o(()=>t,"shape")})}else return e instanceof Le?new Le({...e._def,type:sn(e.element)}):e instanceof de?de.create(sn(e.unwrap())):e instanceof ke?ke.create(sn(e.unwrap())):e instanceof ve?ve.create(e.items.map(t=>sn(t))):e}function xo(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 i=M.objectKeys(t),s=M.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(let c of s){let l=xo(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 i=[];for(let s=0;s<e.length;s++){let a=e[s],c=t[s],l=xo(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===A.date&&r===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function wd(e,t){return new kt({values:e,typeName:N.ZodEnum,...O(t)})}function gd(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function vd(e,t={},n){return e?Je.create().superRefine((r,i)=>{let s=e(r);if(s instanceof Promise)return s.then(a=>{if(!a){let c=gd(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!s){let a=gd(t,r),c=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:c})}}):Je.create()}var ue,hd,D,Xb,Zb,Qb,ew,tw,nw,rw,iw,sw,So,ow,aw,cw,lw,dw,uw,yd,pw,Ye,pt,ft,mt,ht,on,gt,yt,Je,$e,he,an,Le,ae,_t,Me,oi,bt,ve,ai,cn,ln,ci,wt,vt,kt,St,Xe,pe,de,ke,xt,Et,dn,_w,rr,ir,At,bw,N,ww,kd,Sd,vw,kw,xd,Sw,xw,Ew,Aw,Tw,Rw,Iw,Cw,Nw,Ow,Dw,Pw,Mw,$w,Lw,Fw,jw,Uw,Hw,Gw,Ww,Bw,Kw,Vw,zw,qw,Yw,Jw,Xw,Zw,Qw,ev,tv,nv,Ed=b(()=>{ni();ri();md();ko();tr();ue=class{static{o(this,"ParseInputLazyPath")}constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}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}},hd=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 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(rn(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)},i=this._parseSync({data:t,path:r.path,parent:r});return hd(r,i)}"~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 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:we(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(rn(i)?i:Promise.resolve(i));return hd(r,s)}refine(t,n){let r=o(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,s)=>{let a=t(i),c=o(()=>s.addIssue({code:v.custom,...r(i)}),"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,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):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 Le.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 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 xt({...O(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new rr({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 ir.create(this,t)}readonly(){return At.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Xb=/^c[^\s-]{8,}$/i,Zb=/^[0-9a-z]+$/,Qb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ew=/^[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,tw=/^[a-z0-9_-]{21}$/i,nw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rw=/^[-+]?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)?)??$/,iw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ow=/^(?:(?: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])$/,aw=/^(?:(?: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])$/,cw=/^(([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]))$/,lw=/^(([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])$/,dw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,uw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yd="((\\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])))",pw=new RegExp(`^${yd}$`);o(_d,"timeRegexSource");o(fw,"timeRegex");o(bd,"datetimeRegex");o(mw,"isValidIP");o(hw,"isValidJWT");o(gw,"isValidCidr");Ye=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 s=this._getOrReturnCtx(t);return E(s,{code:v.invalid_type,expected:A.string,received:s.parsedType}),C}let r=new V,i;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:v.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:v.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?E(i,{code:v.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&E(i,{code:v.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")iw.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"email",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")So||(So=new RegExp(sw,"u")),So.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"emoji",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")ew.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"uuid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")tw.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"nanoid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Xb.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cuid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Zb.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cuid2",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Qb.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"ulid",code:v.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),E(i,{validation:"url",code:v.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"regex",code:v.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),E(i,{code:v.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),E(i,{code:v.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),E(i,{code:v.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?bd(s).test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:v.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?pw.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:v.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?fw(s).test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:v.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?rw.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"duration",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?mw(t.data,s.version)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"ip",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?hw(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"jwt",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?gw(t.data,s.version)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cidr",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?dw.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"base64",code:v.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?uw.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"base64url",code:v.invalid_string,message:s.message}),r.dirty()):M.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{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}};Ye.create=e=>new Ye({checks:[],typeName:N.ZodString,coerce:e?.coerce??!1,...O(e)});o(yw,"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)!==A.number){let s=this._getOrReturnCtx(t);return E(s,{code:v.invalid_type,expected:A.number,received:s.parsedType}),C}let r,i=new V;for(let s of this._def.checks)s.kind==="int"?M.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:v.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?yw(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:v.not_finite,message:s.message}),i.dirty()):M.assertNever(s);return{status:i.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,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:R.toString(i)}]})}_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)}};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)!==A.bigint)return this._getInvalidInput(t);let r,i=new V;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),E(r,{code:v.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):M.assertNever(s);return{status:i.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,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:R.toString(i)}]})}_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}};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)!==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)}};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)!==A.date){let s=this._getOrReturnCtx(t);return E(s,{code:v.invalid_type,expected:A.date,received:s.parsedType}),C}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return E(s,{code:v.invalid_date}),C}let r=new V,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:v.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:v.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):M.assertNever(s);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}};ht.create=e=>new ht({checks:[],coerce:e?.coerce||!1,typeName:N.ZodDate,...O(e)});on=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)}};on.create=e=>new on({typeName:N.ZodSymbol,...O(e)});gt=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)}};gt.create=e=>new gt({typeName:N.ZodUndefined,...O(e)});yt=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)}};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)});$e=class extends D{static{o(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return Q(t.data)}};$e.create=e=>new $e({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)});an=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)}};an.create=e=>new an({typeName:N.ZodVoid,...O(e)});Le=class e extends D{static{o(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==A.array)return E(n,{code:v.invalid_type,expected:A.array,received:n.parsedType}),C;if(i.exactLength!==null){let a=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(a||c)&&(E(n,{code:a?v.too_big:v.too_small,minimum:c?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(E(n,{code:v.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(E(n,{code:v.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>i.type._parseAsync(new ue(n,a,n.path,c)))).then(a=>V.mergeArray(r,a));let s=[...n.data].map((a,c)=>i.type._parseSync(new ue(n,a,n.path,c)));return V.mergeArray(r,s)}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)}};Le.create=(e,t)=>new Le({type:e,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...O(t)});o(sn,"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:i}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof he&&this._def.unknownKeys==="strip"))for(let d in i.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let u=s[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new ue(i,p,i.path,d)),alwaysSet:d in i.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:i.data[u]}});else if(d==="strict")c.length>0&&(E(i,{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=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new ue(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.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 i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:R.errToObj(t).message??i}:{message:i}},"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 sn(this)}partial(t){let n={};for(let r of M.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.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 s=this.shape[r];for(;s instanceof de;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:o(()=>n,"shape")})}keyof(){return wd(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)});_t=class extends D{static{o(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(let c of s)if(c.result.status==="valid")return c.result;for(let c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=s.map(c=>new oe(c.ctx.common.issues));return E(n,{code:v.invalid_union,unionErrors:a}),C}if(o(i,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let s,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"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.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}};_t.create=(e,t)=>new _t({options:e,typeName:N.ZodUnion,...O(t)});Me=o(e=>e instanceof wt?Me(e.schema):e instanceof pe?Me(e.innerType()):e instanceof vt?[e.value]:e instanceof kt?e.options:e instanceof St?M.objectValues(e.enum):e instanceof xt?Me(e._def.innerType):e instanceof gt?[void 0]:e instanceof yt?[null]:e instanceof de?[void 0,...Me(e.unwrap())]:e instanceof ke?[null,...Me(e.unwrap())]:e instanceof rr||e instanceof At?Me(e.unwrap()):e instanceof Et?Me(e._def.innerType):[],"getDiscriminator"),oi=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,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._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 i=new Map;for(let s of n){let a=Me(s.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(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,s)}}return new e({typeName:N.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...O(r)})}};o(xo,"mergeValues");bt=class extends D{static{o(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=o((s,a)=>{if(ii(s)||ii(a))return C;let c=xo(s.value,a.value);return c.valid?((si(s)||si(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(([s,a])=>i(s,a)):i(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)});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 s=[...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(s).then(a=>V.mergeArray(n,a)):V.mergeArray(n,s)}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)})};ai=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 i=[],s=this._def.keyType,a=this._def.valueType;for(let c in r.data)i.push({key:s._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,i):V.mergeObjectSync(n,i)}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)})}},cn=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 i=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new ue(r,c,r.path,[d,"key"])),value:s._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}}}};cn.create=(e,t,n)=>new cn({valueType:t,keyType:e,typeName:N.ZodMap,...O(n)});ln=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 i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(E(r,{code:v.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(E(r,{code:v.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let s=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)=>s._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)}};ln.create=(e,t)=>new ln({valueType:e,minSize:null,maxSize:null,typeName:N.ZodSet,...O(t)});ci=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 nr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nn(),Pe].filter(d=>!!d),issueData:{code:v.invalid_arguments,argumentsError:l}})}o(r,"makeArgsIssue");function i(c,l){return nr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nn(),Pe].filter(d=>!!d),issueData:{code:v.invalid_return_type,returnTypeError:l}})}o(i,"makeReturnsIssue");let s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Xe){let c=this;return Q(async function(...l){let d=new oe([]),u=await c._def.args.parseAsync(l,s).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,s).catch(h=>{throw d.addIssue(i(p,h)),d})})}else{let c=this;return Q(function(...l){let d=c._def.args.safeParse(l,s);if(!d.success)throw new oe([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,s);if(!p.success)throw new oe([i(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($e.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($e.create()),returns:n||$e.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(wd,"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=wd;St=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 i=M.objectValues(n);return E(r,{expected:M.joinValues(i),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 i=M.objectValues(n);return E(r,{received:r.data,code:v.invalid_enum_value,options:i}),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!==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(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Xe.create=(e,t)=>new Xe({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),i=this._def.effect||null,s={addIssue:o(a=>{E(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(r.data,s);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(i.type==="refinement"){let a=o(c=>{let l=i.refinement(c,s);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(i.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=i.transform(a.value,s);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(i.transform(a.value,s)).then(c=>({status:n.value,value:c})):C);M.assertNever(i)}};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)});xt=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}};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:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return rn(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new oe(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new oe(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)});dn=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}}};dn.create=e=>new dn({typeName:N.ZodNaN,...O(e)});_w=Symbol("zod_brand"),rr=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}},ir=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 s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?C:s.status==="dirty"?(n.dirty(),ut(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})},"handleAsync")();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?C:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:N.ZodPipeline})}},At=class extends D{static{o(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=o(i=>(qe(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return rn(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};At.create=(e,t)=>new At({innerType:e,typeName:N.ZodReadonly,...O(t)});o(gd,"cleanParams");o(vd,"custom");bw={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={}));ww=o((e,t={message:`Input not instance of ${e.name}`})=>vd(n=>n instanceof e,t),"instanceOfType"),kd=Ye.create,Sd=pt.create,vw=dn.create,kw=ft.create,xd=mt.create,Sw=ht.create,xw=on.create,Ew=gt.create,Aw=yt.create,Tw=Je.create,Rw=$e.create,Iw=he.create,Cw=an.create,Nw=Le.create,Ow=ae.create,Dw=ae.strictCreate,Pw=_t.create,Mw=oi.create,$w=bt.create,Lw=ve.create,Fw=ai.create,jw=cn.create,Uw=ln.create,Hw=ci.create,Gw=wt.create,Ww=vt.create,Bw=kt.create,Kw=St.create,Vw=Xe.create,zw=pe.create,qw=de.create,Yw=ke.create,Jw=pe.createWithPreprocess,Xw=ir.create,Zw=o(()=>kd().optional(),"ostring"),Qw=o(()=>Sd().optional(),"onumber"),ev=o(()=>xd().optional(),"oboolean"),tv={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")},nv=C});var f={};ie(f,{BRAND:()=>_w,DIRTY:()=>ut,EMPTY_PATH:()=>Jb,INVALID:()=>C,NEVER:()=>nv,OK:()=>Q,ParseStatus:()=>V,Schema:()=>D,ZodAny:()=>Je,ZodArray:()=>Le,ZodBigInt:()=>ft,ZodBoolean:()=>mt,ZodBranded:()=>rr,ZodCatch:()=>Et,ZodDate:()=>ht,ZodDefault:()=>xt,ZodDiscriminatedUnion:()=>oi,ZodEffects:()=>pe,ZodEnum:()=>kt,ZodError:()=>oe,ZodFirstPartyTypeKind:()=>N,ZodFunction:()=>ci,ZodIntersection:()=>bt,ZodIssueCode:()=>v,ZodLazy:()=>wt,ZodLiteral:()=>vt,ZodMap:()=>cn,ZodNaN:()=>dn,ZodNativeEnum:()=>St,ZodNever:()=>he,ZodNull:()=>yt,ZodNullable:()=>ke,ZodNumber:()=>pt,ZodObject:()=>ae,ZodOptional:()=>de,ZodParsedType:()=>A,ZodPipeline:()=>ir,ZodPromise:()=>Xe,ZodReadonly:()=>At,ZodRecord:()=>ai,ZodSchema:()=>D,ZodSet:()=>ln,ZodString:()=>Ye,ZodSymbol:()=>on,ZodTransformer:()=>pe,ZodTuple:()=>ve,ZodType:()=>D,ZodUndefined:()=>gt,ZodUnion:()=>_t,ZodUnknown:()=>$e,ZodVoid:()=>an,addIssueToContext:()=>E,any:()=>Tw,array:()=>Nw,bigint:()=>kw,boolean:()=>xd,coerce:()=>tv,custom:()=>vd,date:()=>Sw,datetimeRegex:()=>bd,defaultErrorMap:()=>Pe,discriminatedUnion:()=>Mw,effect:()=>zw,enum:()=>Bw,function:()=>Hw,getErrorMap:()=>nn,getParsedType:()=>we,instanceof:()=>ww,intersection:()=>$w,isAborted:()=>ii,isAsync:()=>rn,isDirty:()=>si,isValid:()=>qe,late:()=>bw,lazy:()=>Gw,literal:()=>Ww,makeIssue:()=>nr,map:()=>jw,nan:()=>vw,nativeEnum:()=>Kw,never:()=>Iw,null:()=>Aw,nullable:()=>Yw,number:()=>Sd,object:()=>Ow,objectUtil:()=>wo,oboolean:()=>ev,onumber:()=>Qw,optional:()=>qw,ostring:()=>Zw,pipeline:()=>Xw,preprocess:()=>Jw,promise:()=>Vw,quotelessJson:()=>zb,record:()=>Fw,set:()=>Uw,setErrorMap:()=>Yb,strictObject:()=>Dw,string:()=>kd,symbol:()=>xw,transformer:()=>zw,tuple:()=>Lw,undefined:()=>Ew,union:()=>Pw,unknown:()=>Rw,util:()=>M,void:()=>Cw});var Eo=b(()=>{ri();ko();fd();tr();Ed();ni()});var ee=b(()=>{Eo();Eo()});var Ao,To=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 rv,Ad=b(()=>{"use strict";ee();To();rv=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 Td,Rd,Id,Cd,Ro,Nd,Od,Dd,iv,Pd=b(()=>{"use strict";ee();Td=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],Rd=f.enum(Td),Id=["new_to_ai_agents","new_to_this_client","experienced"],Cd=f.enum(Id),Ro=[{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"}],Nd=Ro.map(e=>e.header),Od=f.object({experience_level:f.array(Cd).default([]),stack_filters:f.array(f.string()).default([])}).default({experience_level:[],stack_filters:[]}),Dd=f.object({id:f.string().min(1),client:Rd,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:Od,version:f.number().int().min(1).default(1),changelog:f.string().max(500).optional()}),iv=Dd.extend({body:f.string().min(1)})});var $d,li,Ld,di,sv,ov,Fd,jd,Ud,Hd,ui,av,cv,Md,lv,Gd,dv,Wd=b(()=>{"use strict";ee();$d=["operating_procedure","code_review","communication_style"],li=f.enum($d),Ld=["info","recommended","required"],di=f.enum(Ld),sv=["optional","default_on","mandatory"],ov=f.enum(sv),Fd=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],jd=f.enum(Fd),Ud=["verify","contribute","mixed"],Hd=f.enum(Ud),ui=f.object({clients:f.array(jd).default([]),stacks:f.array(f.string()).default([]),intents:f.array(Hd).default([])}).default({clients:[],stacks:[],intents:[]}),av=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,cv=64,Md=200,lv=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")),Gd=f.object({id:f.string().min(5).max(cv).regex(av,"id must match conv_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),scope:li,version:f.number().int().min(1),changed_at:lv,changelog:f.string().max(500).optional(),applies_to:ui,severity:di.default("recommended"),disableability:ov.default("default_on"),summary:f.string().min(1).max(Md,`summary must be \u2264 ${Md} 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()}),dv=Gd.extend({body:f.string().min(1)})});var Ze=b(()=>{"use strict";To();Ad();Pd();Wd()});var Io,pi,Co,Bd,Kd,Vd,uv,zd=b(()=>{"use strict";ee();Io=f.object({type:f.literal("text"),md:f.string().min(1).max(2e4)}),pi=f.number().min(0).max(1).optional(),Co=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:pi,right:pi,bottom:pi,left:pi}).optional()}),Bd=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")}),Kd=f.object({type:f.literal("accordion"),title:f.string().min(1).max(200),subtag:Bd.optional(),blocks:f.array(f.discriminatedUnion("type",[Io,Co])).max(50)}),Vd=f.discriminatedUnion("type",[Io,Co,Kd]),uv=f.array(Vd).max(100)});var qd,pv,Yd,Jd,fv,mv,hv,Xd=b(()=>{"use strict";ee();qd=["free","solo_pro","team","enterprise"],pv=f.enum(qd),Yd=["solo_pro","team","enterprise"],Jd=f.enum(Yd),fv=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),mv=f.object({user_id:f.string().uuid(),tier:Jd,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:fv.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"}),hv=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var Zd=b(()=>{"use strict"});var gv,yv,_v,Qd=b(()=>{"use strict";ee();gv=f.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),yv=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:gv.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"}),_v=f.object({override_id:f.string().uuid(),reason:f.string().min(3).max(200).optional()})});var eu,bv,tu,nu,ru,iu,wv,su=b(()=>{"use strict";ee();eu=f.enum(["info","important","critical"]),bv=f.enum(["pass","warn","fail"]),tu=f.object({type:f.enum(["template","lesson"]),id:f.string().min(1)}),nu=f.object({languages:f.array(f.string()).optional(),tools:f.array(f.string()).optional()}).optional(),ru=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")})]),iu=f.object({id:f.string().min(1),title:f.string().min(1),severity:eu,weight:f.number().int().positive().max(100),applies_when:nu,check:ru,fail_message:f.string().min(1),warn_message:f.string().optional(),remediation:tu.optional()}),wv=f.object({version:f.literal(1),checks:f.array(iu).min(1)})});function kv(e){if(!vv.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function fi(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 Sv(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var vv,mi,ou,au,Se,cu,xv,lu=b(()=>{"use strict";ee();vv=/^\d{4}-\d{2}-\d{2}$/;o(kv,"isRealDate");mi=f.string().refine(kv,{message:"expected a real calendar date as YYYY-MM-DD"}),ou=["exact","prefix"],au=f.enum(ou),Se=f.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),cu=f.object({model_pattern:f.string().min(1).max(100),match_kind:au,valid_from:mi,valid_to:mi.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=>fi(e)===0||fi(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"||fi(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=>fi(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(fi,"aboveRateCount");o(Sv,"rowKey");xv=f.object({changelog:f.string().min(1).max(500),as_of:mi,source_url:f.string().url().max(500),rows:f.array(cu).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,s)=>{let a=Sv(i),c=n.get(a);c!==void 0?t.addIssue({code:f.ZodIssueCode.custom,path:["rows",s],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,s)});let r=new Map;e.rows.forEach((i,s)=>{let a=`${i.model_pattern}|${i.match_kind}`,c=r.get(a)??[];c.push({i:s,r:i}),r.set(a,c)});for(let i of r.values())if(!(i.length<2)){i.sort((s,a)=>s.r.valid_from.localeCompare(a.r.valid_from));for(let s=0;s<i.length-1;s++){let a=i[s],c=i[s+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 un=b(()=>{"use strict"});var sr=b(()=>{"use strict"});var fu=b(()=>{"use strict";sr();un()});var mu=b(()=>{"use strict";un()});var hu=b(()=>{"use strict";Ze();sr();un()});var gu=b(()=>{"use strict";sr();un()});var yu=b(()=>{"use strict";un();fu();mu();hu();gu();sr()});var Wv,Bv,_u,Kv,bu,No,wu,vu,ku,Su,Vv,Oo=b(()=>{"use strict";ee();Ze();Wv=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,Bv=64,_u=200,Kv=1e3,bu=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")),No=f.enum(["low","medium","high"]),wu=f.object({owner:f.string().min(1).max(160).optional(),risk_level:No.optional(),reviewed_at:bu.optional()}).default({}),vu=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}),ku=f.object({lesson_query:vu,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:[]}),Su=f.object({id:f.string().min(6).max(Bv).regex(Wv,"id must match skill_<lowercase_alphanum_underscore>"),title:f.string().min(1).max(200),version:f.number().int().min(1),changed_at:bu,tier:f.enum(["community","curated"]).default("curated"),summary:f.string().min(1).max(_u,`summary must be \u2264 ${_u} chars (rendered as one line in skill_index)`),description:f.string().max(Kv).optional(),applies_to:ui,membership:ku,governance:wu}),Vv=Su.extend({body:f.string().default(""),org_id:f.string().uuid().optional(),org_name:f.string().optional()})});var xu,Eu,Au,Tu,Ru,Iu,zv,Cu,qv,Yv,Nu=b(()=>{"use strict";ee();Oo();xu=f.enum(["maind","agent-skill"]),Eu=f.enum(["ready","needs_attention","blocked"]),Au=f.enum(["info","important","critical"]),Tu=f.enum(["pass","warn","fail"]),Ru=f.enum(["structure","governance","scope","membership","package","references"]),Iu=f.object({id:f.string().min(1),title:f.string().min(1),status:Tu,severity:Au,category:Ru,field:f.string().nullable().optional(),message:f.string().min(1),hint:f.string().optional()}),zv=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({}),Cu=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(),qv=f.object({directory_name:f.string().min(1).max(120).optional(),frontmatter:Cu,body:f.string().default(""),file_listing:f.array(f.string()).optional()}),Yv=f.object({format:xu,subject:f.string().min(1),status:Eu,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(Iu),next_steps:f.array(f.string()),trust_note:f.string().min(1)})});var Ou,Jv,Du,Pu,Mu,pn,Xv,$u,Lu,Fu,ju,Uu,Zv,Qv,Hu,ek,Gu=b(()=>{"use strict";ee();Ze();Ou=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],Jv=f.enum(Ou),Du=["verdict","advisory"],Pu=f.enum(Du),Mu=["block","warn","note"],pn=f.enum(Mu),Xv=f.object({convention_id:f.string().min(1).max(64),convention_version:f.number().int().min(1),severity:di,scope:li,grade:Pu,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()}),$u=["open","warn","info"],Lu=f.enum($u),Fu=["introduced","pre_existing"],ju=f.enum(Fu),Uu=["full","partial","none"],Zv=f.enum(Uu),Qv=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:Lu,baseline:ju,evidence_hash:f.string().regex(/^[a-f0-9]{64}$/),count:f.number().int().min(1).max(1e5)}),Hu=f.object({version:f.literal(1).default(1),actions:f.object({required:pn.default("block"),recommended:pn.default("warn"),info:pn.default("note")}).default({}),overrides:f.array(f.object({convention_id:f.string().min(1).max(64),action:pn})).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:pn,reason:f.string().min(1).max(200)})).max(32).optional()}),ek=Hu.parse({})});var Wu,Bu,Ku,Vu,zu,Do,tk,nk,qu,Yu,Ju,Xu,Zu,rk,ik,Qu,ep,tp,sk,np=b(()=>{"use strict";ee();Wu=14,Bu=14,Ku=14,Vu=1,zu=365,Do=f.number().int().min(Vu).max(zu),tk=["propose","direct"],nk="propose",qu=["propose","direct"],Yu="propose",Ju=["propose","direct"],Xu="propose",Zu=["off","propose","direct"],rk=["member","admin","owner"],ik="member",Qu="off",ep="en",tp=f.object({version:f.literal(1).default(1),at_risk_days:Do.default(Wu),stagnation_days:Do.default(Bu),agent_date_mode:f.enum(tk).default(nk),health_manual_ttl_days:Do.default(Ku),agent_event_mode:f.enum(qu).default(Yu),agent_update_mode:f.enum(Ju).default(Xu),agent_pull_mode:f.enum(Zu).default(Qu),org_wide_authoring_min_role:f.enum(rk).default(ik),planning_language:f.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(ep)}),sk=tp.parse({})});var rp,ok,ip=b(()=>{"use strict";ee();rp=f.object({version:f.literal(1).default(1),org_visibility:f.boolean().default(!1),session_span_visibility:f.boolean().default(!0)}),ok=rp.parse({})});var sp,op,ak,ck,ap=b(()=>{"use strict";ee();sp=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([])}),op=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:sp.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()}),ak=op.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()}),ck=f.object({id:f.string().uuid(),title:f.string(),summary:f.string(),tags:f.array(f.string()).default([])})});var cp=b(()=>{"use strict"});var lp=b(()=>{"use strict"});function hi(e){let t=[],n=null;return e.split(`
|
|
27
|
+
`).forEach((r,i)=>{let s=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(s===""||a>n)return;n=null}if(s===""||s.startsWith("#"))return;let c=dk.exec(r);if(!c)return;let l=c[3]??"";if(lk.has(l.trim())){n=a;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&t.push({line:i+1,value:d})}),t}var lk,dk,dp=b(()=>{"use strict";lk=new Set(["|",">","|-",">-","|+",">+"]),dk=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;o(hi,"plainScalarViolations")});function ar(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,i]=n(e),[s,a]=n(t);for(let c=0;c<Math.max(r.length,s.length);c+=1){let l=(r[c]??0)-(s[c]??0);if(l!==0)return l<0?-1:1}if(i.length===0&&a.length===0)return 0;if(i.length===0)return 1;if(a.length===0)return-1;for(let c=0;c<Math.max(i.length,a.length);c+=1){let l=i[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(ar,"compareSemver")});var Po=b(()=>{"use strict";Ze();zd();Ze();Ze();Xd();Zd();Qd();su();lu();yu();Ze();Oo();Nu();Gu();np();ip();ap();cp();lp();dp();up()});import{execFileSync as uk}from"node:child_process";import{existsSync as pk,readFileSync as fk}from"node:fs";import{join as mk}from"node:path";function cr(e){let t=[],n=e.split(`
|
|
28
|
+
`);for(let r=0;r<n.length;r+=1){let i=n[r]??"";if(!/^##(?!#)\s/.test(i))continue;let s=/(\d+\.\d+\.\d+)/.exec(i);s&&t.push({version:s[1],line:r+1,raw:i.trim(),shape:/^##\s+Unreleased\b/i.test(i)?"unreleased-labelled":hk.test(i)?"never-published":"released"})}return t}function fp(e){let t=new Map;for(let n of cr(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(i=>i.line),shapes:r.map(i=>i.shape)})).sort((n,r)=>(n.lines[0]??0)-(r.lines[0]??0))}function mp(e,t){let n=fp(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of cr(t))r.set(a.version,(r.get(a.version)??0)+1);let i=[],s=[];for(let a of n){let c=r.get(a.version)??0;(a.count>c?i:s).push({...a,countBefore:c})}return{introduced:i,preExisting:s,baseResolved:!0}}function hp(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 i=mp(r.head,e.baseRef===null?null:r.base);for(let s of i.introduced)t.push({path:r.path,version:s.version,level:"open",count:s.count,countBefore:s.countBefore,lines:s.lines,title:`${r.path}: version ${s.version} has ${s.count} headings (was ${s.countBefore})`});for(let s of i.preExisting)t.push({path:r.path,version:s.version,level:"info",count:s.count,countBefore:s.countBefore,lines:s.lines,title:`${r.path}: version ${s.version} already had ${s.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function pp(e,t){try{return uk("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function gk(e,t={}){let n=pp(["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(),i=t.baseRef??null,s=r.map(a=>{let c=mk(e,a);return{path:a,head:pk(c)?fk(c,"utf8"):null,base:i===null?null:pp(["show",`${i}:${a}`],e)}});return{isRepo:!0,baseRef:i,files:s}}function Mo(e,t={}){return hp(gk(e,t))}var hk,gi=b(()=>{"use strict";hk=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;o(cr,"parseVersionHeadings");o(fp,"findDuplicateHeadings");o(mp,"classifyIntroduced");o(hp,"computeChangelogDuplicates");o(pp,"git");o(gk,"gatherChangelogFacts");o(Mo,"checkChangelogDuplicates")});import{execFileSync as yk}from"node:child_process";import{existsSync as _k,readFileSync as gp}from"node:fs";import{dirname as yp,join as _p}from"node:path";function wp(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]??[]),i=new Set(n.documentedBase??n.documented),s=[...n.documented].sort(ar);for(let a of s){if(r.has(a)||ar(a,n.version)>=0)continue;let c=!i.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(ar))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 bp(e){let t=cr(e),n=[...new Set(t.filter(s=>s.shape!=="never-published").map(s=>s.version))],r=new Set(n),i=[...new Set(t.filter(s=>s.shape==="never-published"&&!r.has(s.version)).map(s=>s.version))];return{documented:n,neverPublished:i}}function $o(e,t){try{return yk("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function vp(e,t=null){let n=$o(["ls-files","-z","--","package.json","*/package.json"],e);if(n===null)return[];let r=[];for(let i of[...new Set(n.split("\0").filter(Boolean))].sort()){let s;try{s=JSON.parse(gp(_p(e,i),"utf8"))}catch{continue}if(s.private===!0||typeof s.name!="string"||typeof s.version!="string")continue;let a=yp(i)==="."?"":yp(i),c=_p(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=_k(c)?bp(gp(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,p=t===null?null:$o(["show",`${t}:${u}`],e),m=t===null?null:p===null?[]:bp(p).documented;r.push({dir:a,name:s.name,version:s.version,documented:l,documentedBase:m,neverPublished:d})}return r}async function bk(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 kp(e,t={}){if($o(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=vp(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??bk,i={};for(let s of n)try{i[s.name]=await r(s.name)}catch(a){return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:`${s.name}: ${a.message}`}}return{isRepo:!0,packages:n,published:i,registryReachable:!0,registryError:null}}async function Lo(e,t={}){return wp(await kp(e,t))}var Fo=b(()=>{"use strict";Po();gi();o(wp,"computeReleaseClaims");o(bp,"claimsOf");o($o,"git");o(vp,"discoverPackages");o(bk,"packument");o(kp,"gatherReleaseClaimsFacts");o(Lo,"checkReleaseClaims")});import{execFileSync as wk}from"node:child_process";import{existsSync as vk,readFileSync as kk}from"node:fs";import{join as Sk}from"node:path";function Sp(e){return e.split(`
|
|
29
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function Ep(e,t){let n=new Map;for(let s of Sp(t??""))n.set(s,(n.get(s)??0)+1);let r=[];for(let s of Sp(e)){let a=n.get(s)??0;a>0?n.set(s,a-1):r.push(s)}let i=0;for(let s of n.values())i+=s;return{added:r,removed:i,net:Math.max(0,r.length-i)}}function Ap(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=Ep(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 jo(e,t){try{return wk("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function Tp(e,t={}){let n=jo(["ls-files","-z","--",...xp],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&jo(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,s=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=Sk(e,a);return{path:a,head:vk(c)?kk(c,"utf8"):null,base:r===null?null:jo(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:s}}function Uo(e,t={}){return Ap(Tp(e,t))}var xp,Ho=b(()=>{"use strict";xp=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"];o(Sp,"contentLines");o(Ep,"proseDelta");o(Ap,"computeAgentDocProse");o(jo,"git");o(Tp,"gatherAgentDocProseFacts");o(Uo,"checkAgentDocProse")});import{execFileSync as xk}from"node:child_process";import{existsSync as Ek,readFileSync as Ak}from"node:fs";import{join as Tk}from"node:path";function Ip(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?[]:hi(n.base).map(i=>i.value));for(let i of hi(n.content)){let s=i.value.length>60?`${i.value.slice(0,57)}\u2026`:i.value,a=e.baseRef!==null&&!r.has(i.value);t.push({path:n.path,level:a?"open":"info",line:i.line,value:i.value,title:`${n.path}:${i.line}: unquoted plain scalar containing ": " \u2014 ${s}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function Rp(e,t){try{return xk("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function Cp(e,t={}){let n=Rp(["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(),i=t.baseRef??null;return{isRepo:!0,baseRef:i,files:r.map(s=>{let a=Tk(e,s);return{path:s,content:Ek(a)?Ak(a,"utf8"):null,base:i===null?null:Rp(["show",`${i}:${s}`],e)}})}}function Go(e,t={}){return Ip(Cp(e,t))}var Wo=b(()=>{"use strict";Po();o(Ip,"computeWorkflowYaml");o(Rp,"git");o(Cp,"gatherWorkflowYamlFacts");o(Go,"checkWorkflowYaml")});import{readFileSync as Rk}from"node:fs";import{join as Ik,posix as Ck}from"node:path";function Np(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],s=e[n+1];if(i==="-"&&s==="-"){for(;n<r&&e[n]!==`
|
|
30
|
+
`;)n++;continue}if(i==="/"&&s==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let a=(i==="E"||i==="e")&&s==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||a){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function ge(e){let t=[],n="",r=!1,i=!1,s=o(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){s();continue}n+=l}s();let a=t.filter(c=>c.length>0);return a.length===0||a.length>2?null:a.length===2?{schema:a[0],name:a[1]}:{schema:"public",name:a[0]}}function Fe(e){let t=[],n=0,r="";for(let i of e){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}function Nk(e){let t=/^ALTER\s+DEFAULT\s+PRIVILEGES\s+([\s\S]*?)(REVOKE|GRANT)\s+(?:GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+TABLES\s+(?:FROM|TO)\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT|WITH\s+GRANT\s+OPTION))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(/REVOKE\s+GRANT\s+OPTION\s+FOR/i.test(e))return null;let a=/\bFOR\s+ROLE\s+([\s\S]+?)(?=\s+IN\s+SCHEMA\b|$)/i.exec(n);if(a&&!Fe(a[1]).map(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||!Fe(c[1]).map(p=>ge(p)?.name??"").filter(Boolean).includes("public"))return null;let d=Fe(s).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 Fe(i)){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:[...lr]};m[2]!=="("&&lr.includes(h)&&u.push(h)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function Op(e){let t=/^REVOKE\s+(GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+([\s\S]+?)\s+FROM\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(n)return null;let a=i.trim();if(Ok.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!Fe(l[1]).map(m=>ge(m)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),m=Fe(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=Fe(s).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 Fe(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:[...lr]};!g&&lr.includes(h)&&u.push(h)}return{tables:c,roles:d,writePrivs:u}}function Ko(e){let t=new Map,n=[...e].sort((i,s)=>Oe(i.version,s.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let s=Np(i.content);for(let a of s.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=Nk(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:i.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 Fe(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=Op(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 Bo(e){let t=[];for(let[n,r]of Ko(e)){let i=[];r.anonAddressed||i.push("anon"),lr.every(s=>r.authWritesRevoked.has(s))||i.push("authenticated_writes"),i.length>0&&t.push({table:n,createdIn:r.createdIn,missing:i})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function Dp(e){let t=Bo(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Bo(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),a=i!=null&&r.missing.every(l=>i.has(l))?"info":"open",c=r.missing.map(l=>l==="anon"?"kein Tabellen-REVOKE nennt anon":"authenticated beh\xE4lt Schreibrechte (kumulierte REVOKEs decken INSERT/UPDATE/DELETE nicht)").join("; ");return{id:`table.acl:${e.dir}#${r.table}`,status:a,project:e.dir,table:r.table,createdIn:r.createdIn,missing:r.missing,title:`public.${r.table}: Default-Grants nie adressiert (${r.missing.join(", ")})`,detail:`\xDCber den gesamten Migrations-Bestand von ${e.dir}: ${c}. Supabase' ALTER DEFAULT PRIVILEGES grantet vollen CRUD an anon UND authenticated auf jede neue public-Tabelle; ohne Tabellen-REVOKE ist RLS die einzige Verteidigungslinie. Tabelle erzeugt in Migration ${r.createdIn}.`,hint:`REVOKE ALL ON public.${r.table} FROM PUBLIC, anon; REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.${r.table} FROM authenticated; \u2014 SELECT f\xFCr authenticated darf bewusst bleiben (RLS-gedecktes Lese-Muster). PUBLIC allein reicht NICHT (Default-Privileges sind direkte Rollen-Grants). Ein REVOKE in einer sp\xE4teren Migration z\xE4hlt ebenfalls; in DO-Bl\xF6cken z\xE4hlt es nicht (aufs Top-Level ziehen). Eine Tabelle, die NACH der Wurzelbehandlung entsteht (ALTER DEFAULT PRIVILEGES \u2026 IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated), kommt bereits geschlossen zur Welt und braucht kein eigenes REVOKE \u2014 diese Tabelle hier ist \xE4lter als die Wurzelbehandlung oder es gibt keine.`}})}function Pp(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function zo(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(yi)||t.endsWith(Vo))}function Pk(e,t){try{let n=Rk(e,"utf8");return n.length>t?null:n}catch{return null}}function Mk(e,t,n,r,i){let s=T(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(s===null)return i.push(`could not diff ${t} against ${r} ${yi}`),null;let a=new Set,c=[];for(let u of s.split(`
|
|
31
|
+
`).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=Ck.basename(u),m=Xt(p);if(m===null)continue;let h=T(e,["show",`${r}:${u}`]);if(h===null)return i.push(`could not read ${u} at ${r} ${Vo}`),null;l.push({name:p,version:m,content:h})}return l}function Tt(e,t={}){let n=t.maxFileBytes??Dk,r=[],i=at(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let s=t.includeBaseline!==!1,a=null;if(s)if(t.baseRef)a=t.baseRef;else{let m=Ol(e);a=m?`origin/${m}`:null,a===null&&r.push(`no default branch resolvable ${yi}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let m of i){let h=[];for(let _ of m.files){let w=Pk(Ik(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:Mk(e,m.dir,h,a,r);c.push(...Dp({dir:m.dir,files:g,baseFiles:y})),l.push({dir:m.dir,migrationCount:g.length,tableCount:Ko(g).size})}let d=l.reduce((m,h)=>m+h.migrationCount,0),u=Pp(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 lr,Ok,Dk,yi,Vo,_i=b(()=>{"use strict";se();qn();o(Np,"stripSql");o(ge,"normalizeQualifiedIdent");o(Fe,"splitTopLevel");lr=["INSERT","UPDATE","DELETE"];o(Nk,"parseDefaultAclTables");Ok=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;o(Op,"parseTableRevoke");o(Ko,"foldTableAcl");o(Bo,"evaluateTableAcl");o(Dp,"computeTableAclFindings");o(Pp,"deriveTableAclVerdict");Dk=5e6,yi="\u2014 findings reported ungraded (open)",Vo="\u2014 baseline degraded";o(zo,"isTableAclGraded");o(Pk,"safeRead");o(Mk,"baseFilesFor");o(Tt,"checkTableAclLint")});import{readFileSync as $k}from"node:fs";import{join as qo}from"node:path";function Jo(e){return e.verdict!=="no_opinion"&&e.graded}function Xo(e){let t=new Set;for(let n of e.matchAll(Lk))t.add(n[1]);return t}function Zo(e){return new Set([...e].map(t=>t.split("-")[0]))}function Up(e){return e.split(`
|
|
33
32
|
`).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
|
|
34
|
-
`)}function Qo(e){let t=Zo(e.tokens),n=[];for(let{path:r,content:
|
|
35
|
-
`).filter(Boolean)}function
|
|
36
|
-
`).filter(Boolean)),l=o(p=>c.has(p)?
|
|
37
|
-
`).filter(s=>s.length>0&&n.some(i=>CS(s,i)))}function CS(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 NS(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 Yo(e,t){try{let n=xS(e,"utf8");return n.length>t?null:n}catch{return null}}var pf,ES,TS,lf,AS,Os=b(()=>{"use strict";re();o(Jo,"isThemeClassDriftGraded");pf=["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"],ES=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,TS=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+pf.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");o(Xo,"extractTokens");o(Zo,"deriveNamespaces");o(ff,"stripCommentLines");o(Qo,"evaluateThemeClasses");o(cf,"findingKey");o(RS,"gradeAgainstBaseline");o(mf,"deriveThemeClassVerdict");lf=["*.ts","*.tsx","*.js","*.jsx"],AS=15e5;o(ea,"isScannableSource");o(df,"listTracked");o(At,"checkThemeClassDrift");o(IS,"baselineFindings");o(uf,"listTrackedAt");o(CS,"matchesSourcePattern");o(NS,"resolveBaseRef");o(Yo,"safeRead")});function ta(e){return fo[e].version}function Qe(e,t,n,r){return{detector_id:e,detector_version:ta(e),state:t,finding_count:n,...r?{reason:r}:{}}}function j(e,t,n){return{summary:Qe(e,t,0,n),findings:[]}}function bf(e){return e==="open"||e==="warn"||e==="info"}function DS(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(!ao(n))return j(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let s=[];for(let i of r){if(!bf(i.status))continue;let{level:a,baseline:c}=tn(i.status);s.push({detector_id:t,rule_id:mo,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 PS(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(!ko(n))return j(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let s of n.findings){if(!bf(s.status))continue;let{level:i,baseline:a}=tn(s.status,{excepted:s.exceptionReason!==void 0});r.push({detector_id:t,rule_id:yo(s.dimension),level:i,baseline:a,evidence:[s.id],title:s.title})}return{summary:Qe(t,"ran",r.length),findings:r}}function MS(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(!Jo(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:ho,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 LS(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(!zo(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:go,level:i,baseline:a,evidence:[s.project,s.table,...s.missing],title:s.title})}return{summary:Qe(t,"ran",r.length),findings:r}}function $S(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 FS(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 jS(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 na(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||Ds[e.level]-Ds[t.level]||gf[e.baseline]-gf[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function yf(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function US(e){let t=new Map,n=new Map;for(let s of e)if(s.baseline==="introduced"){let i=Zn(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:ta(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,Ds[s.level]<Ds[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:ta(s.detector_id),rule_id:s.rule_id,level:s.level,baseline:"pre_existing",evidence_hash:Zn(s.evidence),count:s.count});return r.sort(na)}function HS(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:DS(e.number),det_spec_drift:PS(e.spec),det_theme_class_drift:MS(e.theme),det_table_acl_lint:LS(e.acl),det_changelog_duplicates:$S(e.changelog),det_workflow_yaml:FS(e.workflow),det_release_claims:jS(e.release)},n=hf.map(l=>t[l].summary),r=hf.flatMap(l=>t[l].findings),s=US(r),i=[...s].sort((l,d)=>yf(l)-yf(d)||na(l,d)).slice(0,_f).sort(na),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:Zn(l.evidence),title:l.title}));return{findings:i,coverage:HS(n,a),engines:n,local:c,truncated:a}}function dr(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 wf(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:wf(t)}}}async function ra(e,t={}){let n={...OS,...t.engines};try{if(R(e,["rev-parse","--is-inside-work-tree"])?.trim()!=="true")return mn(dr("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(dr(`detector adapter failed: ${wf(r)}`))}}var _f,OS,hf,Ds,gf,sa=b(()=>{"use strict";re();_o();Xn();er();Ho();Wo();Is();Ns();Os();_f=64,OS={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)=>Fo(e,t),"changelog"),workflow:o((e,t)=>Go(e,t),"workflow"),release:o((e,t)=>Uo(e,t),"release")},hf=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint","det_changelog_duplicates","det_workflow_yaml","det_release_claims"];o(ta,"versionOf");o(Qe,"summary");o(j,"noFindings");o(bf,"isFindingStatus");o(DS,"adaptNumber");o(PS,"adaptSpec");o(MS,"adaptTheme");o(LS,"adaptAcl");o($S,"adaptChangelog");o(FS,"adaptWorkflow");o(jS,"adaptRelease");Ds={open:0,warn:1,info:2},gf={introduced:0,pre_existing:1};o(na,"compareWire");o(yf,"capPriority");o(US,"buildWire");o(HS,"deriveCoverage");o(mn,"adaptDetectorReports");o(dr,"unavailableDetectorReports");o(wf,"errorText");o(It,"attempt");o(ra,"runRepoHealthDetectors")});var vf,ia=b(()=>{"use strict";vf=[{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 kf(e){let t=new Set;for(let[n,r]of e.paths)for(let s of vf){if(t.has(s.flag)||!s.path.test(n)||s.onlyWhenAdded&&r!=="added")continue;if(!s.content){t.add(s.flag);continue}let i=GS(n,e);i!==null&&s.content.test(i)&&t.add(s.flag)}return[...t].sort()}function GS(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
38
|
-
`):t.readUntracked(e)}var
|
|
33
|
+
`)}function Qo(e){let t=Zo(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let s=Up(i),a=new Set;for(let c of s.matchAll(Fk)){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 Mp(e){return`${e.file} ${e.klass}`}function jk(e,t){let n=t===null?null:new Set(t.map(Mp));return e.map(r=>({...r,status:n!==null&&n.has(Mp(r))?"info":"open"}))}function Hp(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function ea(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Lp(e,t){let n=T(e,["ls-files","--",...t]);return n===null?[]:n.split(`
|
|
34
|
+
`).filter(Boolean)}function Rt(e,t={}){let n=t.maxFileBytes??Uk,r=new Set;for(let u of Lp(e,["*.css"])){let p=Yo(qo(e,u),n);if(p!==null)for(let m of Xo(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 i=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(u=>$p.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):$p,s=[];for(let u of Lp(e,i)){if(!ea(u))continue;let p=Yo(qo(e,u),n);p!==null&&s.push({path:u,content:p})}let a=Qo({tokens:r,sources:s}),c=t.includeBaseline===!1?null:Hk(e,i,n,t.baseRef),l=jk(a,c?.findings??null),d=Hp(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:Zo(r).size,findings:l,scannedFiles:s.length,graded:c!==null,baseRef:c?.mergeBase??null}}function Hk(e,t,n,r){let i=r??Wk(e);if(i===null)return null;let s=T(e,["merge-base",i,"HEAD"])?.trim();if(!s)return null;let a=T(e,["diff","--name-only","--no-renames",s]);if(a===null)return null;let c=new Set(a.split(`
|
|
35
|
+
`).filter(Boolean)),l=o(p=>c.has(p)?T(e,["show",`${s}:${p}`]):Yo(qo(e,p),n),"atBase"),d=new Set;for(let p of Fp(e,s,["*.css"])){let m=l(p);if(m!==null)for(let h of Xo(m))d.add(h)}if(d.size===0)return{findings:[],mergeBase:s};let u=[];for(let p of Fp(e,s,t)){if(!ea(p))continue;let m=l(p);m===null||m.length>n||u.push({path:p,content:m})}return{findings:Qo({tokens:d,sources:u}),mergeBase:s}}function Fp(e,t,n){let r=T(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
|
|
36
|
+
`).filter(i=>i.length>0&&n.some(s=>Gk(i,s)))}function Gk(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let s=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?s.endsWith(r.slice(1)):s===r}function Wk(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(i=>T(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function Yo(e,t){try{let n=$k(e,"utf8");return n.length>t?null:n}catch{return null}}var jp,Lk,Fk,$p,Uk,bi=b(()=>{"use strict";se();o(Jo,"isThemeClassDriftGraded");jp=["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"],Lk=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,Fk=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+jp.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");o(Xo,"extractTokens");o(Zo,"deriveNamespaces");o(Up,"stripCommentLines");o(Qo,"evaluateThemeClasses");o(Mp,"findingKey");o(jk,"gradeAgainstBaseline");o(Hp,"deriveThemeClassVerdict");$p=["*.ts","*.tsx","*.js","*.jsx"],Uk=15e5;o(ea,"isScannableSource");o(Lp,"listTracked");o(Rt,"checkThemeClassDrift");o(Hk,"baselineFindings");o(Fp,"listTrackedAt");o(Gk,"matchesSourcePattern");o(Wk,"resolveBaseRef");o(Yo,"safeRead")});function ta(e){return lo[e].version}function je(e,t,n,r){return{detector_id:e,detector_version:ta(e),state:t,finding_count:n,...r?{reason:r}:{}}}function F(e,t,n){return{summary:je(e,t,0,n),findings:[]}}function zp(e){return e==="open"||e==="warn"||e==="info"}function Bk(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(!no(n))return F(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!zp(s.status))continue;let{level:a,baseline:c}=en(s.status);i.push({detector_id:t,rule_id:uo,level:a,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:je(t,"ran",i.length),findings:i}}function Kk(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(!bo(n))return F(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!zp(i.status))continue;let{level:s,baseline:a}=en(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:mo(i.dimension),level:s,baseline:a,evidence:[i.id],title:i.title})}return{summary:je(t,"ran",r.length),findings:r}}function Vk(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(!Jo(n))return F(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:a}=en(i.status);r.push({detector_id:t,rule_id:po,level:s,baseline:a,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:je(t,"ran",r.length),findings:r}}function zk(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(!zo(n))return F(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:a}=en(i.status);r.push({detector_id:t,rule_id:fo,level:s,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:je(t,"ran",r.length),findings:r}}function qk(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(i=>({detector_id:t,rule_id:"changelog.duplicate_heading",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,i.version],title:i.title}));return{summary:je(t,"ran",r.length),findings:r}}function Yk(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(i=>({detector_id:t,rule_id:"workflow.unparsable_yaml",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,String(i.line)],title:i.title}));return{summary:je(t,"ran",r.length),findings:r}}function Jk(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(i=>({detector_id:t,rule_id:i.rule,level:i.level,baseline:"introduced",evidence:[i.package,i.version],title:i.title}));return{summary:je(t,"ran",r.length),findings:r}}function Xk(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(i=>({detector_id:t,rule_id:"agentdoc.added_prose",level:i.level,baseline:"introduced",evidence:[i.path,...i.sample,String(i.netLines)],title:i.title}));return{summary:je(t,"ran",r.length),findings:r}}function na(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||wi[e.level]-wi[t.level]||Wp[e.baseline]-Wp[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Bp(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function Zk(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let s=Zn(i.evidence),a=`${i.detector_id}|${i.rule_id}|${i.level}|${s}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:i.detector_id,detector_version:ta(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:s,count:1})}else{let s=`${i.detector_id}|${i.rule_id}`,a=n.get(s);a?(a.evidence.push(...i.evidence),a.count+=1,wi[i.level]<wi[a.level]&&(a.level=i.level)):n.set(s,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:ta(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:Zn(i.evidence),count:i.count});return r.sort(na)}function Qk(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 xe(e){let t={det_number_collisions:Bk(e.number),det_spec_drift:Kk(e.spec),det_theme_class_drift:Vk(e.theme),det_table_acl_lint:zk(e.acl),det_changelog_duplicates:qk(e.changelog),det_workflow_yaml:Yk(e.workflow),det_release_claims:Jk(e.release),det_agent_doc_prose:Xk(e.agentDoc)},n=Gp.map(l=>t[l].summary),r=Gp.flatMap(l=>t[l].findings),i=Zk(r),s=[...i].sort((l,d)=>Bp(l)-Bp(d)||na(l,d)).slice(0,Kp).sort(na),a=i.length-s.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:Zn(l.evidence),title:l.title}));return{findings:s,coverage:Qk(n,a),engines:n,local:c,truncated:a}}function It(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 ia(e){return e instanceof Error?e.message:String(e)}async function Qe(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:ia(t)}}}async function sa(e,t={}){let n={...Vp,...t.engines};try{if(!qp(e))return xe(It("not a git work tree"));let r=await Yp(e,n,t.baseRef),i=await ra(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return xe({...r,number:i})}catch(r){return xe(It(`detector adapter failed: ${ia(r)}`))}}async function oa(e,t={}){let n={...Vp,...t.engines};try{if(!qp(e)){let a=xe(It("not a git work tree"));return{commit:a,local:a}}let r=await Yp(e,n,t.baseRef),i=await ra(e,n,t.baseRef,"commit"),s=await ra(e,n,t.baseRef,"local");return{commit:xe({...r,number:i}),local:xe({...r,number:s})}}catch(r){let i=xe(It(`detector adapter failed: ${ia(r)}`));return{commit:i,local:i}}}function qp(e){return T(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function Yp(e,t,n){let r=n?{baseRef:n}:{};return{spec:await Qe(()=>t.spec(e,r)),theme:await Qe(()=>t.theme(e,r)),acl:await Qe(()=>t.acl(e,r)),changelog:await Qe(()=>t.changelog(e,r)),workflow:await Qe(()=>t.workflow(e,r)),release:await Qe(()=>t.release(e,r)),agentDoc:await Qe(()=>t.agentDoc(e,r))}}function ra(e,t,n,r,i){let s=r==="local";return Qe(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:s,includeWorktrees:i??s}))}var Kp,Vp,Gp,wi,Wp,aa=b(()=>{"use strict";se();ho();Xn();er();Fo();Ho();Wo();gi();_i();bi();Kp=64,Vp={number:o((e,t)=>ct(e,t),"number"),spec:o((e,t)=>dt(e,t),"spec"),theme:o((e,t)=>Rt(e,t),"theme"),acl:o((e,t)=>Tt(e,t),"acl"),changelog:o((e,t)=>Mo(e,t),"changelog"),workflow:o((e,t)=>Go(e,t),"workflow"),release:o((e,t)=>Lo(e,t),"release"),agentDoc:o((e,t)=>Uo(e,t),"agentDoc")},Gp=["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(ta,"versionOf");o(je,"summary");o(F,"noFindings");o(zp,"isFindingStatus");o(Bk,"adaptNumber");o(Kk,"adaptSpec");o(Vk,"adaptTheme");o(zk,"adaptAcl");o(qk,"adaptChangelog");o(Yk,"adaptWorkflow");o(Jk,"adaptRelease");o(Xk,"adaptAgentDoc");wi={open:0,warn:1,info:2},Wp={introduced:0,pre_existing:1};o(na,"compareWire");o(Bp,"capPriority");o(Zk,"buildWire");o(Qk,"deriveCoverage");o(xe,"adaptDetectorReports");o(It,"unavailableDetectorReports");o(ia,"errorText");o(Qe,"attempt");o(sa,"runRepoHealthDetectors");o(oa,"runRepoHealthDetectorScopes");o(qp,"insideWorkTree");o(Yp,"runSharedEngines");o(ra,"runNumberEngine")});var Jp,ca=b(()=>{"use strict";Jp=[{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 Xp(e){let t=new Set;for(let[n,r]of e.paths)for(let i of Jp){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let s=eS(n,e);s!==null&&i.content.test(s)&&t.add(i.flag)}return[...t].sort()}function eS(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
|
|
37
|
+
`):t.readUntracked(e)}var Zp=b(()=>{"use strict";ca();o(Xp,"scanRiskFlags");o(eS,"contentForPath")});var fn,Qp,mn,hn,la,vi,ki,Si,da,ef,dr=b(()=>{"use strict";fn="1",Qp=`
|
|
39
38
|
CREATE TABLE IF NOT EXISTS meta (
|
|
40
39
|
key TEXT PRIMARY KEY,
|
|
41
40
|
value TEXT NOT NULL
|
|
@@ -94,20 +93,32 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
94
93
|
vec BLOB NOT NULL,
|
|
95
94
|
content_hash TEXT NOT NULL
|
|
96
95
|
);
|
|
97
|
-
`,gn="schema_version",yn="last_index_commit",oa="last_indexed_at",Ps="embed_recipe_version",Ms="embed_model",Ls="embed_dim",aa="last_synced_at",Ef="last_synced_commit"});function ca(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 Tf(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let s of ca(e.name))t.add(s);for(let s of ca(e.qualifiedName))t.add(s);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function Rf(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 ca(r))t.add(s)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var la=b(()=>{"use strict";o(ca,"splitIdentifier");o(Tf,"buildSearchText");o(Rf,"toFtsMatchQuery")});import{readFileSync as Af}from"node:fs";import{posix as If}from"node:path";function Cf(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 Nf(e){return e==="added"?0:e==="modified"?1:2}function WS(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 pr,da=b(()=>{"use strict";jl();Bi();Hl();Bl();re();rd();qi();so();Xn();sa();er();Sf();ur();la();pr=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=Jl(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=Ql(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=ss(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,Tf(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=Gl(g);for(let _ of p){let w=Wl(_,y);await this.store.replaceOutgoingEdges(w.srcKeys,w.edges)}}if(this.embedder&&t.embed){let g=await this.store.getNodesByKinds([...Wi]),y=await this.store.getEmbeddingContentHashes(),_=[];for(let k of g){let x=Fl(k),S=ss(`${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(Ps,this.embedder.recipeVersion),await this.store.setMeta(Ms,this.embedder.model),await this.store.setMeta(Ls,String(this.embedder.dim))}await this.store.setMeta(gn,hn),await this.store.setMeta(oa,String(n));let h=zn(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(oa);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({...Cf(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:Ul(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({...Cf(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=Af(If.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=Zl(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=rs(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(zn(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return cd(this.repoRoot,n,t)}async checkDivergence(t={}){return Yn(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 ra(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=rs(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=nd(this.repoRoot,t),s=r?.files??new Map,i=r?.coverage??"none",a=kf({paths:n,hunks:s,readUntracked:o(m=>this.readRepoFileHead(m,td),"readUntracked")}),c=Yl(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&&ss(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(WS(x,w,k,_))}return d.sort((m,h)=>Nf(m.change)-Nf(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:zn(this.repoRoot),dirty:ed(this.repoRoot),baseSha:t.since?is(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 Af(If.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(Cf,"toHit");o(Ct,"clampLimit");o(Nf,"changeRank");o(WS,"classifyReviewSymbol")});import{createRequire as BS}from"node:module";function Df(){return Of("node:sqlite")}function _n(){if(fr)return fr;try{let{DatabaseSync:e}=Df(),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(),fr={ok:!0}}finally{t.close()}}catch(e){fr={ok:!1,reason:e instanceof Error?e.message:String(e)}}return fr}function KS(e){let{DatabaseSync:t}=Df(),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 VS(e){let t=Of("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 zS(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function $s(e){let t=zS(),n=o(s=>{let i=s==="node:sqlite"?KS(e):VS(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 Of,fr,ua=b(()=>{"use strict";Of=BS(import.meta.url);o(Df,"loadBuiltin");fr=null;o(_n,"probeBuiltinSqlite");o(KS,"openBuiltin");o(VS,"openBetter");o(zS,"backendOverride");o($s,"openSqliteDatabase")});function Fs(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 Pf,mr,Mf=b(()=>{"use strict";ua();ur();la();o(Fs,"toNodeRow");Pf=400,mr=class{static{o(this,"NodeSqliteStore")}db;backend;constructor(t){let n=$s(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(xf)}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?Fs(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Fs)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Fs)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Fs)}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=Rf(t);if(!s)return[];let i=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
96
|
+
`,mn="schema_version",hn="last_index_commit",la="last_indexed_at",vi="embed_recipe_version",ki="embed_model",Si="embed_dim",da="last_synced_at",ef="last_synced_commit"});function ua(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 tf(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of ua(e.name))t.add(i);for(let i of ua(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function nf(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let i of ua(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var pa=b(()=>{"use strict";o(ua,"splitIdentifier");o(tf,"buildSearchText");o(nf,"toFtsMatchQuery")});import{readFileSync as rf}from"node:fs";import{posix as sf}from"node:path";function of(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 af(e){return e==="added"?0:e==="modified"?1:2}function tS(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(i+=l-c+1)}let s=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||s?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var ur,fa=b(()=>{"use strict";al();Ps();ll();pl();se();xl();Ws();Qs();Xn();aa();er();Zp();dr();pa();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(mn),i=await this.store.countFiles()>0;(t.full||i&&r!==fn)&&await this.wipe();let s=yl(this.repoRoot),a=new Set(s.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:s.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 s){m++;let y=wl(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=Kr(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,tf($));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:s.length})}if(p.length>0){let g=await this.store.getNameIndex(),y=dl(g);for(let _ of p){let w=ul(_,y);await this.store.replaceOutgoingEdges(w.srcKeys,w.edges)}}if(this.embedder&&t.embed){let g=await this.store.getNodesByKinds([...Ds]),y=await this.store.getEmbeddingContentHashes(),_=[];for(let k of g){let x=ol(k),S=Kr(`${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(vi,this.embedder.recipeVersion),await this.store.setMeta(ki,this.embedder.model),await this.store.setMeta(Si,String(this.embedder.dim))}await this.store.setMeta(mn,fn),await this.store.setMeta(la,String(n));let h=zn(this.repoRoot);return h&&await this.store.setMeta(hn,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 s of n)r[s.language]=s.count;let i=await this.store.getMeta(la);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(hn),schemaVersion:await this.store.getMeta(mn),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=Ct(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),s=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&s.push({...of(c),score:a.score})}return s}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=Ct(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:cl(i,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({...of(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=Ct(n.maxDepth,3,5),s=Ct(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<i&&u.length>0;p++){let m=[];for(let h of u){let g=await this.store.neighbors(h,r,a,s);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>=s)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=rf(sf.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let a of n)i[a.kind]=a.count;let s={};for(let a of r)s[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:s,topModules:await this.store.topModulesByFanIn(Ct(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=bl(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),i=[],s=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&s++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:s,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Br(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(zn(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return Il(this.repoRoot,n,t)}async checkDivergence(t={}){return Yn(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 sa(this.repoRoot,t)}async reviewDetectorScopes(t={}){return oa(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Br(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=Sl(this.repoRoot,t),i=r?.files??new Map,s=r?.coverage??"none",a=Xp({paths:n,hunks:i,readUntracked:o(m=>this.readRepoFileHead(m,kl),"readUntracked")}),c=gl(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&&Kr(y)!==g.contentHash;_&&(p++,s==="full"&&(s="partial"));let w=n.get(m.path)??"modified",k=i.get(m.path);for(let x of h)d.push(tS(x,w,k,_))}return d.sort((m,h)=>af(m.change)-af(h.change)||(m.filePath<h.filePath?-1:m.filePath>h.filePath?1:0)||m.startLine-h.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:s,baseKind:t.since?"ref":"uncommitted",headSha:zn(this.repoRoot),dirty:vl(this.repoRoot),baseSha:t.since?Vr(this.repoRoot,t.since):null,mergeBaseSha:t.since?Hs(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 rf(sf.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(of,"toHit");o(Ct,"clampLimit");o(af,"changeRank");o(tS,"classifyReviewSymbol")});var cf=b(()=>{"use strict";se()});var nS,hM,lf=b(()=>{"use strict";se();nS=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],hM=new RegExp(nS.join("|"),"g")});import{existsSync as ma,readdirSync as rS,readFileSync as iS}from"node:fs";import{spawnSync as sS}from"node:child_process";import{dirname as oS,join as xi,posix as ha}from"node:path";function uf(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 ${ga} 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 ${ga} 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 i=new Set(r.versions),s=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!i.has(p)).sort(Oe);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=>!s.has(p)).sort(Oe),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(Oe),h=e.remote.versions.filter(g=>!s.has(g)).sort(Oe);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 pf(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function mf(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(`
|
|
97
|
+
`).filter(Boolean).slice(-1)[0]}}function df(e,t,n){let r=e(t,aS,n);return r.ok===!1?mf(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
|
|
98
|
+
`).map(i=>i.trim()).filter(Boolean)}}function hf(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 cS(e){let t=T(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=oS(t);return n===e?null:n}function lS(e,t,n){let r=ha.dirname(t),s=[{path:xi(e,r,"config.toml"),source:"worktree"}],a=cS(e);a&&s.push({path:xi(a,r,"config.toml"),source:"main_worktree"});for(let c of s)if(ma(c.path))try{let l=hf(iS(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 dS(e,t){let n=new Map,r=T(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=T(e,["rev-parse","--show-toplevel"])?.trim();for(let s of r.split(`
|
|
99
|
+
`)){if(!s.startsWith("worktree "))continue;let a=s.slice(9).trim();if(!a||a===i||!ma(a))continue;let c=xi(a,t);if(ma(c))try{for(let l of rS(c)){let d=Xt(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function ya(e,t={}){let n=t.runPsql??ff,r=t.timeoutMs??15e3,i=[],s=at(e,t.dirs);if(s.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let a=[],c=[],l=[];for(let p of s){let m=lS(e,p.dir,i),h=m.source==="missing"?null:df(n,`postgresql://postgres:postgres@127.0.0.1:${m.port}/postgres`,r),g=t.remoteDbUrl!==void 0?df(n,t.remoteDbUrl,r):null,y=uf({dir:p.dir,projectRoot:xi(e,ha.dirname(ha.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:m,ledger:h,siblingVersions:dS(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=pf(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:i}}}var ga,ff,aS,gf=b(()=>{"use strict";se();qn();ga=54322;o(uf,"evaluateLedgerProject");o(pf,"deriveLedgerVerdict");ff=o((e,t,n)=>{let r=sS("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"),aS="select version from supabase_migrations.schema_migrations order by version";o(mf,"classifyLedgerError");o(df,"readLedger");o(hf,"parseDbPort");o(cS,"mainWorktreeRoot");o(lS,"resolveConfig");o(dS,"gatherSiblingVersions");o(ya,"checkMigrationLedgerDrift")});var yf,gn=b(()=>{"use strict";sl();fa();Ws();ca();gi();Wo();Fo();Ho();Qs();cf();lf();zs();Xn();bi();er();qn();_i();gf();ho();aa();Xn();er();bi();_i();Ur();Ps();dr();Gr();yf="0.2.0"});import{execFileSync as uS}from"node:child_process";import{createHash as pS}from"node:crypto";import{mkdirSync as fS,readFileSync as mS,renameSync as hS,writeFileSync as gS}from"node:fs";import{dirname as _f,join as bf}from"node:path";function Ue(e=process.cwd()){try{let t=uS("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 Ei(e){return pS("sha256").update(e).digest("hex").slice(0,16)}function Ai(e){return bf(e,yS)}function wf(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function vf(e,t,n,r=new Date().toISOString()){try{if(!wf(n))return;let i={version:_a,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},s=Ai(e);fS(_f(s),{recursive:!0}),Vn(_f(s));let a=`${s}.${process.pid}.tmp`;gS(a,JSON.stringify(i,null,2),"utf8"),hS(a,s)}catch{}}function kf(e,t){try{let n=mS(Ai(e),"utf8"),r=JSON.parse(n);return r.version!==_a||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!wf(r.result)?null:{version:_a,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function Sf(e,t,n=new Date){let r=_S(t.cached_at,n),i=t.result.instructions??"",s={...t.result,instructions:`${r}
|
|
100
|
+
|
|
101
|
+
${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:s})}function _S(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${bS(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function bS(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i} minute${i===1?"":"s"} ago`;let s=Math.floor(i/60);if(s<24)return`${s} hour${s===1?"":"s"} ago`;let a=Math.floor(s/24);return`${a} day${a===1?"":"s"} ago`}var _a,yS,yn=b(()=>{"use strict";gn();_a=1,yS=bf(".maind","conventions-cache.json");o(Ue,"resolveRepoRoot");o(Ei,"keyFingerprint");o(Ai,"cachePath");o(wf,"hasInstructions");o(vf,"writeConventionsCache");o(kf,"readConventionsCache");o(Sf,"buildCachedInitializeResponse");o(_S,"fallbackMarker");o(bS,"relativeAge")});import{existsSync as Ni,mkdirSync as NS,readFileSync as xf,writeFileSync as va,chmodSync as Ef}from"node:fs";import{homedir as OS,hostname as DS,platform as wa,release as PS}from"node:os";import{randomUUID as MS}from"node:crypto";import{join as Nt}from"node:path";function Ot(){let e=OS(),t=process.env;if(wa()==="darwin")return Nt(e,"Library","Application Support","maind");if(wa()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:Nt(e,"AppData","Roaming");return Nt(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:Nt(e,".config");return Nt(n,"maind")}function Af(e){Ni(e)||NS(e,{recursive:!0,mode:448})}function te(){let e=Ot();Af(e);let t=Nt(e,$S);if(Ni(t)){let r=xf(t,"utf8").trim();if(jS(r))return r}let n=MS();va(t,n+`
|
|
102
|
+
`,{encoding:"utf8",mode:384});try{Ef(t,384)}catch{}return n}function jS(e){return FS.test(e)}function ka(){return Nt(Ot(),LS)}function Dt(e){let t=Ot();Af(t);let n=ka();va(n,e+`
|
|
103
|
+
`,{encoding:"utf8",mode:384});try{Ef(n,384)}catch{}}function B(){let e=ka();if(!Ni(e))return null;let t=xf(e,"utf8").trim();return t.length>0?t:null}function fr(){let e=ka();Ni(e)&&va(e,"",{encoding:"utf8",mode:384})}function Tf(){try{return`mcp-bridge-${DS()}`}catch{return"mcp-bridge"}}function Oi(e){return{os:`${wa()} ${PS()}`,ide:"mcp-bridge",ext_version:e,device_id:te()}}var $S,LS,FS,ce=b(()=>{"use strict";o(Ot,"configDir");o(Af,"ensureDir");$S="device-id",LS="api-key";o(te,"ensureDeviceId");FS=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;o(jS,"isUuid");o(ka,"apiKeyPath");o(Dt,"writeApiKey");o(B,"readApiKey");o(fr,"clearApiKey");o(Tf,"bridgeLabel");o(Oi,"clientMeta")});function mr(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:US}function _n(e){return`${mr()}/${e.replace(/^\/+/,"")}`}var US,bn=b(()=>{"use strict";US="https://fn.maind.dev/functions/v1";o(mr,"functionsOrigin");o(_n,"functionsUrl")});var H,et=b(()=>{"use strict";H="0.74.0"});import{execFileSync as zS}from"node:child_process";import{createHash as qS}from"node:crypto";function YS(e){return qS("sha256").update(e).digest("hex")}function JS(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 Sa(e){let t=JS(e);return t?YS(t):null}function z(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&XS.test(e))return e;let t;try{t=zS("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Sa(t):null}var XS,tt=b(()=>{"use strict";o(YS,"sha256Hex");o(JS,"normalizeRemoteUrl");o(Sa,"projectKeyFromRemote");XS=/^[a-f0-9]{64}$/;o(z,"computeProjectKey")});import QS from"node:path";import{fileURLToPath as ex}from"node:url";function tx(e,t=QS.sep){return e.split(t).includes("_npx")}function Ae(e){let t=e.extraArgs??[],n=o(r=>({command:"npx",args:["-y",Ff,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):tx(e.entryPath,e.sep)?n("bridge is running from the npx cache (install it globally to pin a path)"):e.nodePath?{command:e.nodePath,args:[e.entryPath,...t],env:e.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},fallbackReason:null}:n("node executable path unavailable")}function Te(){try{let e=ex(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function vn(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Lf(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Lf(n)).join(" ")}function Pi(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Ff)}function Mi(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Lf(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Ff,kn=b(()=>{"use strict";Ff="@maind-dev/mcp-bridge";o(tx,"isEphemeralEntry");o(Ae,"resolveBridgeLaunch");o(Te,"currentBridgeEntry");o(vn,"launchToShellCommand");o(Pi,"isNpxForm");o(Mi,"isLegacyHookForm");o(Lf,"shellQuote")});import*as ye from"node:path";function Uf(e){let t=e.launch??Ae({entryPath:Te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{command:t.command,args:t.args,env:{...t.env,MAIND_CLIENT_FAMILY:e.clientFamily,MAIND_MCP_URL:e.mcpUrl}}}function nx(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 $i(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:nx(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 Hf(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function Li(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:jf(e.env.XDG_CONFIG_HOME),appData:jf(e.env.APPDATA)}}function jf(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}var xa=b(()=>{"use strict";kn();o(Uf,"buildMaindServerEntry");o(nx,"claudeDesktopConfigPath");o($i,"getClientTargets");o(Hf,"filterTargetsByFamily");o(Li,"makeDefaultContext");o(jf,"nonEmpty")});import*as q from"node:fs/promises";import*as Fi from"node:path";async function ne(e){try{return await q.readFile(e,"utf8")}catch(t){if(rx(t))return null;throw t}}async function Ea(e){await q.mkdir(e,{recursive:!0})}async function Y(e,t,n){let r=Fi.dirname(e);await Ea(r);let i=Fi.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await q.writeFile(i,t,{encoding:"utf8",mode:n});try{await q.rename(i,e)}catch(s){if(ix(s))try{await q.copyFile(i,e),await q.unlink(i).catch(()=>{}),n!==void 0&&await q.chmod(e,n).catch(()=>{});return}catch(a){throw await q.unlink(i).catch(()=>{}),a}throw await q.unlink(i).catch(()=>{}),s}}async function Gf(e,t){let n=await ne(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function rx(e){return Wf(e)&&e.code==="ENOENT"}function ix(e){return!Wf(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function Wf(e){return typeof e=="object"&&e!==null&&"code"in e}var He=b(()=>{"use strict";o(ne,"readFileSafe");o(Ea,"ensureDir");o(Y,"atomicWriteFile");o(Gf,"hasLinePrefix");o(rx,"isNoEnt");o(ix,"isWindowsRenameFailure");o(Wf,"isNodeError")});import{existsSync as vx}from"node:fs";import*as Yf from"node:path";function Mt(e,t={},n=Ia){let r=t.fileExists??vx,i=t.expectedCommand??kx,s={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);Ra(a)&&(s=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=Sx(s,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: ${i(a.subcommand)}`;if(Mi(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(Pi(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=xx(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 Ca(e){return e.some(t=>t.status!=="ok")}function Hi(e){return e.some(t=>t.remedy==="run-install")}function kx(e){return vn(Ae({entryPath:Te(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function Sx(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Ra(i))continue;let s=i.hooks;if(Array.isArray(s))for(let a of s){if(!Ra(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function xx(e){for(let t of Ex(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Yf.isAbsolute(t)?t:null;return null}function Ex(e){let t=[],n="",r=!1;for(let i of e){if(i==="'"){r=!r;continue}if(!r&&/\s/.test(i)){n.length>0&&t.push(n),n="";continue}n+=i}return n.length>0&&t.push(n),t}function Ra(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ia,Ui,Sn=b(()=>{"use strict";kn();Ia=[{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."}],Ui=[{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(Mt,"inspectHookWiring");o(Ca,"hasWiringDrift");o(Hi,"needsInstallRun");o(kx,"defaultExpectedCommand");o(Sx,"findCommand");o(xx,"extractScriptPath");o(Ex,"tokenize");o(Ra,"isObject")});import*as Da from"node:path";import*as Xf from"node:readline";async function Zf(e,t){let n=Da.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let i;try{i=await ne(n)}catch(m){return{target:r,action:"merge",status:"failed",detail:`read: ${Na(m)}`}}let s,a="create";if(i===null||i.trim().length===0)s={};else{a="merge";try{let m=JSON.parse(i);if(!Oa(m))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};s=m}catch(m){return{target:r,action:"merge",status:"failed",detail:`parse: ${Na(m)}`}}}let c=Tx(s,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 Rx(e.out,`
|
|
104
|
+
Merge a ${t.event} hook into ${n}?
|
|
105
|
+
${t.consentDescription}
|
|
106
|
+
[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=s.hooks?.[t.event]??[],u={...s,hooks:{...s.hooks??{},[t.event]:[...d,l]}},p=JSON.stringify(u,null,2)+`
|
|
107
|
+
`;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: ${Na(m)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function Qf(e){let t=Da.join(e.homeDir,Jf);return Zf(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 ${Jf} into every new Claude Code session.`})}function Ax(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function Pa(e,t){let n=e.launch??Ae({entryPath:Te(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=vn(n);return Zf(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:Ax(t),skipDetail:o(i=>{let s=`${t.label} already runs maind ${t.subcommand}`;return Mi(i)?`${s}, 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}`:Pi(i)?`${s}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:s},"skipDetail"),consentDescription:t.consentDescription})}async function em(e){let t=[];for(let n of Ia)t.push(await Pa(e,n));return t}function Tx(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!Oa(i))continue;let s=i.hooks;if(Array.isArray(s))for(let a of s){if(!Oa(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function Rx(e,t){e.write(t);let n=Xf.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function Oa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Na(e){return e instanceof Error?e.message:String(e)}var Jf,Ma=b(()=>{"use strict";He();kn();Sn();Jf=".claude/maind-session-start-reminder.md";o(Zf,"mergeClaudeHook");o(Qf,"mergeSessionStartHook");o(Ax,"targetKeyFor");o(Pa,"mergeSubcommandHook");o(em,"mergeAllSubcommandHooks");o(Tx,"findExistingHookCommand");o(Rx,"promptYesNo");o(Oa,"isObject");o(Na,"errMessage")});import{existsSync as Ix,readFileSync as Cx}from"node:fs";import{join as Nx}from"node:path";function We(){return Nx(Ot(),"config.json")}function Re(){try{let e=We();if(!Ix(e))return null;let t=JSON.parse(Cx(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 xn=b(()=>{"use strict";ce();o(We,"bridgeConfigPath");o(Re,"readBridgeConfig")});function Gi(){return{nodes:[],edges:[],refs:[],imports:[]}}function it(e){return e+1}function Wi(e){return(e.text.split(`
|
|
108
|
+
`,1)[0]??"").trim().slice(0,200)}function jx(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 Ux(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=jx(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function En(e,t,n,r){for(let i of Ux(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}var Bi=b(()=>{"use strict";o(Gi,"newResult");o(it,"line1");o(Wi,"signatureOf");o(jx,"calleeName");o(Ux,"collectCallTargets");o(En,"addCallRefs")});function lm(e,t){let n=Gi();for(let r of e.namedChildren)Hx(r,t,n);return n}function dm(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function Hx(e,t,n){let r=dm(e);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??Wx(r);s&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let s=Ki(r,t,i,i,"function");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&En(n,s.nodeKey,a,cm);return}case"class_definition":Gx(r,t,n);return;case"expression_statement":{let s=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(s&&s.type==="identifier"){let a=Ki(r,t,s.text,s.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function Gx(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Ki(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let s=e.childForFieldName("superclasses");if(s){for(let c of s.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=dm(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=Ki(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let m=l.childForFieldName("body");m&&En(n,p.nodeKey,m,cm)}}function Ki(e,t,n,r,i){return{nodeKey:Lr(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:it(e.startPosition.row),endLine:it(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Wi(e),doc:null}}function Wx(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var cm,um=b(()=>{"use strict";Kn();Bi();cm="call";o(lm,"extractPython");o(dm,"unwrapDecorated");o(Hx,"handleTopLevel");o(Gx,"addClass");o(Ki,"makeNode");o(Wx,"firstDottedName")});function mm(e,t){let n=Gi();for(let r of e.namedChildren)Kx(r,t,n);return n}function Bx(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function Kx(e,t,n){let r=Bx(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:zx(i)});return}case"function_declaration":case"generator_function_declaration":{pm(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{Vx(r,t,n);return}case"interface_declaration":$a(r,t,n,"interface");return;case"type_alias_declaration":$a(r,t,n,"type_alias");return;case"enum_declaration":$a(r,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let i of r.namedChildren){if(i.type!=="variable_declarator")continue;let s=i.childForFieldName("name");if(!s||s.type!=="identifier")continue;let a=i.childForFieldName("value"),c=a?.type==="arrow_function"||a?.type==="function_expression"||a?.type==="function";pm(i,t,n,c?"function":"variable",s,a)}return}default:return}}function pm(e,t,n,r,i,s){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=Vi(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let d=s??e.childForFieldName("body")??e;r==="function"&&d&&En(n,l.nodeKey,d,fm)}function $a(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let s=Vi(e,t,i,i,r);n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}function Vx(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=Vi(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let a of e.descendantsOfType("class_heritage"))for(let c of a.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let d of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:d.text});for(let d of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:d.text})}let s=e.childForFieldName("body");if(s)for(let a of s.namedChildren){if(a.type!=="method_definition")continue;let c=a.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,d=Vi(a,t,c,l,"method");n.nodes.push(d),n.edges.push({srcKey:i.nodeKey,dstKey:d.nodeKey,kind:"contains"});let u=a.childForFieldName("body");u&&En(n,d.nodeKey,u,fm)}}function Vi(e,t,n,r,i){return{nodeKey:Lr(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:it(e.startPosition.row),endLine:it(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:Wi(e),doc:null}}function zx(e){return e.replace(/^["'`]|["'`]$/g,"")}var fm,hm=b(()=>{"use strict";Kn();Bi();fm="call_expression";o(mm,"extractTypescript");o(Bx,"unwrapExport");o(Kx,"handleTopLevel");o(pm,"addFunctionLike");o($a,"addSimpleNamed");o(Vx,"addClass");o(Vi,"makeNode");o(zx,"stripQuotes")});import{createRequire as qx}from"node:module";import{join as Yx}from"node:path";function _m(e,t){return t?Yx(t,gm[e]):qx(import.meta.url).resolve(`tree-sitter-wasms/out/${gm[e]}`)}var gm,ym,bm=b(()=>{"use strict";gm={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},ym="tree-sitter.wasm";o(_m,"grammarPath")});import{join as Jx}from"node:path";import La from"web-tree-sitter";var Xx,zi,wm=b(()=>{"use strict";Kn();Ur();um();hm();Bi();bm();Xx=["typescript","tsx","javascript","python"],zi=class{static{o(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await La.init(this.assetDir?{locateFile:o(t=>Jx(this.assetDir,t||ym),"locateFile")}:void 0),this.parser=new La,this.initialized=!0)}supports(t){return Xx.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let s=i.parse(n);if(!s)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[]};let a=s.rootNode,c=$r(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:it(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?lm(a,d):mm(a,d);return s.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 La.Language.load(_m(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as Zx}from"node:module";function km(){return vm("node:sqlite")}function An(){if(_r)return _r;try{let{DatabaseSync:e}=km(),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 Qx(e){let{DatabaseSync:t}=km(),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(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function eE(e){let t=vm("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 tE(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function qi(e){let t=tE(),n=o(i=>{let s=i==="node:sqlite"?Qx(e):eE(e);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(t==="builtin"){let i=An();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=An();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${s})`)}}var vm,_r,Fa=b(()=>{"use strict";vm=Zx(import.meta.url);o(km,"loadBuiltin");_r=null;o(An,"probeBuiltinSqlite");o(Qx,"openBuiltin");o(eE,"openBetter");o(tE,"backendOverride");o(qi,"openSqliteDatabase")});function Yi(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 Sm,br,xm=b(()=>{"use strict";Fa();dr();pa();o(Yi,"toNodeRow");Sm=400,br=class{static{o(this,"NodeSqliteStore")}db;backend;constructor(t){let n=qi(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Qp)}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 s=this.insertNodeStmt(),a=this.insertFtsStmt();for(let c of n)s.run(c.nodeKey,c.kind,c.name,c.qualifiedName,c.filePath,c.language,c.startLine,c.endLine,c.startByte,c.endByte,c.signature,c.doc),a.run(c.nodeKey,r.get(c.nodeKey)??c.name);this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)i.run(a);let s=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)s.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?Yi(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Yi)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Yi)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Yi)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let s=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,s,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=nf(t);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
98
109
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
99
110
|
WHERE nodes_fts MATCH ? AND n.kind = ?
|
|
100
111
|
ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
|
|
101
112
|
FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
|
|
102
113
|
WHERE nodes_fts MATCH ?
|
|
103
|
-
ORDER BY score LIMIT ?`,a=this.db.prepare(
|
|
114
|
+
ORDER BY score LIMIT ?`,a=this.db.prepare(s);return(n?a.all(i,n,r):a.all(i,r)).map(l=>({nodeKey:l.node_key,score:-l.score}))}async neighbors(t,n,r,i){let a=`SELECT src_key, dst_key, kind FROM edges WHERE ${n==="out"?"src_key":"dst_key"} = ?`,c=[t];return r&&r.length>0&&(a+=` AND kind IN (${r.map(()=>"?").join(",")})`,c.push(...r)),a+=" LIMIT ?",c.push(i),this.db.prepare(a).all(...c).map(d=>({srcKey:d.src_key,dstKey:d.dst_key,kind:d.kind}))}async countFiles(){return this.db.prepare("SELECT COUNT(*) AS c FROM files").get().c}async countNodes(){return this.db.prepare("SELECT COUNT(*) AS c FROM nodes").get().c}async countEdges(){return this.db.prepare("SELECT COUNT(*) AS c FROM edges").get().c}async kindDistribution(){return this.db.prepare("SELECT kind, COUNT(*) AS c FROM nodes GROUP BY kind ORDER BY c DESC").all().map(n=>({kind:n.kind,count:n.c}))}async languageDistribution(){return this.db.prepare("SELECT language, COUNT(*) AS c FROM files GROUP BY language ORDER BY c DESC").all().map(n=>({language:n.language,count:n.c}))}async topModulesByFanIn(t){return this.db.prepare(`SELECT n.file_path AS file_path, n.language AS language,
|
|
104
115
|
(SELECT COUNT(*) FROM nodes n2 WHERE n2.file_path = n.file_path) AS symbol_count,
|
|
105
116
|
(SELECT COUNT(*) FROM edges e WHERE e.src_key = n.node_key AND e.kind = 'imports') AS imports_out,
|
|
106
117
|
(SELECT COUNT(*) FROM edges e WHERE e.dst_key = n.node_key AND e.kind = 'imports') AS imports_in
|
|
107
118
|
FROM nodes n
|
|
108
119
|
WHERE n.kind = 'module'
|
|
109
120
|
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(
|
|
121
|
+
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(s=>s.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let s=0;s<n.length;s+=Sm)for(let a of n.slice(s,s+Sm))r.run(a),i.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
|
|
111
122
|
node_key, kind, name, qualified_name, file_path, language,
|
|
112
123
|
start_line, end_line, start_byte, end_byte, signature, doc
|
|
113
124
|
) 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,143 +128,143 @@ CREATE TABLE IF NOT EXISTS embeddings (
|
|
|
117
128
|
content_hash = excluded.content_hash,
|
|
118
129
|
mtime_ms = excluded.mtime_ms,
|
|
119
130
|
size = excluded.size,
|
|
120
|
-
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as qS}from"node:crypto";function bn(e){return qS("sha256").update(e,"utf8").digest("hex")}function Lf(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 $f(e){return{src_key_hash:bn(e.srcKey),dst_key_hash:bn(e.dstKey),kind:e.kind}}function Ff(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 jf=b(()=>{"use strict";o(bn,"sha256");o(Lf,"toCloudNode");o($f,"toCloudEdge");o(Ff,"toCloudEmbedding")});function pa(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Uf(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function JS(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var wn,vn,YS,fa=b(()=>{"use strict";ur();jf();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:Uf(await this.store.getMeta(aa))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Lf),n=(await this.store.getAllEdges()).map($f),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=pa(t,this.chunk),u=pa(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(aa,String(Date.now())),s&&await this.store.setMeta(Ef,s),{nodes:t.length,edges:n.length,pruned:JS(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=>Ff(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=pa(a,YS),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(Ps),n=await this.store.getMeta(Ms),r=Uf(await this.store.getMeta(Ls));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}},YS=250;o(pa,"chunkArray");o(Uf,"numOrNull");o(JS,"numOr0")});var Hf={};oe(Hf,{CodeIndexSync:()=>vn,DEFAULT_DB_RELPATH:()=>ha,SyncError:()=>wn,createCodeIndexSync:()=>ZS,createNodeCodeIndex:()=>ga,openSqliteDatabase:()=>$s,probeBuiltinSqlite:()=>_n});import{mkdirSync as XS}from"node:fs";import{posix as ma}from"node:path";function ga(e){let t=e.dbPath??ma.join(e.repoRoot,ha);XS(ma.dirname(t),{recursive:!0});let n=new mr(t),r=new es;return new pr({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function ZS(e){let t=e.dbPath??ma.join(e.repoRoot,ha),n=e.projectKey??xl(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 mr(t);return new vn(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var ha,ya=b(()=>{"use strict";ji();$l();da();Mf();fa();fa();ua();ha=".maind/code-index.sqlite";o(ga,"createNodeCodeIndex");o(ZS,"createCodeIndexSync")});import{execFileSync as Gf}from"node:child_process";import{existsSync as Wf,realpathSync as Bf}from"node:fs";import{createRequire as QS}from"node:module";import{basename as ex,dirname as tx,isAbsolute as Kf,join as nx,relative as Vf,resolve as js,sep as zf}from"node:path";function qf(){let e=_n();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return QS(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 Yf(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=Gf("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 Xf(e,t=pe(),n=process.cwd()){let r=Kf(e)?[e]:[js(t,e),js(n,e)];for(let s of r){let i=tx(s);if(!Wf(i))continue;let a;try{a=Bf(i)}catch{continue}let c=Zf(a);if(c===null)continue;let l=Vf(c,nx(a,ex(s)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(zf).join("/")}}return null}function Us(e,t=pe(),n=process.cwd()){let r=Kf(e)?[e]:[js(t,e),js(n,e)];for(let s of r){if(!Wf(s))continue;let i;try{i=Bf(s)}catch{continue}let a=Zf(i);if(a===null)continue;let c=Vf(a,i);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(zf).join("/")}}return null}function Zf(e){try{let t=Gf("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 Qf(){return ga({repoRoot:pe()})}var Jf,hr=b(()=>{"use strict";ya();o(qf,"probeNativeStore");o(Yf,"isNativeStoreUnavailable");Jf="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(Xf,"resolveRepoRootForPath");o(Us,"resolveRepoRootForDir");o(Zf,"gitToplevelOf");o(Qf,"defaultEngineFactory")});var om=b(()=>{"use strict"});var am=b(()=>{"use strict";re()});var ox,ZL,cm=b(()=>{"use strict";re();ox=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],ZL=new RegExp(ox.join("|"),"g")});import{existsSync as _a,readdirSync as ax,readFileSync as cx}from"node:fs";import{spawnSync as lx}from"node:child_process";import{dirname as dx,join as Ws,posix as ba}from"node:path";function dm(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 ${wa} 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 ${wa} 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 um(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function fm(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||!_a(a))continue;let c=Ws(a,t);if(_a(c))try{for(let l of ax(c)){let d=Zt(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function va(e,t={}){let n=t.runPsql??pm,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=fx(e,p.dir,s),h=m.source==="missing"?null:lm(n,`postgresql://postgres:postgres@127.0.0.1:${m.port}/postgres`,r),g=t.remoteDbUrl!==void 0?lm(n,t.remoteDbUrl,r):null,y=dm({dir:p.dir,projectRoot:Ws(e,ba.dirname(ba.dirname(p.dir))),fileVersions:p.files.map(_=>_.version),config:m,ledger:h,siblingVersions:mx(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=um(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 wa,pm,ux,hm=b(()=>{"use strict";re();qn();wa=54322;o(dm,"evaluateLedgerProject");o(um,"deriveLedgerVerdict");pm=o((e,t,n)=>{let r=lx("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"),ux="select version from supabase_migrations.schema_migrations order by version";o(fm,"classifyLedgerError");o(lm,"readLedger");o(mm,"parseDbPort");o(px,"mainWorktreeRoot");o(fx,"resolveConfig");o(mx,"gatherSiblingVersions");o(va,"checkMigrationLedgerDrift")});var gm,gr=b(()=>{"use strict";om();da();qi();ia();Is();Wo();Ho();so();am();cm();Zi();Xn();Os();er();qn();Ns();hm();_o();sa();Xn();er();Os();Ns();qr();Bi();ur();gm="0.1.0"});import{execFile as Sm}from"node:child_process";import{randomUUID as kx}from"node:crypto";function Ax(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return Sa.test(t)?t:kx()}function xa(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function Ix(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 Cx(e){return await new Promise(t=>{Sm("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(Nx(r))})})}function Nx(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 Ox(){return await new Promise(e=>{Sm("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 Dx(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function Px(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),s=Sa.test(r)&&r===t?"env":"random";return{current:o(()=>({id:n,source:s,aliases:[]}),"current"),tryUpgrade:o(()=>!1,"tryUpgrade"),adopt:o(i=>{Sa.test(i)&&(n=i.trim().toLowerCase())},"adopt"),activityAtMs:o(()=>null,"activityAtMs")}}var km,xm,Sx,xx,Ex,Tx,Rx,Sa,Vs,Ea=b(()=>{"use strict";Yt();km=45e3,xm=3e4,Sx=5,xx=120,Ex=3e4,Tx=15*6e4,Rx=1500,Sa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(Ax,"resolveClientSessionId");o(xa,"autoAnnounceDisabled");o(Ix,"autoWorkingPathsEnabled");Vs=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??Ox,this.gitBranchObject=t.gitBranchObject??Cx,this.log=t.log??(s=>process.stderr.write(s+`
|
|
124
|
-
`)
|
|
125
|
-
|
|
126
|
-
`)}function IE(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 CE(e,t,n){return vE.test(e)?{polarity:-1,magnitude:Tn.rework,kind:"rework"}:n&&kE.test(e)?{polarity:-1,magnitude:Tn.correction,kind:"correction"}:SE.test(e)?{polarity:1,magnitude:Tn.acceptance,kind:"acceptance"}:t!==null&&IE(t,e)?{polarity:-1,magnitude:Tn.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function NE(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 OE(e,t){for(let n of Xs(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 Qs(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(ei))continue;let d=l.name.slice(ei.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 Oa(e,t={}){let n=NE("");if(!e||!wE(e))return n;let r=t.turns??(await wr(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 Qs(x.message?.content)){if(G.type!=="tool_use"||typeof G.name!="string"||!G.name.startsWith(ei))continue;let Ut=G.name.slice(ei.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=Qs(x.message?.content),Ut=!1;for(let xc of G)xc.type==="tool_use"&&(n.tool_calls++,Ut=!0,xc.name==="AskUserQuestion"&&n.agent_questions++);c=Ut;return}if(S!=="user")return;let L=Qs(x.message?.content),U=AE(L);if(U.includes(xE)){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(EE))){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=br(U);B&&(a=B);let $=CE(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 OE(e,n),n.effort_at_end=a;for(let h of r)h.synthetic||h.model==="<unknown>"||RE(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*TE+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 ei,zm,vE,kE,SE,xE,EE,TE,Tn,qm=b(()=>{"use strict";Js();Zs();ei="mcp__maind__",zm="2026-09-09",vE=/(\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,kE=/(\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,SE=/(\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,xE="[Request interrupted by user",EE="The user doesn't want to proceed with this tool use",TE=.7,Tn={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};o(RE,"bumpModel");o(Qs,"asBlocks");o(AE,"textOf");o(IE,"isRepeat");o(CE,"classifyGenuine");o(NE,"emptyAnalysis");o(OE,"tallySubagentMaindCalls");o(Oa,"analyzeSession")});function Da(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 Pa(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 Ma(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(Da,"parseIngestResponse");o(Pa,"describeSliceVerdict");o(Ma,"ingestBody")});import{homedir as DE}from"node:os";import{join as PE}from"node:path";var ME,La=b(()=>{"use strict";ME=PE(DE(),".codex","sessions")});var Jm=b(()=>{"use strict";La()});import{isAbsolute as ja,relative as $E,resolve as Xm,sep as Ua}from"node:path";function Zm(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function ti(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Ha(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=ti(d.from);typeof d.object_id!="string"||!$a.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:ti(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=ti(c.from);typeof c.path_prefix!="string"||l===null||s.push({path_prefix:c.path_prefix,from:l,to:ti(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"||!$a.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"&&$a.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(!ja(e))return null;let n=$E(Xm(t),Xm(e));return!n||n==="."||n.startsWith("..")||ja(n)?null:Ua==="/"?n:n.split(Ua).join("/")}function FE(e,t){return t===""||e===t||e.startsWith(t+"/")}function Ga(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 Wa(e,t){for(let n of th(t))if(FE(e,n.path_prefix))return n.object_id;return null}function jE(e,t){for(let n of th(t))if(Ga(e,n.path_prefix))return n.object_id;return null}function Fa(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=>Wa(c,i)).filter(c=>c!==null);if(r&&s>0){let c=r.leases.filter(u=>Fa(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=>Fa(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=>Fa(s,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(m=>Ga(m.path_prefix,u))).sort((m,h)=>h.path_prefix.length-m.path_prefix.length);for(let m of p){let h=jE(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 Ba(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 _=Wa(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 Ka(e,t){let n=new Map;for(let i of e){let a=new Set;for(let c of i.edited_paths){if(!ja(c))continue;let l=t(UE(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 UE(e){let t=e.split(Ua).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var Qm,$a,rh=b(()=>{"use strict";Zs();o(Zm,"normalizeModelId");Qm=2e5,$a=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(ti,"msOf");o(Ha,"parseCostContext");o(eh,"toRepoRelative");o(FE,"underPrefix");o(Ga,"prefixesOverlap");o(th,"sortedAnchors");o(Wa,"anchorFor");o(jE,"bestAnchorOverlapping");o(Fa,"inWindow");o(nh,"assignTurn");o(Ba,"sliceSession");o(Ka,"dominantCheckoutRoot");o(UE,"dirOf")});import{createReadStream as HE,existsSync as GE}from"node:fs";import{createInterface as WE}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 VE(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
127
|
-
`
|
|
128
|
-
`)
|
|
129
|
-
`).trim();
|
|
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:")&&
|
|
131
|
+
indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as nE}from"node:crypto";function Tn(e){return nE("sha256").update(e,"utf8").digest("hex")}function Em(e){return{node_key_hash:Tn(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:Tn(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?Tn(e.signature):null}}function Am(e){return{src_key_hash:Tn(e.srcKey),dst_key_hash:Tn(e.dstKey),kind:e.kind}}function Tm(e,t,n){return{node_key_hash:Tn(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var Rm=b(()=>{"use strict";o(Tn,"sha256");o(Em,"toCloudNode");o(Am,"toCloudEdge");o(Tm,"toCloudEmbedding")});function ja(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Im(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function iE(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var Rn,In,rE,Ua=b(()=>{"use strict";dr();Rm();Rn=class extends Error{static{o(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},In=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(hn),lastSyncedAt:Im(await this.store.getMeta(da))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(Em),n=(await this.store.getAllEdges()).map(Am),r=await this.store.getMeta(mn)??fn,i=await this.store.getMeta(hn),s=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:i,schema_version:r,file_count:s,lang_dist:a},l=0,d=ja(t,this.chunk),u=ja(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(da,String(Date.now())),i&&await this.store.setMeta(ef,i),{nodes:t.length,edges:n.length,pruned:iE(h.nodes_deleted),embeddings:g,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),s=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(d=>Tm(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&s[d.node_key_hash]!==d.content_hash);if(a.length===0)return 0;let c=ja(a,rE),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(vi),n=await this.store.getMeta(ki),r=Im(await this.store.getMeta(Si));if(!t||!n||!r)throw new Rn("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let s=i?.error;throw new Rn(`${n} failed (HTTP ${t.status})${s?`: ${s}`:""}`,t.status,s)}return i}},rE=250;o(ja,"chunkArray");o(Im,"numOrNull");o(iE,"numOr0")});var Cm={};ie(Cm,{CodeIndexSync:()=>In,DEFAULT_DB_RELPATH:()=>Ha,SyncError:()=>Rn,createCodeIndexSync:()=>oE,createNodeCodeIndex:()=>Ga,openSqliteDatabase:()=>qi,probeBuiltinSqlite:()=>An});import{mkdirSync as sE}from"node:fs";import{posix as Ji}from"node:path";function Ga(e){let t=e.dbPath??Ji.join(e.repoRoot,Ha);sE(Ji.dirname(t),{recursive:!0}),e.dbPath===void 0&&Vn(Ji.dirname(t));let n=new br(t),r=new zi;return new ur({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function oE(e){let t=e.dbPath??Ji.join(e.repoRoot,Ha),n=e.projectKey??Jl(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 In(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}var Ha,Wa=b(()=>{"use strict";co();wm();fa();xm();Ua();Gr();Ua();Fa();Ha=".maind/code-index.sqlite";o(Ga,"createNodeCodeIndex");o(oE,"createCodeIndexSync")});import{execFileSync as Nm}from"node:child_process";import{existsSync as Om,realpathSync as Dm}from"node:fs";import{createRequire as aE}from"node:module";import{basename as cE,dirname as lE,isAbsolute as Pm,join as dE,relative as Mm,resolve as Xi,sep as $m}from"node:path";function Lm(){let e=An();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return aE(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 Fm(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=Nm("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 Um(e,t=fe(),n=process.cwd()){let r=Pm(e)?[e]:[Xi(t,e),Xi(n,e)];for(let i of r){let s=lE(i);if(!Om(s))continue;let a;try{a=Dm(s)}catch{continue}let c=Hm(a);if(c===null)continue;let l=Mm(c,dE(a,cE(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split($m).join("/")}}return null}function Zi(e,t=fe(),n=process.cwd()){let r=Pm(e)?[e]:[Xi(t,e),Xi(n,e)];for(let i of r){if(!Om(i))continue;let s;try{s=Dm(i)}catch{continue}let a=Hm(s);if(a===null)continue;let c=Mm(a,s);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split($m).join("/")}}return null}function Hm(e){try{let t=Nm("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 Gm(){return Ga({repoRoot:fe()})}var jm,wr=b(()=>{"use strict";Wa();o(Lm,"probeNativeStore");o(Fm,"isNativeStoreUnavailable");jm="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(Um,"resolveRepoRootForPath");o(Zi,"resolveRepoRootForDir");o(Hm,"gitToplevelOf");o(Gm,"defaultEngineFactory")});import{execFile as th}from"node:child_process";import{randomUUID as vE}from"node:crypto";function TE(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return Ka.test(t)?t:vE()}function Va(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function RE(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 IE(e){return await new Promise(t=>{th("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(CE(r))})})}function CE(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 NE(){return await new Promise(e=>{th("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 OE(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function DE(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=Ka.test(r)&&r===t?"env":"random";return{current:o(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:o(()=>!1,"tryUpgrade"),adopt:o(s=>{Ka.test(s)&&(n=s.trim().toLowerCase())},"adopt"),activityAtMs:o(()=>null,"activityAtMs")}}var eh,nh,kE,SE,xE,EE,AE,Ka,rs,za=b(()=>{"use strict";xn();eh=45e3,nh=3e4,kE=5,SE=120,xE=3e4,EE=15*6e4,AE=1500,Ka=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(TE,"resolveClientSessionId");o(Va,"autoAnnounceDisabled");o(RE,"autoWorkingPathsEnabled");rs=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??Re)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??NE,this.gitBranchObject=t.gitBranchObject??IE,this.log=t.log??(i=>process.stderr.write(i+`
|
|
132
|
+
`)),this.machineLabel=OE(r?.machine_label),this.enabled=this.projectKey!==null&&!Va(n,r),this.workingPathsEnabled=RE(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??DE(n,TE(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<eh||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<eh||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<kE||(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,AE).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(xE*2**(this.consecutiveFailures-1),EE);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 s=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 (${s} \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:SE,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let s=await this.gitBranch();if(s&&(r.branch=s),this.lastBranch=s,s)try{let a=await this.gitBranchObject(s);a!==null&&a!==this.lastSentObjectId&&(r.object_ids=[a],this.lastSentObjectId=a)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.sessionMeta!==null)try{let a=await this.sessionMeta();a?.model&&(r.model=a.model),a?.title&&(r.title=a.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let a=await this.deriveWorkingPaths();a&&a.length>0&&(r.working_paths=a)}catch{}}let i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let s=i;if(s.ok===!0&&typeof s.session_id=="string")try{this.identity.adopt(s.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let s={sessionId:this.sessionId,branch:this.lastBranch},a=typeof i=="object"?i:null;if(a!==null&&a.ok===!0)this.snapshot.write(i,s);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,s)}}}catch{}}};o(IE,"defaultGitBranchObject");o(CE,"normalizeObjectId");o(NE,"defaultGitBranch");o(OE,"normalizeMachineLabel");o(DE,"staticIdentity")});import{mkdirSync as rh,readdirSync as ah,readFileSync as PE,renameSync as ih,statSync as ME,unlinkSync as qa,writeFileSync as sh}from"node:fs";import{homedir as $E}from"node:os";import{join as Cn}from"node:path";function ch(){return Cn($E(),".maind","presence")}function lh(e,t){return Cn(e,t)}function dh(e){let t=e.baseDir??ch(),n=lh(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,s=e.cwd??process.cwd(),a=e.now??Date.now,c=null,l=o(d=>{if(c!==null&&c!==d)try{qa(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:i,cwd:s,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[]};rh(n,{recursive:!0,mode:448});let h=Cn(n,`${u.sessionId}.json`),g=`${h}.tmp-${r}`;sh(g,JSON.stringify(m),{mode:384}),ih(g,h),l(h),oh(n,a(),h)}catch{}},endSession(){try{c&&qa(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:i,cwd:s,branch:u.branch,peers:[],conflicts:[],announce_error:d};rh(n,{recursive:!0,mode:448});let m=Cn(n,`${u.sessionId}.json`),h=`${m}.tmp-${r}`;sh(h,JSON.stringify(p),{mode:384}),ih(h,m),l(m),oh(n,a(),m)}catch{}}}}function oh(e,t,n){try{for(let r of ah(e)){if(!r.endsWith(".json"))continue;let i=Cn(e,r);if(i!==n)try{t-ME(i).mtimeMs>LE&&qa(i)}catch{}}}catch{}}function Nn(e,t=ch()){try{let n=lh(t,e),r=[];for(let i of ah(n))if(i.endsWith(".json"))try{let s=JSON.parse(PE(Cn(n,i),"utf8")),a=FE(s);a&&r.push(a)}catch{}return r.sort((i,s)=>s.written_at.localeCompare(i.written_at)),r}catch{return[]}}function FE(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 LE,is=b(()=>{"use strict";LE=120*6e4;o(ch,"presenceSnapshotBaseDir");o(lh,"projectDir");o(dh,"createSnapshotStore");o(oh,"pruneStale");o(Nn,"readSnapshots");o(FE,"parseSnapshot")});import{execFileSync as jE}from"node:child_process";import{createHash as UE,randomUUID as HE}from"node:crypto";import{existsSync as GE,mkdirSync as WE,readdirSync as BE,readFileSync as ph,renameSync as KE,statSync as Ya,unlinkSync as fh,writeFileSync as VE}from"node:fs";import{homedir as zE}from"node:os";import{basename as qE,join as st}from"node:path";function On(e){return st(e??st(zE(),".maind","presence"),"identity")}function kr(e,t){if(e){let n=qE(e).replace(/\.jsonl$/i,"");if(vr.test(n))return n.toLowerCase()}return t&&vr.test(t)?t.toLowerCase():null}function mh(e){let t=e.nowMs??Date.now();WE(e.dir,{recursive:!0,mode:448});let n=st(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(ph(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let s=e.transcriptPath??i.transcript_path,a=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...s?{transcript_path:s}:{},...a?{model:a}:{}};VE(r,JSON.stringify(c,null,2)+`
|
|
133
|
+
`,{mode:384}),KE(r,n),QE(e.dir,t)}function hh(e,t,n,r=Date.now()){try{let i=Ya(st(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function gh(e,t){try{fh(st(e,`${t}.json`))}catch{}}function QE(e,t){try{for(let n of BE(e))if(n.endsWith(".json"))try{let r=Ya(st(e,n));t-r.mtimeMs>JE&&fh(st(e,n))}catch{}}catch{}}function e0(e){return yh(e)?.file??null}function yh(e){let t=st(e.dir,`${e.agentPid}.json`);try{if(!GE(t))return null;let n=Ya(t);if(n.mtimeMs<e.bridgeStartMs-XE)return null;let r=JSON.parse(ph(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!vr.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!t0(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function uh(e){return e.replace(/\/+$/,"")}function t0(e,t){let n=uh(e),r=uh(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function n0(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=UE("sha1").update(n).update(e,"utf8").digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=i.toString("hex");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function r0(e){if(process.platform==="win32")return null;try{let t=jE("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function i0(){try{return te()}catch{return null}}var vr,YE,JE,XE,ZE,ss,os=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,YE=8,JE=48*60*6e4,XE=6e4,ZE="9f3c72da-2f10-4b8f-9c31-ad291c0de291";o(On,"identityDirPath");o(kr,"transcriptStemOf");o(mh,"writeAgentIdentityFile");o(hh,"identityFileStale");o(gh,"deleteAgentIdentityFile");o(QE,"pruneIdentityDir");o(e0,"readAgentIdentityFile");o(yh,"readAgentIdentityEntry");o(uh,"normDir");o(t0,"sameSessionTree");o(n0,"uuidV5");o(r0,"processStartTime");ss=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??On(),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 i=(t.deviceId??i0)(),s=(t.ppidStart??r0)(this.agentPid);if(i!==null&&s!==null&&t.projectKey!==null){this.id=n0(`${i}|${this.agentPid}|${s}|${t.projectKey}`,ZE),this.source="derived";return}this.id=HE(),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>YE&&this.aliases.shift())}activityAtMs(){return yh({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 e0({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};o(i0,"defaultDeviceId")});function Ja(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Xa=b(()=>{"use strict";o(Ja,"newModeState")});import{createReadStream as s0,existsSync as o0}from"node:fs";import{stat as a0}from"node:fs/promises";import{createInterface as c0}from"node:readline";async function Za(e){if(!e||!o0(e))return null;let t;try{t=await a0(e)}catch{return null}let n=new Set,r=0,i=0,s=0;return await new Promise(a=>{let c=s0(e,{encoding:"utf-8"}),l=c0({input:c});l.on("line",d=>{let u=d.trim();if(u){s++;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"&&(i+=m.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:s,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var _h=b(()=>{"use strict";o(Za,"summariseTranscript")});var bh=b(()=>{"use strict"});function Sr(e){if(!e)return null;let t=null;for(let n of e.matchAll(d0)){let r=n[1].toLowerCase();l0.has(r)&&(t=r)}return t}var l0,d0,as=b(()=>{"use strict";l0=new Set(["low","medium","high","xhigh","max"]),d0=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;o(Sr,"detectEffortLevel")});import{createReadStream as u0,existsSync as p0,readdirSync as f0}from"node:fs";import{basename as kh,dirname as m0,join as wh}from"node:path";import{createInterface as h0}from"node:readline";function Dn(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function _0(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let i=y0[r.name];if(!i||!r.input||typeof r.input!="object")continue;let s=r.input[i];typeof s=="string"&&s.length>0&&t.push(s)}return t}function cs(e){let t=kh(e).replace(/\.jsonl$/,""),n=wh(m0(e),t,"subagents"),r;try{r=f0(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>wh(n,i))}async function vh(e,t,n,r,i){p0(e)&&await new Promise(s=>{let a=u0(e,{encoding:"utf-8"}),c=h0({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=_0(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===g0,input_tokens:Dn(w.input_tokens),output_tokens:Dn(w.output_tokens),cache_read_tokens:Dn(w.cache_read_input_tokens),cache_creation_tokens:Dn(w.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(Dn(w.cache_creation?.ephemeral_1h_input_tokens),Dn(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),i.push(S)}),c.on("close",()=>s()),c.on("error",()=>s()),a.on("error",()=>s())})}function Qa(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];i.ts>0?n=i.ts:n>0&&(i.ts=n)}}async function xr(e){let t=new Set,n=new Map,r=[],i=e?cs(e):[];if(!e)return{turns:r,subagent_files:i};let s=[];await vh(e,Ft,t,n,s),Qa(s),r.push(...s);for(let a of i){let c=[],l=kh(a).replace(/\.jsonl$/,"");await vh(a,l,t,n,c),Qa(c);for(let d of c)d.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:i}}var Ft,g0,y0,ls=b(()=>{"use strict";Ft="main",g0="<synthetic>",y0={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};o(Dn,"num");o(_0,"editedPathsOf");o(cs,"subagentFilesOf");o(vh,"readStream");o(Qa,"fillTimestamps");o(xr,"collectTurns")});import{createReadStream as Sh,existsSync as b0}from"node:fs";import{createInterface as xh}from"node:readline";function A0(e,t,n,r,i){let s=`${n?"s":"m"}:${t}`,a=e.get(s);if(!a){e.set(s,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}a.turns++,a.output_tokens+=r,i>0&&((a.first_ts===0||i<a.first_ts)&&(a.first_ts=i),i>a.last_ts&&(a.last_ts=i))}function ds(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function T0(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
134
|
+
`)}function R0(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),i=n(t);if(r.size<3||i.size<3)return!1;let[s,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of s)a.has(l)&&c++;return c/s.size>=.8}function I0(e,t,n){return w0.test(e)?{polarity:-1,magnitude:Pn.rework,kind:"rework"}:n&&v0.test(e)?{polarity:-1,magnitude:Pn.correction,kind:"correction"}:k0.test(e)?{polarity:1,magnitude:Pn.acceptance,kind:"acceptance"}:t!==null&&R0(t,e)?{polarity:-1,magnitude:Pn.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function C0(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:Eh,behaviour_measured:!0}}async function N0(e,t){for(let n of cs(e))await new Promise(r=>{let i=xh({input:Sh(n,{encoding:"utf-8"})});i.on("line",s=>{let a=s.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of ds(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(us))continue;let d=l.name.slice(us.length);d&&(t.maind_tool_calls??={},t.maind_tool_calls[d]=(t.maind_tool_calls[d]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function ec(e,t={}){let n=C0("");if(!e||!b0(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 i=[],s=new Map,a=null,c=!1,l=null;await new Promise(h=>{let g=Sh(e,{encoding:"utf-8"}),y=xh({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 ds(x.message?.content)){if(W.type!=="tool_use"||typeof W.name!="string"||!W.name.startsWith(us))continue;let qt=W.name.slice(us.length);qt&&(n.maind_tool_calls??={},n.maind_tool_calls[qt]=(n.maind_tool_calls[qt]??0)+1)}if(I)return;if(S==="assistant"){let W=ds(x.message?.content),qt=!1;for(let Jc of W)Jc.type==="tool_use"&&(n.tool_calls++,qt=!0,Jc.name==="AskUserQuestion"&&n.agent_questions++);c=qt;return}if(S!=="user")return;let $=ds(x.message?.content),U=T0($);if(U.includes(S0)){n.interrupts++,i.push({polarity:-1,magnitude:Pn.interrupt,kind:"interrupt"});return}if($.some(W=>W.type==="tool_result"&&W.is_error===!0&&typeof W.content=="string"&&W.content.includes(x0))){n.tool_denials++,i.push({polarity:-1,magnitude:Pn.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=I0(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&&i.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 N0(e,n),n.effort_at_end=a;for(let h of r)h.synthetic||h.model==="<unknown>"||A0(s,h.model,h.sidechain,h.output_tokens,h.ts);n.model_mix=[...s.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 i.forEach((h,g)=>{h.polarity>0?n.reactions_pos++:h.polarity<0&&n.reactions_neg++,u=u*E0+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&&i[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 us,Eh,w0,v0,k0,S0,x0,E0,Pn,Ah=b(()=>{"use strict";as();ls();us="mcp__maind__",Eh="2026-09-09",w0=/(\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,v0=/(\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,k0=/(\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,S0="[Request interrupted by user",x0="The user doesn't want to proceed with this tool use",E0=.7,Pn={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};o(A0,"bumpModel");o(ds,"asBlocks");o(T0,"textOf");o(R0,"isRepeat");o(I0,"classifyGenuine");o(C0,"emptyAnalysis");o(N0,"tallySubagentMaindCalls");o(ec,"analyzeSession")});function tc(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 nc(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 rc(e,t,n,r="unknown",i){let s={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};return t&&t.started_at&&(s.session_span=n?{...t,...n}:t),s}var Th=b(()=>{"use strict";o(tc,"parseIngestResponse");o(nc,"describeSliceVerdict");o(rc,"ingestBody")});import{homedir as O0}from"node:os";import{join as D0}from"node:path";var P0,ic=b(()=>{"use strict";P0=D0(O0(),".codex","sessions")});var Rh=b(()=>{"use strict";ic()});import{isAbsolute as ac,relative as $0,resolve as Ih,sep as cc}from"node:path";function Ch(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function ps(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function lc(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=ps(d.from);typeof d.object_id!="string"||!sc.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:ps(d.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=ps(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:ps(c.to)})}let s=[];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"||!sc.test(c.object_id)||typeof c.path_prefix=="string"&&s.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&sc.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:s}}function Oh(e,t){if(!ac(e))return null;let n=$0(Ih(t),Ih(e));return!n||n==="."||n.startsWith("..")||ac(n)?null:cc==="/"?n:n.split(cc).join("/")}function L0(e,t){return t===""||e===t||e.startsWith(t+"/")}function dc(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Dh(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function uc(e,t){for(let n of Dh(t))if(L0(e,n.path_prefix))return n.object_id;return null}function F0(e,t){for(let n of Dh(t))if(dc(e,n.path_prefix))return n.object_id;return null}function oc(e,t){return e>=t.from&&(t.to===null||e<t.to)}function Ph(e,t,n,r){let i=e.ts,s=r?.anchors??[],a=t.map(c=>uc(c,s)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>oc(i,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=>oc(i,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=>oc(i,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(m=>dc(m.path_prefix,u))).sort((m,h)=>h.path_prefix.length-m.path_prefix.length);for(let m of p){let h=F0(m.path_prefix,s);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 pc(e,t,n){let r=t?.anchors??[],i=o(g=>{if(!n.repoRoot)return[];let y=[];for(let _ of g.edited_paths){let w=Oh(_,n.repoRoot);w!==null&&!y.includes(w)&&y.push(w)}return y},"relOf"),s=o(g=>{for(let y of g){let _=uc(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===Ft?-1:y===Ft?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:i(k)})).sort((k,x)=>k.t.ts-x.t.ts||k.i-x.i),w=null;for(let k of _){let x=s(k.rels);if(x){w=x;break}}!w&&g!==Ft&&_.length&&(w=d(_[0].t.ts));for(let k of _){let x=s(k.rels);x&&(w=x),g===Ft&&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 $=Ph(S,k.rels,w,t),U=S.input_tokens+S.cache_read_tokens+S.cache_creation_tokens>Nh?"above_200k":"standard",j=Ch(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 fc(e,t){let n=new Map;for(let s of e){let a=new Set;for(let c of s.edited_paths){if(!ac(c))continue;let l=t(j0(c));l&&a.add(l)}for(let c of a)n.set(c,(n.get(c)??0)+1)}let r=null,i=0;for(let[s,a]of n)(a>i||a===i&&r!==null&&s.length>r.length)&&(r=s,i=a);return r}function j0(e){let t=e.split(cc).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var Nh,sc,Mh=b(()=>{"use strict";ls();o(Ch,"normalizeModelId");Nh=2e5,sc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(ps,"msOf");o(lc,"parseCostContext");o(Oh,"toRepoRelative");o(L0,"underPrefix");o(dc,"prefixesOverlap");o(Dh,"sortedAnchors");o(uc,"anchorFor");o(F0,"bestAnchorOverlapping");o(oc,"inWindow");o(Ph,"assignTurn");o(pc,"sliceSession");o(fc,"dominantCheckoutRoot");o(j0,"dirOf")});import{createReadStream as U0,existsSync as H0}from"node:fs";import{createInterface as G0}from"node:readline";function $h(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function K0(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
135
|
+
`)}function jh(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 V0(e){let t=e.message?.role;if(t==="assistant")return{holder:$h(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=$h(e.message?.content),r=K0(n);return r.includes(W0)?{holder:"human",genuine:!1}:n.some(s=>s.type==="tool_result"&&s.is_error===!0&&typeof s.content=="string"&&s.content.includes(B0))?{holder:"agent",genuine:!1}:n.some(s=>s.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function mc(e){let t=jh("");if(!e||!H0(e))return t;let n=null,r=0,i=0,s=null,a="human",c=[];return await new Promise(l=>{let d=U0(e,{encoding:"utf-8"}),u=G0({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)||s!==null&&y<s)return;let _=V0(g);if(_!==null){if(t.event_count++,_.genuine&&t.turn_count++,n===null&&(n=y),r=y,s!==null){let w=y-s;a==="agent"?i+=w:w>=Lh*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(w/1e3),c.length<Fh&&c.push({offset_seconds:Math.round((s-n)/1e3),duration_seconds:Math.round(w/1e3)}))}s=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(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var W0,B0,Lh,Fh,Uh=b(()=>{"use strict";W0="[Request interrupted by user",B0="The user doesn't want to proceed with this tool use",Lh=60,Fh=200;o($h,"asBlocks");o(K0,"textOf");o(jh,"emptySpan");o(V0,"classify");o(mc,"analyzeSpan")});import{createReadStream as z0,existsSync as q0}from"node:fs";import{createInterface as Y0}from"node:readline";function X0(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function fs(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Z0(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(`
|
|
136
|
+
`)}return""}async function hc(e,t={}){if(!e||!q0(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Ja(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,s=t.initialModes?{...t.initialModes}:Ja(),a=t.start??0;return await new Promise(c=>{let l=z0(e,{encoding:"utf-8",start:t.start??0}),d=Y0({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=J0[h.attachment.type];w&&(s[X0(w.mode)]=w.active,n.push({kind:"mode",session_id:g,ts:y,mode:w.mode,active:w.active}));return}if(_==="user"){let w=Z0(h.message?.content),k=Sr(w);k&&(i=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:fs(w?.input_tokens),output_tokens:I?0:fs(w?.output_tokens),cache_read_input_tokens:I?0:fs(w?.cache_read_input_tokens),cache_creation_input_tokens:I?0:fs(w?.cache_creation_input_tokens),effort:i,isSidechain:h.isSidechain===!0,...s.ultracode?{ultracode:!0}:{},...s.planMode?{planMode:!0}:{},...s.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...$})}});let u=o(()=>({events:n,bytesRead:a,effortAtEnd:i,modesAtEnd:{...s},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var J0,Hh=b(()=>{"use strict";as();Xa();J0={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(X0,"modeFlagKey");o(fs,"num");o(Z0,"extractUserText");o(hc,"streamTranscript")});var Gh=b(()=>{"use strict"});import{homedir as Q0}from"node:os";import{join as eA}from"node:path";function yc(e){return e.replace(/[/.]/g,"-")}var tA,gc,Wh=b(()=>{"use strict";tA=Q0(),gc=eA(tA,".claude","projects");o(yc,"projectPathFromCwd")});var Mn=b(()=>{"use strict";Xa();_h();bh();Ah();Th();ls();ic();Rh();Mh();Uh();Hh();as();Gh();Wh()});function _c(e,t){let n=e.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0),r=t.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0);for(let i=0;i<3;i++)if(n[i]!==r[i])return n[i]-r[i];return 0}function uA(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(i=>i[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 jt(e,t){let n=`npm i -g ${Er}@${e}`;return t?`nvm use ${t} && ${n}`:n}function zh(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(d=>d.bridgeVersion).filter(d=>d!==null)],r=e.latestVersion??n.sort(_c).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 i=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:jt(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:jt(r,m.node)})}if(new Set(i.map(m=>m.bridgeVersion)).size>1)for(let m of i.filter(h=>_c(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:jt(r,m.node)})}let s=!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=uA(d);if(u===null)continue;if(s=!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:`${jt(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 ${jt(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:jt(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(s||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(_c(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?jt(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||!Vh.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"}):dA.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&Vh.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=Mt(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 qh(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}`]:[]]),i=e.filter(a=>a.level==="error").length,s=e.filter(a=>a.level==="warn").length;return r.push("",i+s===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${i} error(s), ${s} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
|
|
137
|
+
`)+`
|
|
138
|
+
`}var Er,dA,Vh,Yh=b(()=>{"use strict";Sn();Er="@maind-dev/mcp-bridge",dA=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,Vh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(_c,"compareVersions");o(uA,"maindEntry");o(jt,"installFix");o(zh,"diagnose");o(qh,"renderFindings")});var eg={};ie(eg,{realProbe:()=>Qh,resolveNvmAlias:()=>Zh,runDoctor:()=>kA});import{execFileSync as pA}from"node:child_process";import{existsSync as vc,readFileSync as fA,readdirSync as bc,realpathSync as mA}from"node:fs";import{homedir as Ar,platform as hs}from"node:os";import{delimiter as hA,dirname as Jh,join as re}from"node:path";function Ut(e){try{return vc(e)?fA(e,"utf8"):null}catch{return null}}function gA(){try{let e=pA(hs()==="win32"?"npm.cmd":"npm",["view",Xh,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function wc(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:re(Ar(),".nvm")}function yA(){let e=re(wc(),"versions","node"),t=[];try{t=bc(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=Ut(re(e,n,"lib","node_modules","@maind-dev","mcp-bridge","package.json")),i=null;try{i=r?JSON.parse(r).version??null:null}catch{i=null}return{node:n,bridgeVersion:i}})}function Zh(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 i=[...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 i.at(-1)??null;let s=r.startsWith("v")?r:`v${r}`;if(t.includes(s))return s;let a=s.endsWith(".")?s:`${s}.`;return i.filter(c=>c.startsWith(a)).at(-1)??null}function _A(e){let t=Ut(re(wc(),"alias","default"));return t===null?null:Zh(t,e.map(n=>n.node),n=>{let r=Ut(re(wc(),"alias",n));return r===null?null:r})}function bA(){let e=hs()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(hA))if(t)for(let n of e){let r=re(t,n);if(vc(r)){let i=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:i?i[1]:null,path:r}}}return null}function wA(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:hs()==="win32"?re(process.env.LOCALAPPDATA??re(Ar(),"AppData","Local"),"npm-cache"):re(Ar(),".npm"),t=re(e,"_npx"),n=[],r=[];try{r=bc(t)}catch{return[]}for(let i of r)try{bc(re(t,i,"node_modules")).some(s=>s.startsWith(".better-sqlite3-"))&&n.push(re(t,i))}catch{}return n}function vA(e){let t;try{t=Jh(mA(e))}catch{return null}for(let n=0;n<6;n++){let r=Ut(re(t,"package.json"));if(r!==null)try{let s=JSON.parse(r);if(s.name===Xh)return s.version??null}catch{}let i=Jh(t);if(i===t)break;t=i}return null}function Qh(e=process.cwd()){let t=yA(),n=Ut(re(Ot(),"device-id")),r=Li({projectRoot:e,homeDir:Ar(),platform:hs(),env:process.env}),i=null;try{i=B()}catch{i=null}let s=(process.env.MAIND_API_KEY??"").trim();return{runningVersion:H,latestVersion:gA(),nodeTrees:t,nvmDefault:_A(t),pathWinner:bA(),clientConfigs:$i(r).map(a=>({label:a.label,path:a.path,kind:a.kind,raw:Ut(a.path)})),npxStaleDirs:wA(),claudeSettings:Ut(re(Ar(),".claude","settings.json")),fileExists:o(a=>vc(a),"fileExists"),installVersionOf:vA,deviceId:n===null?null:n.trim(),apiKey:i,envApiKey:s.length>0?s:null}}async function kA(e){let t=zh(Qh());return e.includes("--json")?process.stdout.write(JSON.stringify({version:H,findings:t},null,2)+`
|
|
139
|
+
`):process.stdout.write(qh(t)),t.some(n=>n.level==="error")?1:0}var Xh,tg=b(()=>{"use strict";ce();xa();et();Yh();Xh="@maind-dev/mcp-bridge";o(Ut,"readOrNull");o(gA,"latestVersion");o(wc,"nvmDir");o(yA,"nodeTrees");o(Zh,"resolveNvmAlias");o(_A,"nvmDefault");o(bA,"pathWinner");o(wA,"npxStaleDirs");o(vA,"installVersionOf");o(Qh,"realProbe");o(kA,"runDoctor")});async function ng(e){return Ht("get_session_briefing",{tools:["claude-code"]},e)}async function Ht(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??kc,i=new AbortController,s=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let a={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n.apiKey}`,"x-maind-client-family":n.clientFamily??"claude-code","x-maind-client-version":n.bridgeVersion,"x-maind-bridge-version":n.bridgeVersion};n.deviceId&&(a["x-maind-device-id"]=n.deviceId),n.projectKey&&(a["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:a,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:SA,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:i.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:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!u.ok)return null;let m=(u.headers.get("content-type")??"").startsWith("text/event-stream")?await xA(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(s)}}async function xA(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s="",a=o(()=>{if(i.length===0)return;let c=i.join(`
|
|
140
|
+
`).trim();i=[],c.length>0&&(s=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(`
|
|
141
|
+
`))!==-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/,""))}}return a(),s}var kc,SA,Tr=b(()=>{"use strict";kc="https://mcp.maind.dev/mcp",SA="2025-06-18";o(ng,"fetchSessionBriefing");o(Ht,"fetchToolText");o(xA,"readSseMessage")});function EA(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":te()}}async function rg(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:EA(t),body:JSON.stringify({metrics:n})});if(!r.ok){let s=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:s.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 gs,Sc=b(()=>{"use strict";ce();bn();gs=process.env.MAIND_ENDPOINT??_n("mcp-client-metrics-ingest");o(EA,"ingestHeaders");o(rg,"postMetrics")});function ig(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function og(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,s=Array.isArray(i.active_claims)?i.active_claims:[],a=[];for(let c of s){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 i.session_id_short=="string"?i.session_id_short:"?",is_own_user:i.is_own_user===!0,branch:typeof i.branch=="string"?i.branch:null,focus:typeof i.focus=="string"?i.focus:null,machine_label:typeof i.machine_label=="string"?i.machine_label:null,last_seen_seconds:typeof i.last_seen_seconds=="number"?i.last_seen_seconds:0,claims:a,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function $n(e,t){if(t.hostPids.length>0){let r=e.find(i=>t.hostPids.includes(i.own_ppid));if(r)return{snap:r,via:"ppid"}}let n=e.find(r=>r.cwd===t.cwd);return n?{snap:n,via:"cwd"}:null}function Rr(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function ag(e,t,n){let r=n.maxAgeMs??sg,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let s=i/1e3,a=og(e,s),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)ig(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+s)} 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(ig(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+s)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${Rr(s)} ago, advisory \u2014 never a lock):
|
|
131
142
|
`+c.map(l=>` \u2022 ${l}`).join(`
|
|
132
143
|
`)+`
|
|
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
|
-
`),
|
|
136
|
-
\u2192 ${
|
|
137
|
-
${
|
|
144
|
+
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 cg(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 lg(e,t,n,r=sg,i=null){if(!e)return null;let s=n-Date.parse(e.written_at);if(!Number.isFinite(s)||s<0||s>r)return null;let a=s/1e3,c=og(e,a),l=i!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${i}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let 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}
|
|
145
|
+
${h}`:h}var sg,xc=b(()=>{"use strict";o(ig,"prefixConflict");sg=10*6e4;o(og,"parsePeers");o($n,"selectOwnSnapshot");o(Rr,"ageDisplay");o(ag,"adviseOnPath");o(cg,"claimedIdentity");o(lg,"sessionStartSummary")});async function G(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=o(s=>{n||(n=!0,clearTimeout(i),t(s))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",s=>e.push(s)),process.stdin.on("end",()=>{try{let s=Buffer.concat(e).toString("utf-8").trim();r(s?JSON.parse(s):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function Ln(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function Ie(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var Ce=b(()=>{"use strict";o(G,"readHookInput");o(Ln,"transcriptPathOf");o(Ie,"toolFilePathOf")});function Fn(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function ot(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function dg(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}var jn=b(()=>{"use strict";o(Fn,"denyPayload");o(ot,"advisoryPayload");o(dg,"postAdvisoryPayload")});import{realpathSync as AA}from"node:fs";import{basename as ug,dirname as pg,join as TA}from"node:path";function Gt(e){let t=pg(e),n=[ug(e)];for(;;)try{let r=AA(t);return TA(r,...n.reverse())}catch{let r=pg(t);if(r===t)return e;n.push(ug(t)),t=r}}var ys=b(()=>{"use strict";o(Gt,"realpathOfUnwritten")});import{mkdir as RA,readFile as IA,writeFile as CA,rename as NA}from"node:fs/promises";import{existsSync as mg}from"node:fs";import{homedir as OA}from"node:os";import{join as hg}from"node:path";function fg(){return{config:null,sessions:{},pending_metrics:[]}}async function X(){if(!mg(_s))return fg();try{let e=await IA(_s,"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)}
|
|
146
|
+
`),fg()}}async function Ne(e){mg(Wt)||await RA(Wt,{recursive:!0,mode:448});let t=`${_s}.tmp`;await CA(t,JSON.stringify(e,null,2),{mode:384}),await NA(t,_s)}function Ec(e){return e.thresholds??e.config?.thresholds??DA}var Wt,_s,DA,Bt=b(()=>{"use strict";Wt=hg(OA(),".maind"),_s=hg(Wt,"state.json"),DA={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};o(fg,"emptyState");o(X,"loadState");o(Ne,"saveState");o(Ec,"resolveThresholds")});import{existsSync as PA,realpathSync as MA,statSync as $A}from"node:fs";import{dirname as gg,isAbsolute as LA,join as FA}from"node:path";function HA(e,t){let n=e.filter(i=>yg.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let s=i.hint?`
|
|
147
|
+
\u2192 ${i.hint}`:"";return` \u2022 ${i.title}
|
|
148
|
+
${i.detail}${s}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
|
|
138
149
|
|
|
139
150
|
`+r.join(`
|
|
140
151
|
|
|
141
152
|
`)+`
|
|
142
153
|
|
|
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
|
|
154
|
+
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 GA(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function WA(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},s=i[t]??{};s[n]=new Date(r).toISOString(),i[t]=s,e.repo_health_seen=i}function Ac(e){let t=gg(e);for(;;){try{if($A(t).isDirectory())return t}catch{}let n=gg(t);if(n===t)return t;t=n}}async function BA(e,t,n){let r=await n.load();if(GA(r,e,t))return null;WA(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let s=i.filter(c=>yg.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:jA,metric_value:1},{session_id:e,metric_key:UA,metric_value:s}),await n.save(a),HA(i,t)}async function _g(){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=Ie(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=LA(r)?r:FA(i,r),a=PA(s)?MA(s):Gt(s),c=Ue(Ac(a)),l=await BA(n,c,{load:X,save:Ne,check:o(async d=>(await Yn(d,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(ot(l)),0}catch{return 0}}var yg,jA,UA,Tc=b(()=>{"use strict";gn();yn();jn();Ce();ys();Bt();yg=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],jA="repo_health_hook_runs",UA="repo_health_hook_findings";o(HA,"formatRepoHealth");o(GA,"alreadySeen");o(WA,"markSeen");o(Ac,"nearestExistingDir");o(BA,"repoHealthForEdit");o(_g,"runOnRepoHealth")});import{existsSync as KA,readFileSync as VA,realpathSync as zA}from"node:fs";import{isAbsolute as wg,join as vg,posix as qA,relative as YA,sep as JA}from"node:path";function bg(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function tT(e,t){return{contracts:t.filter(r=>bg(r.spec)===e||bg(r.impl)===e).map(r=>r.id),theme:QA.test(e),acl:eT.test(e)}}function nT(e){return e.contracts.length===0&&!e.theme&&!e.acl}function rT(e,t,n,r,i=Date.now()){let s=e.write_health_seen??{},a=s[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(i).toISOString(),keys:[...c]},s[t]=a,e.write_health_seen=s}return l}function iT(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
155
|
|
|
145
156
|
`+e.map(n=>` \u2022 ${n.line}`).join(`
|
|
146
157
|
`)+`
|
|
147
158
|
|
|
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
|
|
159
|
+
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 sT(e,t){let n=YA(e,t);return!n||n.startsWith("..")||wg(n)?null:n.split(JA).join(qA.sep)}function oT(e){try{let t=VA(vg(e,Xr),"utf8"),{manifest:n}=ti(t);return n?.contracts??[]}catch{return[]}}async function kg(){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=Ie(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=wg(r)?r:vg(i,r),a=KA(s)?zA(s):Gt(s),c=Ue(Ac(a)),l=sT(c,a);if(l===null)return 0;let d=tT(l,oT(c));if(nT(d))return 0;let u=[];if(d.contracts.length>0)try{let g=await dt(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=Rt(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=Tt(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=rT(p,n,c,u);p.pending_metrics.push({session_id:n,metric_key:XA,metric_value:1},{session_id:n,metric_key:ZA,metric_value:m.length}),await Ne(p);let h=iT(m,l);return h!==null&&process.stdout.write(dg(h)),0}catch{return 0}}var XA,ZA,QA,eT,Sg=b(()=>{"use strict";gn();yn();jn();Ce();Tc();ys();Bt();XA="write_health_hook_runs",ZA="write_health_hook_findings",QA=/\.(tsx?|jsx?|css)$/,eT=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;o(bg,"declPath");o(tT,"routesForPath");o(nT,"routesAreEmpty");o(rT,"takeUnreported");o(iT,"formatWriteHealth");o(sT,"repoRelative");o(oT,"readContracts");o(kg,"runOnWriteHealth")});var Mg={};ie(Mg,{agentHostPidCandidates:()=>Be,closeTrackedSession:()=>Cg,effectiveConfig:()=>Kt,grandparentPid:()=>Og,recordGuardSignals:()=>Ig,runFlush:()=>kT,runHookStatus:()=>ST,runOnFileEdit:()=>bT,runOnFileWrite:()=>_T,runOnRepoHealth:()=>_g,runOnSessionStart:()=>fT,runOnToolUse:()=>gT,runOnWriteHealth:()=>kg,runSessionEndMetrics:()=>Ic,runSyncConfig:()=>ET,writeIdentitySideChannel:()=>Rc});import{execFileSync as Eg}from"node:child_process";import{existsSync as vs,readFileSync as Ag,realpathSync as aT}from"node:fs";import{writeFile as cT}from"node:fs/promises";import{homedir as Tg}from"node:os";import{isAbsolute as ws,join as Ir,relative as Rg}from"node:path";function Ig(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=n.includes("search_lessons")||n.includes("get_session_briefing")||n.includes("get_lesson")||n.includes("get_conventions")||n.includes("activate_skill")||n.includes("suggest_skills")||n.includes("codebase_change_briefing"),s=n.includes("review_changes");if(!i&&!s)return;let a=e.guard_signals??{},c=a[t]??{},l=new Date(r).toISOString();i&&(c.consulted_at=l),s&&(c.reviewed_at=l),a[t]=c,e.guard_signals=a}function Cg(e,t,n=Date.now()){pT(e,n);let r=e.sessions[t];if(!r)return!1;let i=n-new Date(r.started_at).getTime();return e.pending_metrics.push({session_id:t,metric_key:"session_duration_ms",metric_value:Math.max(0,i)},{session_id:t,metric_key:"tool_call_count",metric_value:r.tool_call_count},{session_id:t,metric_key:"lessons_consulted",metric_value:r.lessons_consulted}),delete e.sessions[t],!0}function pT(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let i=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0);t-i>bs&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s)||0));t-i>bs&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s.at)||0));t-i>bs&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let i=Date.parse(r.started_at);!Number.isNaN(i)&&t-i>bs&&delete e.sessions[n]}}function Kt(e){if(e.config)return e.config;let t=B();return t===null?null:{api_key:t,endpoint:gs}}function Ng(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 fT(){let e=await X();if(Kt(e)===null)return 0;let t=await G(),n=Pg(t);if(n===null)return 0;Ng(e,n),await Ne(e);try{Rc(t,n)}catch{}try{let r=z();if(r!==null){let i=Nn(r),s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=$n(i,{hostPids:Be(),cwd:s}),c=cg(a?.snap??null,kr(Ln(t)||null,n)),l=lg(a?.snap??i[0]??null,c.id,Date.now(),void 0,c.announceError);l!==null&&process.stdout.write(l+`
|
|
160
|
+
`)}}catch{}try{let r=Mt(mT());if(Ca(r)&&Hi(r)){let i=r.filter(s=>s.remedy==="run-install").map(s=>s.subcommand).join(", ");process.stderr.write(`[maind] New bridge capability not yet wired (${i}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
|
|
161
|
+
`)}}catch{}return 0}function mT(){try{let e=Ir(Tg(),".claude","settings.json");return vs(e)?Ag(e,"utf8"):null}catch{return null}}function Rc(e,t,n,r=On()){let i=n??Be();if(i.length===0)return;let s=kr(Ln(e)||null,t);if(s===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=Ln(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of i)mh({dir:r,agentPid:d,sessionId:t,transcriptStem:s,cwd:a,transcriptPath:c,model:l})}function Og(){try{if(process.platform==="win32")return null;let e=Eg("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 Be(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=Og();return n!==null&&n>1&&n!==t&&e.push(n),e}async function gT(){let e=await X();if(Kt(e)===null)return 0;let t=await G(),n=Pg(t)??"unknown",r=Ng(e,n);r.tool_call_count+=1;try{let a=Be().filter(c=>hh(On(),c,hT));n!=="unknown"&&a.length>0&&Rc(t,n,a)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),Ig(e,n,i);let s=t.transcript_path;if(typeof s=="string"&&s&&!r.transcript_path&&(r.transcript_path=s),r.transcript_path){let a=await Za(r.transcript_path);a&&(r.token_count=a.total_tokens,await vT(e,r))}return await Ne(e),0}function yT(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
|
|
151
162
|
`);return`${t.prefix}${e.number} is already taken:
|
|
152
163
|
${n}
|
|
153
164
|
|
|
154
165
|
Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
|
|
155
166
|
|
|
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
|
|
157
|
-
`)}
|
|
167
|
+
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 _T(){try{let e=await G();if((e.tool_name??"")!=="Write")return 0;let t=Ie(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=ws(t)?t:Ir(n,t);if(vs(r))return 0;let i=Ue(n),s=Rg(i,Gt(r));if(s.length===0||s.startsWith("..")||ws(s))return 0;let a=await lt(i,s);return!a.taken||a.namespace===null||process.stdout.write(Fn(yT(a,a.namespace))),0}catch{return 0}}async function bT(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=Ie(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=ws(n)?n:Ir(r,n),s=z();if(s===null)return 0;let a=Nn(s);if(a.length===0)return 0;let c=$n(a,{hostPids:Be(),cwd:r});if(c===null)return 0;let l=Ue(r),d=vs(i)?aT(i):Gt(i),u=Rg(l,d).replace(/\\/g,"/");if(u.length===0||u.startsWith("..")||ws(u))return 0;let p=ag(c.snap,u,{via:c.via,currentBranch:c.via==="cwd"?wT(r):null,nowMs:Date.now()});return p===null||process.stdout.write(ot(p)),0}catch{return 0}}function wT(e){try{let n=Eg("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 vT(e,t){let n=Ec(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,s="ok";if(i>=n.handoff_at_pct/100?s="handoff_recommended":i>=n.warn_at_pct/100&&(s="warn"),t.last_advisory_status===s||(t.last_advisory_status=s,s==="ok"))return;let a=Math.round(i*100),c={session_id:t.session_id,status:s,tokens:r,ratio:Number(i.toFixed(3)),pct:a,thresholds:n,suggested_next:s==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await cT(Ir(Wt,`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)}
|
|
168
|
+
`)}s==="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
169
|
`):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
|
|
170
|
+
`)}async function Ic(e){try{let t=await X(),n=Kt(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Cg(t,r),await Ne(t)),await Dg(n,dT)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
|
|
171
|
+
`)}}async function kT(){let e=await X(),t=Kt(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 Dg(t,uT);return process.stdout.write(JSON.stringify(n,null,2)+`
|
|
172
|
+
`),n.ok?0:1}async function Dg(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),i=rg(e.endpoint,e.api_key,r),s=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([i,s]);if(a.ok){let c=await X();return c.pending_metrics=c.pending_metrics.slice(r.length),await Ne(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 ST(){let e=await X(),t=Kt(e),n=xT(),r=Ca(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:Ec(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!r,hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...Hi(n.findings)?{remedy:xg}:{}}},null,2)+`
|
|
162
173
|
`),r){process.stderr.write(`
|
|
163
174
|
[maind] Claude Code hook wiring is incomplete:
|
|
164
|
-
`);for(let
|
|
165
|
-
`);
|
|
166
|
-
`)}return 0}function
|
|
175
|
+
`);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
|
|
176
|
+
`);Hi(n.findings)&&process.stderr.write(` ${xg}
|
|
177
|
+
`)}return 0}function xT(){let e=Ir(Tg(),".claude","settings.json"),t=null;try{vs(e)&&(t=Ag(e,"utf8"))}catch{}return{settingsPath:e,findings:Mt(t)}}async function ET(){let e=await X(),t=Kt(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??lT,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
178
|
`),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
|
|
168
179
|
`);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
|
|
169
|
-
`),1}let
|
|
170
|
-
`),1}let i
|
|
171
|
-
`),1):(e.thresholds={warn_at_pct:
|
|
172
|
-
`),0)}function
|
|
173
|
-
`)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([
|
|
174
|
-
`)}return await
|
|
175
|
-
`,384)}var
|
|
176
|
-
`),1;let
|
|
177
|
-
`);let a=
|
|
180
|
+
`),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
|
|
181
|
+
`),1}let s=i;return typeof s.warn_at_pct!="number"||typeof s.handoff_at_pct!="number"||typeof s.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
|
|
182
|
+
`),1):(e.thresholds={warn_at_pct:s.warn_at_pct,handoff_at_pct:s.handoff_at_pct,model_token_limit:s.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await Ne(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
|
|
183
|
+
`),0)}function Pg(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var lT,dT,uT,bs,hT,xg,Cc=b(()=>{"use strict";Mn();gn();yn();ce();Sn();is();tt();Sc();xc();os();Ce();jn();ys();Bt();bn();Tc();Sg();lT=process.env.MAIND_THRESHOLDS_ENDPOINT??_n("get-context-thresholds"),dT=1500,uT=1e4,bs=7*24*60*60*1e3;o(Ig,"recordGuardSignals");o(Cg,"closeTrackedSession");o(pT,"gcState");o(Kt,"effectiveConfig");o(Ng,"getOrCreateSession");o(fT,"runOnSessionStart");o(mT,"readSettingsRaw");o(Rc,"writeIdentitySideChannel");hT=6e4;o(Og,"grandparentPid");o(Be,"agentHostPidCandidates");o(gT,"runOnToolUse");o(yT,"denyReason");o(_T,"runOnFileWrite");o(bT,"runOnFileEdit");o(wT,"currentGitBranch");o(vT,"maybeEmitAdvisory");o(Ic,"runSessionEndMetrics");o(kT,"runFlush");o(Dg,"flushPending");o(ST,"runHookStatus");xg="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(xT,"readHookWiring");o(ET,"runSyncConfig");o(Pg,"sessionIdOf")});function $g(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Lg=b(()=>{"use strict";o($g,"resolveConnection")});function jg(e,t,n,r=Date.now()){let i=t===null?null:lc(t),s=pc(e,i,{repoRoot:n,nowMs:r});return s.length===0?null:{slices:s,context_ok:i!==null}}var Fg,Nc=b(()=>{"use strict";Mn();Fg=2e3;o(jg,"buildCostPayload")});function Hg(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!Ug.test(n))return null;let r=n.toLowerCase();return t!==null&&Ug.test(t)&&r!==t.toLowerCase()?null:r}var Ug,Gg=b(()=>{"use strict";Ug=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(Hg,"snapshotSessionId")});async function Wg(e){let t=e.now??Date.now,n=e.fetchContext(e.projectKey),{turns:r}=await xr(e.transcriptPath),i=e.resolveRoot?fc(r,e.resolveRoot):null,s=i&&e.projectKeyOf?e.projectKeyOf(i):null,a=i!==null&&s!==null&&s!==e.projectKey;a&&n.catch(()=>{});let[c,l,d]=await Promise.all([ec(e.transcriptPath,{turns:r}),mc(e.transcriptPath),a?e.fetchContext(s):n]),u=i??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=jg(r,d,u,t()),m=rc(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 Bg=b(()=>{"use strict";Mn();Nc();o(Wg,"ingestSessionEnd")});var zg={};ie(zg,{runOnSessionEnd:()=>PT});import{execFileSync as Oc}from"node:child_process";function TT(e,t){try{let n=z(),r=n!==null&&!Va(process.env,Re()),i=null;if(n!==null){let s=$n(Nn(n),{hostPids:Be(),cwd:process.cwd()});if(s){let a=Date.parse(s.snap.written_at);i=Number.isFinite(a)?Math.max(0,t-a):null}}return $g({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function RT(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 i=$n(Nn(r),{hostPids:Be(),cwd:process.cwd()}),s=Hg(i?.snap,e);if(s!==null)return s}}catch{}let n=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return t.test(n)?n:null}function IT(){try{let e=Oc("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function CT(e){let t=Kg.get(e);if(t!==void 0)return t;let n=null;try{let r=Oc("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 Kg.set(e,n),n}function NT(e){let t=Vg.get(e);if(t!==void 0)return t;let n=null;try{let r=Oc("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=Sa(r))}catch{n=null}return Vg.set(e,n),n}async function OT(e,t,n,r){if(n===null)return null;try{return await Ht("get_session_cost_context",{project_key:n,...r?{session_id:r}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:H,timeoutMs:Fg})}catch{return null}}async function DT(e,t,n,r,i){let s=fetch(AT,{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=nc(tc(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
|
|
184
|
+
`)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([s,a])}async function PT(){try{for(let i of Be())gh(On(),i)}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=Ln(t);if(r)try{let i=te(),s=RT(kr(r,n)),a=z();await Wg({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:s,repoRoot:IT(),resolveRoot:CT,projectKeyOf:NT,fetchContext:o(c=>OT(e,i,c,s),"fetchContext"),post:o((c,l)=>DT(e,i,c,1500,l),"post"),connection:TT})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
|
|
185
|
+
`)}return await Ic(n),0}var AT,Kg,Vg,qg=b(()=>{"use strict";Mn();xn();ce();Tr();Sc();xc();Ce();Cc();za();is();tt();os();et();Lg();Nc();Gg();Bg();AT=gs;o(TT,"connectionVerdict");o(RT,"presenceSessionId");o(IT,"sessionRepoRoot");Kg=new Map;o(CT,"gitRootOf");Vg=new Map;o(NT,"projectKeyOfRoot");o(OT,"fetchCostContext");o(DT,"postWithTimeout");o(PT,"runOnSessionEnd")});function _e(e=process.env,t=Re()){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 Un(e,t=We()){let n={};try{let i=await ne(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await Y(t,JSON.stringify(r,null,2)+`
|
|
186
|
+
`,384)}var Vt=b(()=>{"use strict";xn();He();o(_e,"resolveGuardConfig");o(Un,"writeGuardConfig")});function MT(e){let t={mode:"warn",stopGate:!1,full:!1,dryRun:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--mode":{let i=e[++n];if(i!=="warn"&&i!=="block")return null;t.mode=i;break}case"--stop-gate":t.stopGate=!0;break;case"--full":case"--yes":t.full=!0;break;case"--dry-run":t.dryRun=!0;break;default:return null}return t}async function Yg(e,t,n=process.stdout){let r=MT(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
|
|
187
|
+
`),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},s=[];for(let l of Ui)s.push(await Pa(i,l));for(let l of s)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
|
|
188
|
+
`);let a=s.some(l=>l.detail==="user declined"),c=s.some(l=>l.status==="failed");return r.dryRun?(n.write(`
|
|
178
189
|
[dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
|
|
179
|
-
`),0):(await
|
|
190
|
+
`),0):(await Un({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
|
|
180
191
|
Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
|
|
181
192
|
flip: maind-mcp-bridge guard mode <warn|block>
|
|
182
193
|
disable: maind-mcp-bridge guard off (hooks stay wired, become no-ops)
|
|
183
194
|
check: maind-mcp-bridge guard status
|
|
184
195
|
Takes effect for NEW Claude Code sessions (hooks are read at session start).
|
|
185
196
|
`),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
|
|
189
|
-
`),1):(await
|
|
190
|
-
`),0)}case"off":return await
|
|
197
|
+
`),c?1:0)}var Jg=b(()=>{"use strict";Sn();Ma();Vt();o(MT,"parseGuardInstallFlags");o(Yg,"runGuardInstall")});import{existsSync as Xg}from"node:fs";import{mkdir as $T,readFile as LT,readdir as FT,rename as jT,stat as UT,unlink as HT,writeFile as GT}from"node:fs/promises";import{join as ks}from"node:path";function Zg(e){return ks(Cr,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function Ke(e){try{let t=Zg(e);if(!Xg(t))return{};let n=JSON.parse(await LT(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function me(e,t){await $T(Cr,{recursive:!0,mode:448});let n=Zg(e),r=`${n}.tmp`;await GT(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await jT(r,n)}async function Qg(e=7*24*60*60*1e3,t=Date.now()){try{if(!Xg(Cr))return;for(let n of await FT(Cr)){if(!n.endsWith(".json"))continue;let r=ks(Cr,n);try{let i=await UT(r);t-i.mtimeMs>e&&await HT(r)}catch{}}}catch{}}var Hn,Cr,Gn=b(()=>{"use strict";Bt();Hn=ks(Wt,"guard"),Cr=ks(Hn,"sessions");o(Zg,"sessionFile");o(Ke,"loadGuardSession");o(me,"saveGuardSession");o(Qg,"sweepOldGuardSessions")});import{existsSync as WT}from"node:fs";import{appendFile as BT,mkdir as KT,open as VT}from"node:fs/promises";import{join as zT}from"node:path";async function le(e){try{await KT(Hn,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
|
|
198
|
+
`;await BT(Wn,t,{mode:384})}catch{}}async function ey(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(!WT(Wn))return t;let n=await VT(Wn,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),s=Buffer.alloc(r-i);await n.read(s,0,s.length,i);let c=s.toString("utf8").split(`
|
|
199
|
+
`);for(let l of i>0?c.slice(1):c)if(l.trim())try{let d=JSON.parse(l);typeof d.event=="string"&&d.event in t&&(t[d.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var Wn,Bn=b(()=>{"use strict";Gn();Wn=zT(Hn,"events.jsonl");o(le,"appendGuardEvent");o(ey,"readGuardEventCounts")});var ny={};ie(ny,{runGuard:()=>ZT});import{existsSync as qT,readFileSync as YT}from"node:fs";import{homedir as ty}from"node:os";import{join as JT}from"node:path";async function ZT(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Yg(n,ty());case"status":return eR();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
|
|
200
|
+
`),1):(await Un({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
|
|
201
|
+
`),0)}case"off":return await Un({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
|
|
191
202
|
`),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),
|
|
195
|
-
logged (auditable) in ${
|
|
196
|
-
`),0}async function
|
|
197
|
-
`);let
|
|
203
|
+
`),1):(await Un({guard_stop_gate:r==="on"}),process.stdout.write(`strict stop-gate ${r==="on"?"enabled":"disabled"}.
|
|
204
|
+
`),0)}case"skip":return QT(n);default:return process.stdout.write(XT),t===void 0||t==="--help"||t==="-h"?0:1}}async function QT(e){let t=null,n=null;for(let s=0;s<e.length;s++)e[s]==="--session"?t=e[++s]??null:e[s]==="--reason"&&(n=e[++s]??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>"
|
|
205
|
+
`),1;let r=n.trim().slice(0,500),i=await Ke(t);return await me(t,{...i,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.
|
|
206
|
+
logged (auditable) in ${Wn}
|
|
207
|
+
`),0}async function eR(){let e=_e(),t=JT(ty(),".claude","settings.json"),n=null;try{qT(t)&&(n=YT(t,"utf8"))}catch{}let r=Mt(n,{},Ui),i=await ey();process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",hook_wiring:r.map(a=>({event:a.event,subcommand:a.subcommand,status:a.status,detail:a.detail})),events:i,events_file:Wn},null,2)+`
|
|
208
|
+
`);let s=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"),s.length>0&&e.mode!=="off"){process.stderr.write(`
|
|
198
209
|
[maind] guard hook wiring is incomplete:
|
|
199
|
-
`);for(let a of
|
|
200
|
-
`);
|
|
201
|
-
`);o(
|
|
202
|
-
`),0):(process.stdout.write(
|
|
210
|
+
`);for(let a of s)process.stderr.write(` \u2022 ${a.detail}
|
|
211
|
+
`);s.some(a=>a.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var XT,ry=b(()=>{"use strict";Sn();Vt();Jg();Bn();Gn();XT=["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(`
|
|
212
|
+
`);o(ZT,"runGuard");o(QT,"runGuardSkip");o(eR,"runGuardStatus")});var cy={};ie(cy,{BRIEFING_CACHE_FILE:()=>sy,formatInjection:()=>ay,resolveBriefingInjection:()=>oy,runGuardInject:()=>dR});import{existsSync as tR}from"node:fs";import{mkdir as nR,readFile as rR,rename as iR,writeFile as sR}from"node:fs/promises";import{dirname as oR,join as aR}from"node:path";async function oy(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??sy,s=n.fetcher??ng,a=await uR(i);if(a!==null&&r-Date.parse(a.fetched_at)<cR&&a.project_key===e)return{text:a.text,via:"cache"};let l=await s({apiKey:t,deviceId:fR(),projectKey:e,bridgeVersion:H,timeoutMs:lR});return l!==null?(await pR(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:l}),{text:l,via:"fetch"}):a!==null?{text:a.text,via:"stale-cache"}:{text:null,via:"none"}}async function dR(){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 Qg();let r=typeof t.source=="string"?t.source:"startup";if(r==="resume"||r==="compact"){let d=await Ke(n);return await me(n,{...d,carryover:!0}),0}let i=B();if(i===null)return 0;let s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=z(),c=await oy(a,i),l=await Ke(n);return c.text===null?(await me(n,{...l,inject_failed:!0}),await le({event:"inject_fail",session_id:n,cwd:s,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.
|
|
213
|
+
`),0):(process.stdout.write(ay(c.text,c.via)),await me(n,{...l,injected:!0}),await le({event:"inject_ok",session_id:n,cwd:s,project_key:a??void 0,detail:c.via}),0)}catch{return 0}}function ay(e,t){let n=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",r=e;return Buffer.byteLength(r,"utf8")>iy&&(r=r.slice(0,iy)+`
|
|
203
214
|
\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
215
|
|
|
205
216
|
`+r+`
|
|
206
|
-
`}async function
|
|
217
|
+
`}async function uR(e){try{if(!tR(e))return null;let t=JSON.parse(await rR(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 pR(e,t){try{await nR(oR(e),{recursive:!0,mode:448});let n=`${e}.tmp`;await sR(n,JSON.stringify(t,null,2),{mode:384}),await iR(n,e)}catch{}}function fR(){try{return te()}catch{return null}}var sy,cR,lR,iy,ly=b(()=>{"use strict";ce();Ce();tt();et();Vt();Bn();Gn();Tr();sy=aR(Hn,"briefing-cache.json"),cR=12*60*60*1e3,lR=3e3,iy=10*1024;o(oy,"resolveBriefingInjection");o(dR,"runGuardInject");o(ay,"formatInjection");o(uR,"readCache");o(pR,"writeCache");o(fR,"safeDeviceId")});var fy={};ie(fy,{decideGate:()=>py,runGuardGate:()=>hR});function py(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:dy(n)}:(n.deny_count??0)>=uy?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. "+dy(n)}:{kind:"deny",reason:mR(e.sessionId,n)}}function dy(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 mR(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
218
|
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
208
219
|
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<=
|
|
220
|
+
After ${uy} denies this gate downgrades itself to warn.`}async function hR(){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 i=await Ke(r),s=(await X()).guard_signals?.[r]?.consulted_at!==void 0,a=py({mode:e.mode,session:i,consulted:s,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(Fn(a.reason)),await me(r,{...i,deny_count:(i.deny_count??0)+1}),await le({event:"deny",session_id:r,cwd:c,project_key:l}),0):a.kind==="warn"?(process.stdout.write(ot(a.context)),await me(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await le({event:"warn",session_id:r,cwd:c,project_key:l}),0):(await me(r,{...i,edits_seen:(i.edits_seen??0)+1}),0)}catch{return 0}}var uy,my=b(()=>{"use strict";Ce();jn();Bt();tt();Vt();Bn();Gn();uy=3;o(py,"decideGate");o(dy,"warnText");o(mR,"denyText");o(hR,"runGuardGate")});var gy={};ie(gy,{decideStopGate:()=>hy,runGuardStop:()=>yR});function hy(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function yR(){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 Ke(n),i=(await X()).guard_signals?.[n]?.reviewed_at!==void 0;return hy({enabled:!0,editsSeen:r.edits_seen??0,reviewed:i,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:gR})),await me(n,{...r,stop_blocked:!0}),await le({event:"stop_block",session_id:n})),0}catch{return 0}}var gR,yy=b(()=>{"use strict";Ce();Bt();Vt();Bn();Gn();o(hy,"decideStopGate");gR="[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(yR,"runGuardStop")});import{appendFile as _R,mkdir as bR,readFile as by,rename as wy,writeFile as vy}from"node:fs/promises";import{homedir as ky}from"node:os";import{join as Sy}from"node:path";function xy(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},s=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=i[d.tool]??={calls:0,warns:0,denies:0};if(d.event==="tool_call"?u.calls+=1:d.event==="policy_warn"||d.event==="sha_warn"?u.warns+=1:u.denies+=1,(d.event==="policy_warn"||d.event==="policy_deny")&&d.convention_id!==void 0&&d.convention_version!==void 0){let p=s.get(d.convention_id);(p===void 0||d.convention_version>p)&&s.set(d.convention_id,d.convention_version)}}let l=Object.entries(i).sort((d,u)=>u[1].calls+u[1].warns+u[1].denies-(d[1].calls+d[1].warns+d[1].denies)).slice(0,64);return{window_start:new Date(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:[...s.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function zt(){return Sy(ky(),".maind","gateway","attest-spool.jsonl")}async function Dc(e){let t=B();if(t===null)return!1;let n=await Ht("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 Ey(e){try{await bR(Sy(ky(),".maind","gateway"),{recursive:!0}),await _R(zt(),JSON.stringify(e)+`
|
|
221
|
+
`,{mode:384}),await wR()}catch{}}async function wR(){try{let t=(await by(zt(),"utf8")).split(`
|
|
222
|
+
`).filter(r=>r.trim());if(t.length<=_y)return;let n=`${zt()}.${process.pid}.tmp`;await vy(n,t.slice(-_y).join(`
|
|
212
223
|
`)+`
|
|
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
|
|
224
|
+
`,{mode:384}),await wy(n,zt())}catch{}}async function Ay(){let e;try{e=(await by(zt(),"utf8")).split(`
|
|
225
|
+
`).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await Dc(i)||(n=!0,t.push(r))}try{let r=`${zt()}.${process.pid}.tmp`;await vy(r,t.length>0?t.join(`
|
|
215
226
|
`)+`
|
|
216
|
-
`:"",{mode:384}),await
|
|
217
|
-
`,384)}async function
|
|
218
|
-
`),2;let n=
|
|
219
|
-
`);continue}let a=
|
|
220
|
-
`);continue}if(!(t.yes||await
|
|
227
|
+
`:"",{mode:384}),await wy(r,zt())}catch{}}var _y,Ty=b(()=>{"use strict";ce();Tr();et();_y=256;o(xy,"aggregateWindow");o(zt,"attestSpoolPath");o(Dc,"postAttestation");o(Ey,"spoolAttestation");o(wR,"capSpool");o(Ay,"flushAttestSpool")});function Nr(e=process.env,t=Re()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Ss(e=process.env,t=Re()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function Ry(e,t=We()){let n={};try{let i=await ne(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await Y(t,JSON.stringify(r,null,2)+`
|
|
228
|
+
`,384)}async function Iy(e,t=We()){await Ry({gateway_mode:e},t)}async function Cy(e,t=We()){await Ry({gateway_attest:e},t)}function Ny(e=process.env,t=Re()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var Pc=b(()=>{"use strict";xn();He();o(Nr,"resolveGatewayMode");o(Ss,"resolveGatewayAttest");o(Ry,"writeGatewayConfigPatch");o(Iy,"writeGatewayMode");o(Cy,"writeGatewayAttest");o(Ny,"resolveShaProofMode")});function Dy(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,s=i.gateway_gate;if(typeof s!="object"||s===null)continue;let a=s;if(a.enabled!==!0)continue;let c=typeof i.id=="string"&&i.id.length>0&&i.id.length<=64?i.id:null,l=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||l===null)continue;let d=typeof i.severity=="string"&&vR.has(i.severity)?i.severity:"recommended",u=typeof i.summary=="string"?i.summary:"",p=Array.isArray(a.servers)?a.servers.filter(h=>typeof h=="string"&&h.length>0):null;if(p!==null&&p.length===0)continue;let 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 kR(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Py(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let s of n)kR(s,e,t)&&(i===null||Oy[s.severity]>Oy[i.severity])&&(i=s);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function My(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 vR,Oy,Mc=b(()=>{"use strict";vR=new Set(["required","recommended","info"]);o(Dy,"extractGatewayRules");Oy={required:2,recommended:1,info:0};o(kR,"ruleMatches");o(Py,"decideToolCall");o(My,"policyDenyText")});import{mkdirSync as SR,readFileSync as xR,renameSync as ER,writeFileSync as AR}from"node:fs";import{homedir as TR}from"node:os";import{dirname as RR,join as IR}from"node:path";function $y(){return IR(TR(),".maind","gateway","policy-cache.json")}function xs(e,t,n=new Date().toISOString()){try{let r={version:$c,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=$y();SR(RR(i),{recursive:!0});let s=`${i}.${process.pid}.tmp`;AR(s,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),ER(s,i)}catch{}}function Es(e){try{let t=xR($y(),"utf8"),n=JSON.parse(t);return n.version!==$c||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:$c,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var $c,Lc=b(()=>{"use strict";$c=1;o($y,"policyCachePath");o(xs,"writePolicyCache");o(Es,"readPolicyCache")});function Or(e=process.env){let t=e.MAIND_MCP_URL??kc,n=B();return{mcpUrl:t,keyFp:n?Ei(n):"anon"}}async function As(e=6e3){let t=B();if(t===null)return null;let n=null;try{n=z()}catch{n=null}let r=await Ht("get_conventions",{},{apiKey:t,deviceId:te(),projectKey:n,bridgeVersion:H,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return Dy(i)}var Fc=b(()=>{"use strict";yn();ce();Tr();tt();et();Mc();o(Or,"policyIdentity");o(As,"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 CR(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 NR(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"}:CR(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Ly(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],s=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=s||t.env?{...s??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return a&&(c.env=a),c}function Fy(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 jy(e){return Object.entries(e).map(([t,n])=>{let r=NR(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var Uy=b(()=>{"use strict";o(Dr,"isGatewayWrapped");o(CR,"isMaindProxyEntry");o(NR,"classifyServer");o(Ly,"wrapServerEntry");o(Fy,"unwrapServerEntry");o(jy,"planRewrites")});var Vy={};ie(Vy,{runGatewayInstall:()=>LR,runGatewayUninstall:()=>FR});import{existsSync as OR,readFileSync as DR}from"node:fs";import{homedir as PR}from"node:os";import{join as Hy}from"node:path";import{createInterface as MR}from"node:readline";function Gy(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 Wy(){return[{label:"Claude Code (project .mcp.json)",path:Hy(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:Hy(PR(),".claude.json")}]}async function By(e){let t=MR({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 Ky(e){let t=$R(e);if(t===null)return null;try{let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=n,i=r.mcpServers;return typeof i!="object"||i===null||Array.isArray(i)?null:{raw:r,servers:i}}catch{return null}}function $R(e){try{return OR(e)?DR(e,"utf8"):null}catch{return null}}async function LR(e){let t=Gy(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
229
|
+
`),2;let n=Ae({entryPath:Te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of Wy()){let s=Ky(i.path);if(s===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
|
|
230
|
+
`);continue}let a=jy(s.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
|
|
231
|
+
`);continue}if(!(t.yes||await By(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
|
|
221
232
|
Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
|
|
222
|
-
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${
|
|
223
|
-
`);continue}
|
|
224
|
-
`)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await
|
|
233
|
+
The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
|
|
234
|
+
`);continue}s.servers[c.key]=Ly(s.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
|
|
235
|
+
`)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await Y(i.path,JSON.stringify(s.raw,null,2)+`
|
|
225
236
|
`,384)}return process.stderr.write(r>0?`
|
|
226
237
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
|
|
227
238
|
`:`
|
|
228
239
|
Nothing to wrap.
|
|
229
|
-
`),0}async function
|
|
230
|
-
`),2;let n=0;for(let r of
|
|
231
|
-
`);continue}
|
|
232
|
-
`)}!t.dryRun&&
|
|
240
|
+
`),0}async function FR(e){let t=Gy(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
241
|
+
`),2;let n=0;for(let r of Wy()){let i=Ky(r.path);if(i===null)continue;let s=!1;for(let[a,c]of Object.entries(i.servers)){if(!Dr(c)||!(t.yes||await By(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=Fy(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
|
|
242
|
+
`);continue}i.servers[a]=d,s=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
|
|
243
|
+
`)}!t.dryRun&&s&&await Y(r.path,JSON.stringify(i.raw,null,2)+`
|
|
233
244
|
`,384)}return process.stderr.write(n>0?`
|
|
234
245
|
${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
|
|
235
246
|
`:`
|
|
236
247
|
Nothing wrapped \u2014 nothing to restore.
|
|
237
|
-
`),0}var
|
|
248
|
+
`),0}var zy=b(()=>{"use strict";He();kn();Uy();o(Gy,"parseFlags");o(Wy,"targets");o(By,"confirm");o(Ky,"loadConfig");o($R,"readFileSafeSync");o(LR,"runGatewayInstall");o(FR,"runGatewayUninstall")});var qy={};ie(qy,{runGatewayAttest:()=>UR,runGatewayMode:()=>jR,runGatewayPolicy:()=>WR});async function jR(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
249
|
`),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
239
|
-
`),2):(await
|
|
250
|
+
`),2):(await Iy(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
|
|
240
251
|
`:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
|
|
241
252
|
`:`Convention policy is off; only explicit --deny-tool flags apply.
|
|
242
|
-
`)),0)}async function
|
|
253
|
+
`)),0)}async function UR(e){let t=e[0];if(t===void 0){let n=Ss(),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
254
|
`+(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
255
|
`)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
|
|
245
|
-
`),2):(await
|
|
256
|
+
`),2):(await Cy(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
257
|
`:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
|
|
247
|
-
`),0)}function
|
|
248
|
-
`;let t="";for(let n of e){let r=n.servers===null?"*":n.servers.join(","),
|
|
249
|
-
`}return t}function
|
|
250
|
-
`):(
|
|
251
|
-
`))}let
|
|
252
|
-
`),
|
|
253
|
-
`),0):(process.stdout.write(`maind: policy from cache (${
|
|
254
|
-
`),process.stdout.write(
|
|
255
|
-
`),0)}var
|
|
256
|
-
`,{mode:384})}catch{}}function
|
|
258
|
+
`),0)}function HR(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
|
|
259
|
+
`;let t="";for(let n of e){let r=n.servers===null?"*":n.servers.join(","),i=n.severity==="required"?"deny-capable":"warn-only";t+=` ${n.tool} [servers: ${r}] ${n.conventionId} v${n.conventionVersion} (${n.severity} \u2192 ${i})
|
|
260
|
+
`}return t}function GR(e,t=Date.now()){let n=Date.parse(e.cached_at);if(Number.isNaN(n))return"unknown age";let r=Math.floor((t-n)/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;let i=Math.floor(r/60);return i<24?`${i} h ago`:`${Math.floor(i/24)} d ago`}async function WR(e){let t=e.includes("--refresh"),n=Nr(),r=Or();if(t){let s=await As();s===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
|
|
261
|
+
`):(xs(r,s),process.stdout.write(`maind: policy refreshed (${s.length} rule(s)).
|
|
262
|
+
`))}let i=Es(r);return process.stdout.write(`maind: gateway mode '${n}'
|
|
263
|
+
`),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
|
|
264
|
+
`),0):(process.stdout.write(`maind: policy from cache (${GR(i)}, ${r.mcpUrl}):
|
|
265
|
+
`),process.stdout.write(HR(i.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
|
|
266
|
+
`),0)}var Yy=b(()=>{"use strict";Pc();Lc();Fc();o(jR,"runGatewayMode");o(UR,"runGatewayAttest");o(HR,"renderRules");o(GR,"cacheAge");o(WR,"runGatewayPolicy")});var e_={};ie(e_,{gatewayEventsFile:()=>Zy,parseGatewayArgs:()=>Qy,runGateway:()=>JR});import{spawn as BR}from"node:child_process";import{appendFile as KR,mkdir as VR}from"node:fs/promises";import{homedir as Jy}from"node:os";import{basename as zR,join as Xy}from"node:path";import{createInterface as qR}from"node:readline";function Zy(){return Xy(Jy(),".maind","gateway","events.jsonl")}async function YR(e){try{let t=Zy();await VR(Xy(Jy(),".maind","gateway"),{recursive:!0}),await KR(t,JSON.stringify(e)+`
|
|
267
|
+
`,{mode:384})}catch{}}function Qy(e){let t=new Set,n=null,r=0;for(;r<e.length;){let i=e[r];if(i==="--deny-tool"){let s=e[r+1];if(!s)return null;t.add(s),r+=2;continue}if(i==="--label"){let s=e[r+1];if(!s)return null;n=s,r+=2;continue}if(i==="--"){let s=e[r+1];return s?{denyTools:t,label:n,command:s,args:e.slice(r+2)}:null}return null}return null}async function JR(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:S,runGatewayUninstall:I}=await Promise.resolve().then(()=>(zy(),Vy));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(()=>(Yy(),qy));return e[0]==="mode"?I(e.slice(1)):e[0]==="attest"?S(e.slice(1)):$(e.slice(1))}let t=Qy(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
|
|
257
268
|
maind-mcp-bridge gateway install [--yes] [--dry-run]
|
|
258
269
|
maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
|
|
259
270
|
maind-mcp-bridge gateway mode [off|warn|enforce]
|
|
@@ -263,54 +274,54 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
|
|
|
263
274
|
NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
|
|
264
275
|
install/uninstall rewrite Claude Code MCP configs (consent per server).
|
|
265
276
|
mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
|
|
266
|
-
`),2;let{denyTools:n,label:r,command:
|
|
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[
|
|
275
|
-
`);let g=r.params?.name;process.stdout.write(
|
|
276
|
-
`);return}
|
|
277
|
+
`),2;let{denyTools:n,label:r,command:i,args:s}=t,a=r??zR(i),c=Nr(),l=Ny(),d=l==="off"?null:Pr(),u=c==="off"?[]:Es(Or())?.rules??[];c!=="off"&&As().then(S=>{S!==null&&(u=S,xs(Or(),S))}).catch(()=>{});let p=[],m=Ss()&&B()!==null&&c!=="off",h=null;try{h=z()}catch{h=null}let g=o(S=>{YR(S),m&&p.push(S)},"record"),y=o(async()=>{if(!m)return;let S=xy(p.splice(0),c,a,h);S!==null&&(await Dc(S)||await Ey(S))},"attestAndReset");m&&Ay().catch(()=>{});let _=setInterval(()=>{y()},30*6e4);_.unref();let w=BR(i,s,{stdio:["pipe","pipe","inherit"]});w.stdout.pipe(process.stdout),w.on("error",S=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(S)}
|
|
278
|
+
`),process.exitCode=1});let k=qR({input:process.stdin,terminal:!1});k.on("line",S=>{let I=Qc(S);if(I.kind==="request"&&I.method==="tools/call"&&I.toolName){if(n.has(I.toolName)&&I.id!==void 0){process.stdout.write(Yt(I.id,I.toolName)+`
|
|
279
|
+
`),g(Rs("deny",a,I.toolName,Date.now()));return}let $=Py(I.toolName,a,u,c);if($.kind==="deny"&&I.id!==void 0){process.stdout.write(Yt(I.id,I.toolName,My(I.toolName,$.rule))+`
|
|
280
|
+
`),g(Is("policy_deny",a,I.toolName,Date.now(),$.rule.conventionId,$.rule.conventionVersion));return}($.kind==="warn"||$.kind==="deny")&&g(Is("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(Yt(I.id,I.toolName,Jt(j,!0))+`
|
|
281
|
+
`),g(Cs("sha_deny",a,I.toolName,Date.now()));return}let L=j??U[0];process.stderr.write(`[maind gateway] ${Jt(L,!1)}
|
|
282
|
+
`),g(Cs("sha_warn",a,I.toolName,Date.now()))}g(Rs("tool_call",a,I.toolName,Date.now()))}w.stdin.write(S+`
|
|
283
|
+
`)}),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 t_=b(()=>{"use strict";Ns();Ty();Pc();Mc();Os();Lc();Fc();ce();tt();o(Zy,"gatewayEventsFile");o(YR,"logEvent");o(Qy,"parseGatewayArgs");o(JR,"runGateway")});var Kc={};ie(Kc,{MAX_ENTRIES:()=>jc,TTL_MS:()=>Gc,crossSessionDir:()=>Wc,decideCrossSession:()=>i_,parseSessionDb:()=>r_,pruneDb:()=>Bc,runGuardCrossCheck:()=>sI,runGuardCrossObserve:()=>iI,staleReason:()=>Uc});import{mkdir as XR,readFile as ZR,readdir as QR,stat as n_,unlink as eI,writeFile as tI}from"node:fs/promises";import{homedir as nI}from"node:os";import{join as Hc}from"node:path";function Wc(){return Hc(nI(),".maind","cross-session")}function r_(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[s,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[s]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[s,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(i[s]=a);return{files:r,warned:i}}function Bc(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=Gc);return n.length>jc&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-jc)),{files:Object.fromEntries(n),warned:e.warned}}function i_(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Uc(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 s_(e){let t=Wc();return await XR(t,{recursive:!0}),Hc(t,`${e}.json`)}async function o_(e,t){try{let n=await ZR(await s_(e),"utf8");return Bc(r_(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function a_(e,t){try{await tI(await s_(e),JSON.stringify(t),{mode:384})}catch{}}async function rI(e){try{let t=Wc();for(let n of await QR(t)){if(!n.endsWith(".json"))continue;let r=Hc(t,n),i=await n_(r).catch(()=>null);i&&e-i.mtimeMs>Gc&&await eI(r).catch(()=>{})}}catch{}}async function c_(e){try{return(await n_(e)).mtimeMs}catch{return}}async function iI(e,t=Date.now()){try{if(_e().mode==="off")return 0;let r=e??await G(),i=typeof r.session_id=="string"?r.session_id:"",s=Ie(r);if(!i||!s)return 0;let a=await c_(s);if(a===void 0)return 0;let c=await o_(i,t);return c.files[s]={m:a,t},delete c.warned[s],await a_(i,Bc(c,t)),await rI(t),0}catch{return 0}}async function sI(e,t=Date.now()){try{let n=_e();if(n.mode==="off")return 0;let r=e??await G(),i=typeof r.session_id=="string"?r.session_id:"",s=Ie(r);if(!i||!s)return 0;let a=await o_(i,t),c=i_(a.files[s]?.m,await c_(s));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(Fn(Uc(s,c))+`
|
|
284
|
+
`),await le({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s}),0):(a.warned[s]===c.current||(process.stdout.write(ot(Uc(s,c))+`
|
|
285
|
+
`),a.warned[s]=c.current,await a_(i,a),await le({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s})),0)}catch{return 0}}var Gc,jc,Vc=b(()=>{"use strict";Ce();jn();Vt();Bn();Gc=48*3600*1e3,jc=500;o(Wc,"crossSessionDir");o(r_,"parseSessionDb");o(Bc,"pruneDb");o(i_,"decideCrossSession");o(Uc,"staleReason");o(s_,"dbPath");o(o_,"loadDb");o(a_,"saveDb");o(rI,"sweepStaleSessionFiles");o(c_,"fileMtime");o(iI,"runGuardCrossObserve");o(sI,"runGuardCrossCheck")});var qc={};ie(qc,{INDEX_REFRESH_WORKER:()=>u_,acquireLock:()=>f_,releaseLock:()=>zc,runIndexRefreshWorker:()=>fI,runOnIndexRefresh:()=>pI});import{spawn as oI}from"node:child_process";import{existsSync as aI,mkdirSync as cI,rmdirSync as l_,statSync as lI}from"node:fs";import{join as d_}from"node:path";function p_(e){return d_(e,".maind","index-refresh.lock")}function uI(e){return d_(e,".maind","code-index.sqlite")}function f_(e,t=Date.now()){let n=p_(e);try{if(t-lI(n).mtimeMs<dI)return!1;l_(n)}catch{}try{return cI(n,{recursive:!1}),!0}catch{return!1}}function zc(e){try{l_(p_(e))}catch{}}async function pI(){try{let e=await G(),t=fe(typeof e.cwd=="string"?e.cwd:process.cwd());if(!aI(uI(t))||!f_(t))return 0;let n=process.argv[1];if(n===void 0)return zc(t),0;oI(process.execPath,[n,u_,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function fI(){let e=process.argv[3]??fe();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(Wa(),Cm)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{zc(e)}return 0}var dI,u_,Yc=b(()=>{"use strict";Ce();wr();dI=30*6e4,u_="index-refresh-run";o(p_,"lockPath");o(uI,"indexDbPath");o(f_,"acquireLock");o(zc,"releaseLock");o(pI,"runOnIndexRefresh");o(fI,"runIndexRefreshWorker")});import{randomUUID as mI}from"node:crypto";import{createInterface as wS}from"node:readline";var m_=[["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 h_(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of m_)if(t.includes(n))return r;return null}o(h_,"mapClientInfoNameToFamily");function Zc(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Ts(t)||t.method!=="initialize")return null;let n=t.params;if(!Ts(n))return null;let r=n.clientInfo;if(!Ts(r))return null;let i=r.name,s=h_(typeof i=="string"?i:null);if(s===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:s,version:c}}o(Zc,"tryExtractInitializeClient");function Ts(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Ts,"isRecord");Ns();Os();yn();var vS="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")}},Ci=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=Ei(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=kS(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=SS(r),this.clientVersionLocked=this.clientVersion!==null;let i=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=i&&/^[a-f0-9]{64}$/.test(i)?i:null,this.localRouter=t.localRouter??null,this.presence=t.presence??null,this.shaRepoRoot=Pr(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??vS}async run(){let t=wS({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=Zc(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&Ri(t)&&(this.initFrame=t);let r=AS(t),i=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&&rl(p)&&r.id!==null){let h=Jt(p,!0);process.stderr.write(`[maind] ${h}
|
|
286
|
+
`);let g=r.params?.name;process.stdout.write(Yt(r.id,typeof g=="string"?g:"unknown",h)+`
|
|
287
|
+
`);return}i=Jt(m,!1),process.stderr.write(`[maind] ${i}
|
|
277
288
|
`)}}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
|
|
279
|
-
`);return}if(
|
|
280
|
-
`);return}if(
|
|
281
|
-
`);return}if(d.startsWith("text/event-stream"))await
|
|
282
|
-
`)}}}async handle401(t,n){let r=await t.text().catch(()=>""),
|
|
283
|
-
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${
|
|
284
|
-
`).trim();
|
|
289
|
+
`);return}let s=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=Ti(t);if(this.serveInitializeFromCache(t,p))return;Ii(p,-32603,`bridge network error: ${RS(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&&!Ri(t)){let u=await c.text().catch(()=>"");if(TS(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=Ti(t);Ii(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=Ti(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;Ii(u,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let d=c.headers.get("content-type")??"";if(s&&this.localRouter){let u=d.startsWith("text/event-stream")?await ba(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
|
|
290
|
+
`);return}if(Ri(t)){let u=d.startsWith("text/event-stream")?await ba(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
|
|
291
|
+
`);return}if(i!==null){let u=d.startsWith("text/event-stream")?await ba(c):await c.text(),p=ES(u,i);p.trim().length>0&&process.stdout.write(p+`
|
|
292
|
+
`);return}if(d.startsWith("text/event-stream"))await xS(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
|
|
293
|
+
`)}}}async handle401(t,n){let r=await t.text().catch(()=>""),i=r.toLowerCase();if(i.includes("device_mismatch")||i.includes("device_revoked")||i.includes("device_required")||i.includes("invalid or revoked"))throw this.terminated=!0,new pr(IS(i));let a=Ti(n);Ii(a,-32001,`bridge auth error: ${r.slice(0,200)}`)}async postPresenceToolCall(t,n){if(this.sessionId===null)throw new Error("presence: no MCP session established yet");this.presenceFrameId+=1;let r=JSON.stringify({jsonrpc:"2.0",id:`maind-presence-${this.presenceFrameId}`,method:"tools/call",params:{name:t,arguments:n}}),i=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),s=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return CS(s)}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=Ue()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&vf(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!Ri(t))return!1;let r=kf(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(Sf(n,r)+`
|
|
294
|
+
`),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${Ai(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function kS(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(kS,"normalizeClientFamily");function SS(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}o(SS,"normalizeClientVersion");async function xS(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=o(()=>{if(i.length===0)return;let a=i.join(`
|
|
295
|
+
`).trim();i=[],a.length>0&&process.stdout.write(a+`
|
|
285
296
|
`)},"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===""){
|
|
287
|
-
`).trim();
|
|
288
|
-
`))!==-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:")&&
|
|
289
|
-
`)}o(
|
|
290
|
-
`)}o(
|
|
291
|
-
`).map(a=>a.trim()).filter(a=>a.startsWith("data:"));if(
|
|
292
|
-
`),null));if(p){if(p.status==="approved")return
|
|
297
|
+
`))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){s();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{s()}}o(xS,"pipeSseToStdout");function ES(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(ES,"appendNoteToToolResult");function AS(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}o(AS,"parseRpc");async function ba(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=[],a=o(()=>{if(s.length===0)return;let c=s.join(`
|
|
298
|
+
`).trim();s=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
|
|
299
|
+
`))!==-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/,""))}}}finally{a()}return i.join(`
|
|
300
|
+
`)}o(ba,"collectSseText");function Ti(e){try{return JSON.parse(e).id??null}catch{return null}}o(Ti,"tryExtractId");function Ri(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}o(Ri,"isInitializeRequest");function TS(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(TS,"isSessionLossBody");function RS(e){return e instanceof Error?e.message:String(e)}o(RS,"stringifyErr");function Ii(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
|
|
301
|
+
`)}o(Ii,"emitJsonRpcError");function IS(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}o(IS,"extractHint");function CS(e){try{let t=e.trim();if(t.length===0)return null;let n=t;if(!t.startsWith("{")){let s=t.split(`
|
|
302
|
+
`).map(a=>a.trim()).filter(a=>a.startsWith("data:"));if(s.length===0)return null;n=s[s.length-1].slice(5).trim()}let i=JSON.parse(n).result?.content?.[0]?.text;return typeof i!="string"?null:JSON.parse(i)}catch{return null}}o(CS,"parsePresenceToolResult");ce();ce();bn();import{spawn as HS}from"node:child_process";import{platform as GS}from"node:os";async function wn(e,t=process.stderr){let n=mr(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,s=Oi(e),a=`mcp-bridge-${s.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:s})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await VS(l.verification_uri_complete).catch(()=>{}),KS(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await BS(u);let p=await WS(i,l.device_code).catch(m=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(m)}
|
|
303
|
+
`),null));if(p){if(p.status==="approved")return Dt(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
|
|
293
304
|
`),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
|
|
294
305
|
`),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
|
|
295
306
|
`),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
|
|
296
|
-
`),null}o(
|
|
307
|
+
`),null}o(wn,"runDeviceFlow");async function WS(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(WS,"pollOnce");function BS(e){return new Promise(t=>setTimeout(t,e))}o(BS,"sleep");function KS(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: ${Rf(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Rf(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
308
|
`)+`
|
|
298
|
-
`)}o(
|
|
299
|
-
`))}o(
|
|
300
|
-
`;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)),
|
|
309
|
+
`)}o(KS,"printAuthInstructions");function Rf(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}o(Rf,"pad");async function VS(e){let t,n;switch(GS()){case"darwin":t="open",n=[e];break;case"win32":t="cmd",n=["/c","start","",e];break;default:t="xdg-open",n=[e];break}return new Promise((r,i)=>{try{let s=HS(t,n,{stdio:"ignore",detached:!0});s.on("error",i),s.unref(),r()}catch(s){i(s)}})}o(VS,"openExternalBrowser");et();tt();et();import*as Wm from"node:os";function If(e){let t={projectRoot:null,full:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--no-preamble":t.noPreamble=!0;break;case"--no-hook":t.noHook=!0;break;case"--non-interactive":t.nonInteractive=!0;break;case"--telemetry":t.telemetry=!0;break;case"--skip-codex":t.skipCodex=!0;break;case"--dry-run":t.dryRun=!0;break;case"--auto-working-paths":t.autoWorkingPaths=!0;break;case"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Ee("--project-root requires a path argument");t.projectRoot=i,n++;break}case"--token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Ee("--token requires a token argument");t.token=i,n++;break}case"--one-click-token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Ee("--one-click-token requires a token argument");t.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Ee("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=i,n++;break}case"--client":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Ee("--client requires a family argument (e.g. claude-code, cursor, windsurf, copilot, codex, claude-desktop)");t.client=i,n++;break}default:throw new Ee(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}return t.full&&(t.nonInteractive=!0),t}o(If,"parseInstallFlags");var Ee=class extends Error{static{o(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function Cf(){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(`
|
|
310
|
+
`))}o(Cf,"printInstallHelp");var Di=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 i of this.results)i.status==="created"||i.status==="merged"||i.status==="skipped"||i.status==="would-create"||i.status==="would-merge"||i.status==="would-pair"?t++:i.status==="needs-user-decision"?n++:i.status==="failed"&&r++;return{total:this.results.length,ok:t,needsDecision:n,failed:r}}hasFailures(){return this.results.some(t=>t.status==="failed")}hasUserDecisionPending(){return this.results.some(t=>t.status==="needs-user-decision")}exitCode(){return this.hasFailures()||this.hasUserDecisionPending()?1:0}toMarkdownTable(){if(this.results.length===0)return`_no steps were attempted_
|
|
311
|
+
`;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(d=>d.target.length)),r=Math.max(t[1].length,...this.results.map(d=>d.action.length)),i=Math.max(t[2].length,...this.results.map(d=>d.status.length)),s=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(i)} | ${"-".repeat(s)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],i)} | ${a(t[3],s)} |`),l.push(c);for(let d of this.results)l.push(`| ${a(d.target,n)} | ${a(d.action,r)} | ${a(d.status,i)} | ${a(d.detail??"",s)} |`);return l.join(`
|
|
301
312
|
`)+`
|
|
302
313
|
`}print(t){let n=this.summary();t.write(`
|
|
303
314
|
`),t.write(this.toMarkdownTable()),t.write(`
|
|
304
315
|
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
|
|
316
|
+
`)}toJson(){return{steps:[...this.results],summary:this.summary()}}};import*as Nf from"node:fs/promises";import*as nt from"node:path";import*as Of from"node:readline";var ZS=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];async function Df(e){let t=nt.resolve(e),n=t;for(;;){if(await Mf(n))return n;let r=nt.dirname(n);if(r===n)return t;n=r}}o(Df,"detectProjectRoot");async function Pf(e){let n=nt.resolve(e),r=[];for(;;){await Mf(n)&&r.push(n);let i=nt.dirname(n);if(i===n)break;n=i}return r}o(Pf,"findAllProjectRoots");async function Mf(e){for(let t of ZS)try{return await Nf.access(nt.join(e,t)),!0}catch{}return!1}o(Mf,"hasAnyMarker");async function $f(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
|
|
306
317
|
Multiple project roots found between cwd and the filesystem root:
|
|
307
|
-
`),e.forEach((
|
|
318
|
+
`),e.forEach((s,a)=>{process.stdout.write(` [${a+1}] ${s}
|
|
308
319
|
`)}),process.stdout.write(`
|
|
309
|
-
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=
|
|
310
|
-
`),null):e[
|
|
311
|
-
`;if(n)return{target:e.key,action:
|
|
320
|
+
Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=Of.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(s=>{n.question("",a=>s(a.trim()))});if(n.close(),r==="")return e[0];let i=Number.parseInt(r,10);return Number.isNaN(i)||i<1||i>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
|
|
321
|
+
`),null):e[i-1]}o($f,"disambiguateProjectRoot");xa();kn();He();var hr="maind";async function Vf(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 Aa(e,"read",u)}let i,s="create";if(r===null||r.trim().length===0)i={};else{s="merge";try{i=JSON.parse(r)}catch(u){return Aa(e,"parse",u)}}if(!rt(i))return{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};let a=e.key==="claude-code-user"&&sx(i),c,l=!1;if(a){let u=i[hr];rt(u)&&Kf(u,t)&&(l=!0),c={...i,[hr]:Bf(u,t)}}else{let u=rt(i.mcpServers)?i.mcpServers:{},p=u[hr];rt(p)&&Kf(p,t)&&(l=!0),c={...i,mcpServers:{...u,[hr]:Bf(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)+`
|
|
322
|
+
`;if(n)return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:e.path};try{await Y(e.path,d)}catch(u){return Aa(e,"write",u)}return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:e.path}}o(Vf,"mergeJsonConfig");function Bf(e,t){let n=rt(e)&&rt(e.env)?e.env:{},r={...t.env};for(let[i,s]of Object.entries(n))!(i in r)&&typeof s=="string"&&(r[i]=s);return{command:t.command,args:[...t.args],env:r}}o(Bf,"mergeEntry");function sx(e){return!("mcpServers"in e||!(hr in e))}o(sx,"hasRootShape");function Kf(e,t){if(!rt(e)||e.command!==t.command||!ox(e.args,t.args)||!rt(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}o(Kf,"serverEntriesEqual");function ox(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(ox,"arrayEquals");function rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(rt,"isObject");function Aa(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}o(Aa,"failed");He();import{parse as ax,stringify as cx}from"smol-toml";async function zf(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 ji(e,"read",g)}let i,s="create";if(r===null||r.trim().length===0)i={};else{s="merge";try{let g=ax(r);if(!Pt(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=g}catch(g){return ji(e,"parse",g)}}let a=Pt(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(Pt(c)&&lx(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=Pt(c)&&Pt(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={...i,mcp_servers:{...a,maind:u}},m;try{m=cx(p),m.endsWith(`
|
|
312
323
|
`)||(m+=`
|
|
313
|
-
`)}catch(g){return
|
|
324
|
+
`)}catch(g){return ji(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:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:e.path};try{await Y(e.path,m)}catch(g){return ji(e,"write",g)}return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:e.path}}o(zf,"mergeTomlConfig");function lx(e,t){if(!Pt(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(!Pt(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}o(lx,"tomlServerEntryEqual");function Pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Pt,"isObject");function ji(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}o(ji,"failed");import*as Ge from"node:path";var dx="__STACK__";var ux="__INTENT__";var Ta="https://mcp.maind.dev/mcp",px=`?stack=${dx}&intent=${ux}`;function fx(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(fx,"buildStackAwareEndpoint");var gL=fx(Ta,{stack:["nextjs","supabase"],intent:"mixed"}),yr=`## maind MCP integration \u2014 Mandatory consultation
|
|
314
325
|
|
|
315
326
|
This project uses the maind MCP server (mcp.maind.dev/mcp) as
|
|
316
327
|
authoritative source for vetted coding conventions and lessons. The
|
|
@@ -379,7 +390,7 @@ For non-trivial changes, resolve documentation path in this order:
|
|
|
379
390
|
If no path is discoverable, provide a guided fallback:
|
|
380
391
|
\`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
|
|
381
392
|
|
|
382
|
-
Full tool set + provenance via \`get_conventions\`.`;function
|
|
393
|
+
Full tool set + provenance via \`get_conventions\`.`;function mx(e){return`I want to add the **maind MCP server** to my AI coding agent.
|
|
383
394
|
|
|
384
395
|
- My stack: \`__STACK__\`
|
|
385
396
|
- MCP endpoint: \`${e}\`
|
|
@@ -575,7 +586,7 @@ written config.
|
|
|
575
586
|
|
|
576
587
|
--- Preamble block ---
|
|
577
588
|
|
|
578
|
-
${
|
|
589
|
+
${yr}`}o(mx,"buildAiPromptBody");function gr(e,t,n){let r=n?`
|
|
579
590
|
MAIND_CLIENT_FAMILY="${n}"`:"";return`#!/usr/bin/env bash
|
|
580
591
|
set -euo pipefail
|
|
581
592
|
|
|
@@ -610,7 +621,7 @@ ${n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":""}
|
|
|
610
621
|
config.mcpServers.maind = server;
|
|
611
622
|
fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
|
|
612
623
|
console.log("WROTE " + file);
|
|
613
|
-
NODE`}o(
|
|
624
|
+
NODE`}o(gr,"buildJsonConfigInstaller");function hx(e){return`#!/usr/bin/env bash
|
|
614
625
|
set -euo pipefail
|
|
615
626
|
|
|
616
627
|
CONFIG_FILE="$HOME/.codex/config.toml"
|
|
@@ -663,7 +674,7 @@ if (serverCount !== 1 || envCount !== 1) {
|
|
|
663
674
|
|
|
664
675
|
fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
|
|
665
676
|
console.log("WROTE " + file);
|
|
666
|
-
NODE`}o(
|
|
677
|
+
NODE`}o(hx,"buildCodexTomlInstaller");function gx(e=Ta){let t=`${e}${px}`;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:mx(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
678
|
"mcpServers": {
|
|
668
679
|
"maind": {
|
|
669
680
|
"command": "npx",
|
|
@@ -674,7 +685,7 @@ NODE`}o(U_,"buildCodexTomlInstaller");function H_(e=Ii){let t=`${e}${$_}`;return
|
|
|
674
685
|
}
|
|
675
686
|
}
|
|
676
687
|
}
|
|
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:
|
|
688
|
+
}`,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
689
|
"mcpServers": {
|
|
679
690
|
"maind": {
|
|
680
691
|
"command": "npx",
|
|
@@ -685,13 +696,13 @@ NODE`}o(U_,"buildCodexTomlInstaller");function H_(e=Ii){let t=`${e}${$_}`;return
|
|
|
685
696
|
}
|
|
686
697
|
}
|
|
687
698
|
}
|
|
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:
|
|
699
|
+
}`,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
700
|
command = "npx"
|
|
690
701
|
args = ["-y", "@maind-dev/mcp-bridge"]
|
|
691
702
|
|
|
692
703
|
[mcp_servers.maind.env]
|
|
693
704
|
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:
|
|
705
|
+
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:hx(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
706
|
"mcpServers": {
|
|
696
707
|
"maind": {
|
|
697
708
|
"command": "npx",
|
|
@@ -702,7 +713,7 @@ MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",
|
|
|
702
713
|
}
|
|
703
714
|
}
|
|
704
715
|
}
|
|
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:
|
|
716
|
+
}`,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
717
|
# maind agent-preamble installer \u2014 idempotent. Creates or extends:
|
|
707
718
|
# CLAUDE.md (Claude Code)
|
|
708
719
|
# AGENTS.md (Codex, Windsurf, newer Cursor \u2014 cross-agent standard)
|
|
@@ -719,7 +730,7 @@ set -e
|
|
|
719
730
|
|
|
720
731
|
read -r -d '' MAIND_BLOCK <<'MAIND_PREAMBLE_EOF' || true
|
|
721
732
|
|
|
722
|
-
${
|
|
733
|
+
${yr}
|
|
723
734
|
MAIND_PREAMBLE_EOF
|
|
724
735
|
|
|
725
736
|
mkdir -p .github
|
|
@@ -768,7 +779,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
768
779
|
}
|
|
769
780
|
}
|
|
770
781
|
}
|
|
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:
|
|
782
|
+
}`,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
783
|
"mcpServers": {
|
|
773
784
|
"maind": {
|
|
774
785
|
"command": "npx",
|
|
@@ -779,7 +790,7 @@ echo "same edit into the others to keep the agent's view consistent."`},{id:"cur
|
|
|
779
790
|
}
|
|
780
791
|
}
|
|
781
792
|
}
|
|
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:
|
|
793
|
+
}`,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
794
|
|
|
784
795
|
const mcp = new MultiServerMCPClient({
|
|
785
796
|
maind: {
|
|
@@ -800,15 +811,15 @@ const tools = await mcp.getTools();
|
|
|
800
811
|
"env": {
|
|
801
812
|
"MAIND_MCP_URL": "${t}"
|
|
802
813
|
}
|
|
803
|
-
}`}]}o(
|
|
804
|
-
`:
|
|
805
|
-
`;return await
|
|
814
|
+
}`}]}o(gx,"buildSnippetTemplates");var yL=gx(Ta);He();var yx="## maind MCP integration";function _x(e){return[{key:"preamble:CLAUDE.md",path:Ge.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:Ge.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:Ge.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:Ge.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:Ge.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:Ge.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}o(_x,"buildPreambleTargets");async function qf(e,t=!1){let n=_x(e),r=[];for(let i of n)r.push(await bx(i,t));return r}o(qf,"writePreambleFiles");async function bx(e,t){try{if(e.mayNeedParentDir&&!t&&await Ea(Ge.dirname(e.path)),await Gf(e.path,yx))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 i=r===null||r.length===0?`${yr}
|
|
815
|
+
`:wx(r)+`${yr}
|
|
816
|
+
`;return await Y(e.path,i),{target:e.key,action:r===null?"write":"append",status:r===null?"created":"merged",detail:e.path}}catch(n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"append",status:"failed",detail:r}}}o(bx,"writeOnePreambleFile");function wx(e){return e.endsWith(`
|
|
806
817
|
|
|
807
818
|
`)?e:e.endsWith(`
|
|
808
819
|
`)?e+`
|
|
809
820
|
`:e+`
|
|
810
821
|
|
|
811
|
-
`}o(
|
|
822
|
+
`}o(wx,"ensureTrailingBlankLine");Ma();xn();He();import*as tm from"node:readline";var $t="config:auto_working_paths",Ox=`
|
|
812
823
|
Enable presence enrichment (auto working_paths)?
|
|
813
824
|
With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
|
|
814
825
|
locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
|
|
@@ -817,34 +828,34 @@ before editing the same area. Directory names only: never file contents, never
|
|
|
817
828
|
absolute paths. Server-side these paths are account-private (org members never
|
|
818
829
|
see them) and revocable any time on the dashboard consent page or via
|
|
819
830
|
{"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})`,
|
|
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
|
|
831
|
+
[y/N]: `;async function nm(e){let t=e.configPath??We(),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:$t,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:$t,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??Dx)(e.out,Ox)}else return{target:$t,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:$t,action:"skip",status:"skipped",detail:"user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"};let i={...n,auto_working_paths:!0},s=JSON.stringify(i,null,2)+`
|
|
832
|
+
`;if(e.dryRun)return{target:$t,action:"merge",status:"would-merge",detail:t};try{await Y(t,s,384)}catch(a){return{target:$t,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:$t,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}o(nm,"applyWorkingPathsConsent");async function Dx(e,t){e.write(t);let n=tm.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}o(Dx,"promptYesNoDefaultNo");ce();async function rm(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let i=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),s={};try{s=await i.json()}catch{}return i.ok?s.status!=="exchanged"||typeof s.api_key!="string"||!s.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:s.api_key,plan:s.plan??"unknown"}:{ok:!1,reason:s.error??`http_${i.status}`}}catch(i){return i instanceof Error&&i.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:i instanceof Error?i.message:String(i)}}finally{clearTimeout(r)}}o(rm,"exchangeOneClickToken");async function om(e){let t="browser-pair";if(e.token!==null)try{let s=Px(e.token);return e.dryRun?{apiKey:s,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(fr(),Dt(s),{apiKey:s,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(s){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:im(s)}}}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 s=Oi(e.bridgeVersion),a=await rm({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:s.device_id,label:Tf(),clientMeta:{...s}});if(a.ok)return fr(),Dt(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,sm(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
|
|
833
|
+
`)}let r=n===null?"":` (after exchange failure: ${n})`,i=B();if(i!==null)return{apiKey:i,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let s=await wn(e.bridgeVersion,sm(e));return s===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:s.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${s.plan})${r}`}}}catch(s){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:im(s)}}}}o(om,"pairOrUseToken");function Px(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(Px,"validateTokenShape");function im(e){return e instanceof Error?e.message:String(e)}o(im,"errMessage");function sm(e){return e.out??process.stdout}o(sm,"out");bn();var Mx="install-completed",$x=3e3;async function am(e){if(!e.enabled||e.apiKey===null)return;let t=_n(Mx),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:Fx(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:Lx(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,i=setTimeout(()=>r.abort(),$x);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(i)}}o(am,"postInstallTelemetry");function Lx(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(Lx,"countStatuses");function Fx(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}o(Fx,"parseNodeMajor");wr();var uE="https://mcp.maind.dev/mcp";async function Bm(e){let t=Date.now(),n;try{n=If(e)}catch(k){if(k instanceof Ee)return process.stderr.write(`error: ${k.message}
|
|
834
|
+
`),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw k}if(n.help)return Cf(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,s=Wm.homedir();if(s.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
|
|
835
|
+
`),2;let a;if(n.projectRoot!==null)a=n.projectRoot;else{let k=await Pf(process.cwd());if(k.length===0)a=await Df(process.cwd());else if(k.length===1)a=k[0];else{let x=await $f(k,i);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
836
|
`);for(let S of k)process.stderr.write(` candidate: ${S}
|
|
826
|
-
`);return 2}a=x}}let c=new
|
|
837
|
+
`);return 2}a=x}}let c=new Di,l=(process.env.MAIND_MCP_URL??"").trim()||uE;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
|
|
827
838
|
`),process.stdout.write(`maind install \u2014 project root: ${a}
|
|
828
839
|
`),process.stdout.write(` \u2014 mcp endpoint: ${l}
|
|
829
840
|
|
|
830
|
-
`);let d=await
|
|
841
|
+
`);let d=await om({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
842
|
pairing failed: ${d.result.detail??"unknown"}
|
|
832
843
|
Skipping remaining steps.
|
|
833
|
-
`),c.print(process.stdout),2;let u=
|
|
844
|
+
`),c.print(process.stdout),2;let u=Li({projectRoot:a,homeDir:s,platform:process.platform,env:process.env}),p=$i(u);if(p=Hf(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
845
|
`:`error: no client targets selected (did you skip all of them?)
|
|
835
|
-
`),c.print(process.stdout),2;for(let k of p){let x=
|
|
846
|
+
`),c.print(process.stdout),2;for(let k of p){let x=Uf({mcpUrl:l,clientFamily:k.clientFamilyEnv}),S;k.kind==="json"?S=await Vf(k,x,n.dryRun):S=await zf(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 qf({projectRoot:a,homeDir:s},n.dryRun);for(let x of k)c.add(x)}let m={homeDir:s,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await Qf(m));for(let k of await em(m))c.add(k);c.add(await nm({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let h=Lm();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 am({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
847
|
DRY RUN finished in ${y}s. No files were modified. Re-run without --dry-run to apply.
|
|
837
848
|
`):process.stdout.write(`
|
|
838
849
|
Finished in ${y}s. Restart your MCP client so it picks up the new server entry.
|
|
839
|
-
`);let _=
|
|
850
|
+
`);let _=Ae({entryPath:Te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),w=_.fallbackReason===null?`${vn(_)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${w}
|
|
840
851
|
`),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(tm,"runInstall");hr();import{readFileSync as sx}from"node:fs";import{join as nm}from"node:path";function Hs(e){return e?Math.ceil(e.length/4):0}o(Hs,"estimateTokens");var rm=1e6,Gs=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 sm(e){try{let t=sx(e,"utf8");return t.length>rm?t.slice(0,rm):t}catch{return""}}o(sm,"readFileCapped");function ix(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(ix,"distinctFilePaths");function im(e,t,n,r){try{let s=Hs(n);if(e==="codebase_search"){let i=ix(t);if(i.length===0)return 0;let a=0;for(let c of i)a+=Hs(sm(nm(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=Hs(sm(nm(r,i)));return Math.max(0,a-s)}return 0}catch{return 0}}o(im,"measureLocalToolSaved");gr();hr();import{createHash as hx}from"node:crypto";function Bs(e){return hx("sha256").update(e,"utf8").digest("hex")}o(Bs,"nodeKeyHash");var gx=["module","class","interface","function","method","type_alias","enum","variable"],ka=[{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:gx,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(ka.map(e=>e.name));function J(e){return typeof e=="string"&&e.length>0?e:void 0}o(J,"str");var yx=10;function _x(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>=yx&&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(_x,"aggregateHistoryContext");function Nt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}o(Nt,"num");function ym(e){if(e===void 0)return{repoRoot:pe(),scanDirs:void 0};let t=Us(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}o(ym,"anchorRepo");function _m(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(_m,"dirNotFound");async function wm(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=Xf(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=Us(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=Us(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=ym(J(n.dir));if(r===null)return _m("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=ym(J(n.dir));if(r===null)return _m("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let s=va(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:Bs(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:Bs(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:Bs(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=_x(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(dr(`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:gm,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:Bs(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(wm,"dispatchLocalTool");var Ks=class{constructor(t=Qf,n=null,r=pe){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{o(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return ka}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 wm(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=Yf(a)?`${Jf} (${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=im(t,n,r,this.repoRootCache);this.aggregator.add(s)}catch{}}};Kt();var bx="/mcp-client-metrics-ingest",wx=4e3,vx="codebase_search_tokens_saved";async function vm(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${Un()}${bx}`,n=new AbortController,r=setTimeout(()=>n.abort(),wx);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:vx,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(
|
|
852
|
+
`),g}o(Bm,"runInstall");wr();import{readFileSync as pE}from"node:fs";import{join as Km}from"node:path";function Qi(e){return e?Math.ceil(e.length/4):0}o(Qi,"estimateTokens");var Vm=1e6,es=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 zm(e){try{let t=pE(e,"utf8");return t.length>Vm?t.slice(0,Vm):t}catch{return""}}o(zm,"readFileCapped");function fE(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(fE,"distinctFilePaths");function qm(e,t,n,r){try{let i=Qi(n);if(e==="codebase_search"){let s=fE(t);if(s.length===0)return 0;let a=0;for(let c of s)a+=Qi(zm(Km(r,c)));return Math.max(0,a-i)}if(e==="codebase_snippet"){let s=t?.filePath;if(typeof s!="string"||s.length===0)return 0;let a=Qi(zm(Km(r,s)));return Math.max(0,a-i)}return 0}catch{return 0}}o(qm,"measureLocalToolSaved");gn();wr();import{createHash as mE}from"node:crypto";function ts(e){return mE("sha256").update(e,"utf8").digest("hex")}o(ts,"nodeKeyHash");var hE=["module","class","interface","function","method","type_alias","enum","variable"],Ba=[{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:hE,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."}}}}],Xm=new Set(Ba.map(e=>e.name));function J(e){return typeof e=="string"&&e.length>0?e:void 0}o(J,"str");var gE=10;function yE(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,s=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=gE&&r++,c>i&&(i=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>s&&(s=d)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:s>0?Math.max(0,Math.floor((t-s)/864e5)):0}}o(yE,"aggregateHistoryContext");function Lt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}o(Lt,"num");function Ym(e){if(e===void 0)return{repoRoot:fe(),scanDirs:void 0};let t=Zi(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}o(Ym,"anchorRepo");function Jm(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(Jm,"dirNotFound");async function Zm(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(a=>a.status==="open").length,s=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:s,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${s} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=J(n.for_path);if(i!==void 0){let u=Um(i);if(u===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await 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 s=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(s!==void 0&&s.length>0){let u=new Map,p=[];for(let x of s){let S=Zi(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 ct(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}),i=o(p=>r.findings.filter(m=>m.status===p),"of"),s=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let 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=s.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:s.length,warn_count:a.length,preexisting_count:c.length,findings:[...s,...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 ${s.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${s.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),i,s;if(r!==void 0){let u=Zi(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."};i=u.repoRoot,s=u.repoRelDir===""?void 0:[u.repoRelDir]}else i=fe(),s=void 0;let a=Rt(i,{dirs:s,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:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(u=>u.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(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=Ym(J(n.dir));if(r===null)return Jm("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=Tt(r.repoRoot,{dirs:r.scanDirs,baseRef:J(n.base_ref),includeBaseline:n.include_baseline!==!1}),s="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+s}}case"check_migration_ledger_drift":{let r=Ym(J(n.dir));if(r===null)return Jm("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=ya(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:J(n.remote_db_url)}),s=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=o(p=>i.findings.filter(m=>m.status===p),"of"),c=a("open"),l=a("warn"),d=a("info"),u=s.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:s,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:u,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=J(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:J(n.kind),limit:Lt(n.limit)})).map(s=>({...s,nodeKeyHash:ts(s.nodeKey)}))}case"codebase_trace":{let r=J(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:i,maxDepth:Lt(n.max_depth),limit:Lt(n.limit)})}case"codebase_snippet":{let r=J(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await e.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:ts(r)}}case"codebase_map":return e.getArchitecture({topN:Lt(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:J(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Lt(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language,file:i.filePath,start_line:i.startLine,node_key:i.nodeKey,node_key_hash:ts(i.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:J(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Lt(n.limit)}),i;if(n.include_history!==!1)try{i=yE(await e.fileHistory({since:J(n.since),limit:1}))}catch{i=void 0}let s;try{s=await e.reviewDetectors({baseRef:J(n.since)})}catch(l){s=xe(It(`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:yf,detector_coverage:s.coverage},c=s.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:ts(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...i?{history:i}:{}},verdict_args:{detector_findings:s.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:s.coverage,truncated:s.truncated,block_eligible:c,engines:s.engines,findings:s.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 ${s.findings.length} detector row(s) (${c} block-eligible, coverage ${s.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(s=>typeof s=="string"):void 0,i=await e.fileHistory({paths:r,since:J(n.since),limit:Lt(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(s=>({path:s.path,last_commits:s.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:s.ownership?{top_authors:s.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:s.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(s=>({sha:s.sha,date_iso:s.dateIso,author_name:s.authorName,subject:s.subject,files_touched:s.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}o(Zm,"dispatchLocalTool");var ns=class{constructor(t=Gm,n=null,r=fe){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r}static{o(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Ba}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Xm.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",s=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=await Zm(this.getEngine(),i,s),c=JSON.stringify(a,null,2);return this.recordSavings(i,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=Fm(a)?`${jm} (${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(s=>s&&typeof s=="object"?s.name:void 0).filter(s=>typeof s=="string")),i=this.descriptors().filter(s=>!r.has(s.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=qm(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};bn();var _E="/mcp-client-metrics-ingest",bE=4e3,wE="codebase_search_tokens_saved";async function Qm(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${mr()}${_E}`,n=new AbortController,r=setTimeout(()=>n.abort(),bE);try{let i=await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"x-maind-device-id":e.deviceId,"user-agent":`@maind-dev/mcp-bridge/${e.bridgeVersion}`},body:JSON.stringify({metrics:[{session_id:e.sessionId,metric_key:wE,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await i.text().catch(()=>""),i.ok}catch(i){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${i instanceof Error?i.message:String(i)}
|
|
853
|
+
`),!1}finally{clearTimeout(r)}}o(Qm,"postSavingsMetric");za();is();os();Mn();import{join as nA}from"node:path";var rA="<synthetic>";function Bh(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:nA(gc,yc(e.cwd),`${e.transcript_stem}.jsonl`)}o(Bh,"transcriptPathFromSideChannel");var ms=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 i=await(this.deps.stream??hc)(n,{start:this.offset});for(let s of i.events)if(s.kind==="title"){let a=s.title.trim();a.length>0&&(this.title=a)}else s.kind==="assistant"&&!s.isSidechain&&typeof s.model=="string"&&s.model.length>0&&s.model!==rA&&(this.model=s.model);i.bytesRead>this.offset&&(this.offset=i.bytesRead)}}catch{}let t=null;try{t=this.deps.fallbackModel?.()??null}catch{t=null}return{model:this.model??t,title:this.title}}};import{execFile as iA}from"node:child_process";var sA=8,oA=32;function aA(e){return e.split(`
|
|
854
|
+
`).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,oA)}o(aA,"parsePorcelain");function cA(e,t=sA){let n=[];for(let r of e){let i=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(i.length===0)continue;let s=i.includes("/")?i.slice(0,i.lastIndexOf("/")):i;if(!(s.length===0||n.includes(s))&&(n.push(s),n.length>=t))break}return n}o(cA,"condenseToDirs");async function Kh(e=lA){let t=await e();if(t===null)return null;let n=cA(aA(t));return n.length>0?n:null}o(Kh,"deriveWorkingPaths");async function lA(){return await new Promise(e=>{iA("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}o(lA,"defaultGitStatus");var hI=1,gI=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function yI(e){return gI.includes(e)}o(yI,"isHookSubcommand");var _I=6e4;async function bI(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==B()&&Dt(e),e;let t=B();if(t!==null)return t;let n=await wn(H);return n===null&&(process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
|
|
855
|
+
`),process.exit(1)),n.apiKey}o(bI,"ensureApiKey");async function wI(){let e=await wn(H);return e===null&&(process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
|
|
856
|
+
`),process.exit(1)),e.apiKey}o(wI,"reauth");async function vI(){let e=process.argv.slice(2).find(_=>!_.startsWith("-"));if(e==="install"){let _=process.argv.indexOf("install"),w=process.argv.slice(_+1),k=await Bm(w);process.exit(k)}if(e==="doctor"){let{runDoctor:_}=await Promise.resolve().then(()=>(tg(),eg));process.exit(await _(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:_}=await Promise.resolve().then(()=>(qg(),zg));process.exit(await _())}if(e==="guard"){let _=process.argv.indexOf("guard"),{runGuard:w}=await Promise.resolve().then(()=>(ry(),ny));process.exit(await w(process.argv.slice(_+1)))}if(e==="guard-inject"){let{runGuardInject:_}=await Promise.resolve().then(()=>(ly(),cy));process.exit(await _())}if(e==="guard-gate"){let{runGuardGate:_}=await Promise.resolve().then(()=>(my(),fy));process.exit(await _())}if(e==="guard-stop"){let{runGuardStop:_}=await Promise.resolve().then(()=>(yy(),gy));process.exit(await _())}if(e==="gateway"){let _=process.argv.indexOf("gateway"),{runGateway:w}=await Promise.resolve().then(()=>(t_(),e_));process.exit(await w(process.argv.slice(_+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:_}=await Promise.resolve().then(()=>(Vc(),Kc));process.exit(await _())}if(e==="guard-cross-check"){let{runGuardCrossCheck:_}=await Promise.resolve().then(()=>(Vc(),Kc));process.exit(await _())}if(e==="on-index-refresh"){let{runOnIndexRefresh:_}=await Promise.resolve().then(()=>(Yc(),qc));process.exit(await _())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:_}=await Promise.resolve().then(()=>(Yc(),qc));process.exit(await _())}if(e!==void 0&&yI(e)){let _=await Promise.resolve().then(()=>(Cc(),Mg)),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+`
|
|
857
|
+
`),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(kI(),process.exit(0)),process.argv.includes("--reauth")&&(fr(),await wn(H,process.stdout)===null&&process.exit(1),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
|
|
858
|
+
`),process.exit(0));let t=te(),n=await bI(),r=z(),s=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new es:null,a=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new ns(void 0,s),c=`bridge-${mI()}`,l=o(async()=>{if(!s)return;let _=s.takePending();_.tokens<=0||await Qm({apiKey:n,deviceId:t,sessionId:c,tokensSaved:_.tokens,bridgeVersion:H})},"flushSavings"),d=s?setInterval(()=>{l()},_I):null;d?.unref();let u=null,p=new ss({projectKey:r}),m=new ms({resolvePath:o(()=>Bh(p.sideChannel()),"resolvePath"),fallbackModel:o(()=>p.sideChannel()?.model??null,"fallbackModel")}),h=new rs({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(()=>Kh(),"deriveWorkingPaths"),snapshot:r!==null?dh({projectKey:r}):void 0}),g=h.isEnabled?setInterval(()=>{h.pollActivity()},nh):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 Ci({apiKey:n,deviceId:t,bridgeVersion:H,projectKey:r,localRouter:a,presence:h});u=_;try{await _.run();return}catch(w){if(w instanceof pr&&y<hI){y+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${w.message}; re-authorizing\u2026
|
|
859
|
+
`),n=await wI();continue}throw w}}}finally{d&&clearInterval(d),g&&clearInterval(g),await h.end(),await l()}}o(vI,"main");function kI(){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(`
|
|
860
|
+
`))}o(kI,"printHelp");vI().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
|
|
850
861
|
`),process.exit(1)});
|